Skip to content

Instantly share code, notes, and snippets.

@BrianLeishman
Last active June 9, 2024 02:37
Show Gist options
  • Save BrianLeishman/a59cdcfd2034ed093dd04c75d2ade741 to your computer and use it in GitHub Desktop.
Save BrianLeishman/a59cdcfd2034ed093dd04c75d2ade741 to your computer and use it in GitHub Desktop.
Serverless HTML to PDF with AWS Lambda + Chrome
{
"html": "<p>Hello, world!</p>"
}
const chromium = require('chrome-aws-lambda');
const fs = require('fs');
exports.handler = async (event, context, callback) => {
let result = null;
let browser = null;
try {
browser = await chromium.puppeteer.launch({
args: chromium.args,
defaultViewport: chromium.defaultViewport,
executablePath: await chromium.executablePath,
headless: chromium.headless,
ignoreHTTPSErrors: true,
});
// this guarantees that the file won't conflict with other files
// that could possibly be generated at the same time
//
// this is assuming of course that the file system in lambda
// is shared and that we don't want name conflicts to occur
// if the function is invoked at the same time
let fileName = Date.now();
fs.writeFileSync(`/tmp/${fileName}.html`, event.html);
const page = await browser.newPage();
await page.goto(`file:///tmp/${fileName}.html`);
const pdf = await page.pdf({
displayHeaderFooter: false,
printBackground: true,
margin: {
'top': '0.4in',
'bottom': '0.4in',
'left': '0.4in',
'right': '0.4in'
}
});
result = pdf.toString('base64');
} catch (error) {
return callback(error);
} finally {
if (browser !== null) {
await browser.close();
}
}
return callback(null, result);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment