@fibonalabs/pdf-generator
v0.0.1
Published
Converting HTML To PDF using AWS Lambda Functions and Layers with Serverless Framework
Readme
HTML To PDF using AWS Lambda Functions and Layers with Serverless
html-pdf is used to convert html to pdf
Prerequisite
- Nodejs
- Install Serverless globally
npm i -g serverlessGetting Started
Install 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: lambdaSetting Environment
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'Deployment
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 deployExample
- 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)Template Engines
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
More Fonts
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
Reference
- https://github.com/naeemshaikh27/phantom-lambda-fontconfig-pack
