Skip to content

Instantly share code, notes, and snippets.

@studds
Created April 21, 2020 07:11
Show Gist options
  • Save studds/3913affa99981dd881ebaebde84c7cf2 to your computer and use it in GitHub Desktop.
Save studds/3913affa99981dd881ebaebde84c7cf2 to your computer and use it in GitHub Desktop.
// NB: I'd normally deploy this using CloudFormation
/*
The lambda needs the following configuration:
- A bunch of memory probably 2GB
- Better to have a long timeout just in case
- Must include the following later:
- nodejs10.x (or a newer layer - but haven't tested)
- BUCKET_NAME environment variable
- Permissions to access BUCKET_NAME
*/
const chromium = require('chrome-aws-lambda');
const puppeteer = chromium.puppeteer;
const { S3 } = require('aws-sdk');
const s3 = new S3();
exports.handler = async event => {
console.log(event.url);
const buffer = await toPdf(event.url);
console.log('got buffer');
await s3
.putObject({
Bucket: process.env.BUCKET_NAME,
Key: 'image.png', // todo: determine the key dynamically, based on the provided URL
Body: buffer
})
.promise();
console.log('wrote to s3');
// TODO implement
const response = {
statusCode: 200,
body: JSON.stringify('Hello from Lambda!')
};
return response;
};
('use strict');
async function toPdf(url) {
let browser;
let buffer;
let error;
try {
browser = await puppeteer.launch({
args: chromium.args,
defaultViewport: chromium.defaultViewport,
executablePath: await chromium.executablePath,
headless: true
});
const page = await browser.newPage();
await page.goto(url, { waitUntil: 'networkidle0' });
buffer = await page.pdf({ format: 'A4' });
} catch (err) {
error = err;
} finally {
if (browser) {
await browser.close();
}
}
if (error) {
throw error;
}
if (!buffer) {
throw new Error('Oh no! Did not get the pdf!');
}
return buffer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment