html-pdf is used to convert html to pdf
- Nodejs
- Install Serverless globally
npm i -g serverless
Install all dependencies
cd path/to/the/repo
npm install
To run Locally
cd htmlToPdf/
sls offline start
Make sure the following lines are commented to run locally
htmlToPdf/handler.js
pdf.create(html, {
format: "Letter",
orientation: "portrait",
// phantomPath: '/opt/phantomjs_linux-x86_64'
}).toBuffer((err, buffer) => {
if (err) {
reject(err)
} else {
resolve(buffer)
}
});
htmlToPdf/serverless.yml
htmlToPdf:
handler: handler.htmlToPdf
# layers:
# - ${cf:executables-layer-${self:provider.stage}.HtmlToPdfLayerExport}
events:
- http:
path: api/htmltopdf
method: get
cors: true
integration: lambda
The following environment variables must be set before the function. If not set the pdf will not be generated or else the pdf will contain black dots.
process.env.PATH = `${process.env.PATH}:/opt`
process.env.FONTCONFIG_PATH = '/opt'
process.env.LD_LIBRARY_PATH = '/opt'
Step 1. First deploy the layer.
cd layers/
sls deploy
Step 2. Deploy the main service that will be converting html to pdf
cd htmlToPdf/
sls deploy
- Plain HTML
let html = `<h1>This is a example to convert html to pdf<h1>`
let file = await exportHtmlToPdf(html)
- With Template Engine(hbs)
import handlebars from 'handlebars'
let html = `<h1>This is a example to convert html to pdf</h1><br /><b>{{template}}</b>`
html = handlebars.compile(html)({ template: 'HBS' })
let file = await exportHtmlToPdf(html)
To generate HTML with dynamic data there are some popular template engines like hbs, pug, Mustache, ejs, etc.
For list of template engines visit Template Engines
For more fonts add .ttf font files in executable folder and redeploy the layer and the redeploy the other service so the function is pointing to the latest Lambda Layer