AWS Lambda HTML to PDF
The Nightmare is Over
Rendering PDF in Lambda took longer than expected. Tutorials exist in both AWS Lambda and the Serverless Framework. Most do not work, though. The wktohtml and phantomJS libraries in nodeJS are problematic. They don't fully support NodeJS 12.X. So fear no more, some people have figured it out.
Headless Chromium to the Rescue
The key is to use the chrome-aws-lambda tooling. The catch is you must install a Lambda layer (instructions exist in the Readme). Serverless provides an easy way to apply layers. You can always manually add one in the Lambda AWS dashboard. Once there, you can write a Lambda function to load a headless browser to perform work.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const chromium = require('chrome-aws-lambda'); | |
module.exports.handler = async (event) => { | |
let browser = null; | |
try { | |
browser = await chromium.puppeteer.launch({ | |
args: chromium.args, | |
defaultViewport: chromium.defaultViewport, | |
executablePath: await chromium.executablePath, | |
headless: chromium.headless | |
}); | |
const page = await browser.newPage(); | |
await page.goto('https://google.com'); | |
const pdf = await page.pdf({format: 'A4'}); | |
return { | |
statusCode: 200, | |
headers: { | |
"Content-type": "application/pdf", | |
"accept-ranges": "bytes", | |
'Access-Control-Allow-Origin': '*', | |
}, | |
body: pdf.toString('base64'), | |
isBase64Encoded : true | |
} | |
} finally { | |
if (browser !== null) { | |
await browser.close(); | |
} | |
} | |
}; |
Comments
Post a Comment