Once run locally once, you don't need to run it again. The API endpoint will stay the same. You only ever need to deploy if you're making tweaks or changes to the any of the layers, or htmlToPdf directories. You can re-initialise it with
sudo serverless deploy --aws-profile profile_name --region eu-west-2
html-pdf is used to convert html to pdf
- Nodejs
- Install Serverless globally
npm i -g serverlessInstall all dependencies
cd path/to/the/repo
npm installTo run Locally
cd htmlToPdf/
sls offline startMake 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: lambdaThe 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'These are env vars set within. No need to add as an Env var to the S3 bucket.
This only needs to be set for the S3_BUCKET
Step 1. First deploy the layer.
cd layers/
sls deployStep 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
SLS-deploy script help
sudo serverless deploy --aws-profile profile_name --region eu-west-2
serverless.yml contains the deploymentBucket name