Skip to content

Instantly share code, notes, and snippets.

@ms2sato
Last active July 7, 2023 01:46
Show Gist options
  • Save ms2sato/1c6ee1238c9d57052ceb27d3e91fbb29 to your computer and use it in GitHub Desktop.
Save ms2sato/1c6ee1238c9d57052ceb27d3e91fbb29 to your computer and use it in GitHub Desktop.
chrome-aws-lamba-layer-pdf
const chromium = require("@sparticuz/chrome-aws-lambda");
const AWS = require('aws-sdk')
const s3 = new AWS.S3();
exports.handler = async (event, context, callback) => {
let browser = null
try {
const ep = await chromium.executablePath
console.log('executable path ', ep)
browser = await chromium.puppeteer.launch({
args: chromium.args,
defaultViewport: chromium.defaultViewport,
executablePath: ep,
headless: chromium.headless,
})
const page = await browser.newPage()
await page.setContent(`<h1>test:日本語:Your awesome PDF report template</h1>`)
const pdf = await page.pdf({
path: '/tmp/pdfReport.pdf', // TAKE ATTENTION!!
format: 'A4',
printBackground: true,
margin: { top: 20, left: 20, right: 20, bottom: 20 },
displayHeaderFooter: true
})
const params = {
Body: Buffer.from(pdf),
Bucket: "ms2sato-test-pdf-store",
ContentType: "application/pdf",
ContentDisposition: 'inline',
Key: "pdfReport.pdf"
}
await s3.putObject(params, (err, data) => {
if (err) {
console.log('Error: ', err)
} else {
console.log('Stored: ', data)
}
})
const httpResponse = {
statusCode: 200,
body: 'Done!',
};
callback(null, httpResponse)
}
catch(error) {
console.log('Error: ', error)
}
finally {
console.log('In the end...')
if (browser !== null) {
await browser.close()
// process.exit()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment