Last active
June 9, 2024 02:37
-
-
Save BrianLeishman/a59cdcfd2034ed093dd04c75d2ade741 to your computer and use it in GitHub Desktop.
Serverless HTML to PDF with AWS Lambda + Chrome
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
{ | |
"html": "<p>Hello, world!</p>" | |
} |
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'); | |
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