Skip to content

Instantly share code, notes, and snippets.

@fideliocc
Created April 5, 2020 18:26
Show Gist options
  • Save fideliocc/ff292ed58d16a7c21b3bf6c12cba5917 to your computer and use it in GitHub Desktop.
Save fideliocc/ff292ed58d16a7c21b3bf6c12cba5917 to your computer and use it in GitHub Desktop.
PDF Generator Function
'use strict'
const chromium = require('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>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: "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,
headers: {
"Content-Type": "application/json",
"Content-Disposition": "attachment; filename=test.pdf",
"X-Requested-With": '*',
"Access-Control-Allow-Headers": 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Requested-With',
"Access-Control-Allow-Origin": '*',
"Access-Control-Allow-Methods": 'GET, OPTIONS',
"Access-Control-Allow-Credentials": true
},
body: 'Done!',
isBase64Encoded: true
};
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