Skip to content

Instantly share code, notes, and snippets.

@duzzifelipe
Created October 3, 2019 14:55
Show Gist options
  • Save duzzifelipe/8e6fc04ac2a9a89c7a5ad183534bcd97 to your computer and use it in GitHub Desktop.
Save duzzifelipe/8e6fc04ac2a9a89c7a5ad183534bcd97 to your computer and use it in GitHub Desktop.
Use puppeteer on aws lambda to render html content and upload a pdf from it to s3
// Setup:
// $ npm i --save aws-sdk@^2.541.0 chrome-aws-lambda@^1.20.0 puppeteer@^1.20.0
//
// Deploy Script:
// $ rm -Rf node_modules
// $ npm install
// $ rm -rf node_modules/puppeteer/.local-chromium/**
// $ rm pack.zip
// $ zip pack.zip index.js -r node_modules/*
// $ aws lambda --region $REGION update-function-code --function-name $LAMBDA_FN_NAME --zip-file fileb://pack.zip
// index.js content
const AWS = require('aws-sdk');
const chromium = require("chrome-aws-lambda");
const s3 = new AWS.S3();
exports.handler = async (event, context, callback) => {
const executablePath = await chromium.executablePath;
const browser = await chromium.puppeteer.launch({
args: chromium.args,
defaultViewport: chromium.defaultViewport,
executablePath: executablePath,
headless: chromium.headless,
});
const page = await browser.newPage();
await page.setContent('<h1>Hello</h1>');
const pdfStream = await page.pdf();
const params = { Bucket: '$BUCKET_NAME', Key: 'testfile.pdf', ContentType: 'application/pdf', Body: pdfStream };
return s3.putObject(params).promise();
};
@duzzifelipe
Copy link
Author

duzzifelipe commented Oct 3, 2019

Customization for pdf rendering a web page (https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pagepdfoptions):

// set a custom width
// render page background
const pdfStream = await page.pdf({ width: '1920px', printBackground: true });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment