-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
62 lines (51 loc) · 1.51 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
const chromium = require("chrome-aws-lambda");
const puppeteer = require("puppeteer-core");
exports.handler = async (event) => {
console.log(event.body);
const eventBody = JSON.parse(event.body);
const executablePath = event.isOffline
? "./node_modules/puppeteer/.local-chromium/mac-674921/chrome-mac/Chromium.app/Contents/MacOS/Chromium"
: await chromium.executablePath;
const browser = await puppeteer.launch({
args: chromium.args,
executablePath
});
try {
const page = await browser.newPage();
const pageLoadOptions = {
waitUntil: ["networkidle0", "load", "domcontentloaded"]
};
if (eventBody.url) {
await page.goto(eventBody.url, pageLoadOptions);
} else if (eventBody.html) {
await page.setContent(eventBody.html, pageLoadOptions);
} else {
return {
statusCode: 400,
headers: {
"Content-type": "application/json",
},
body: JSON.stringify("Must provide either `html` or `url` on the request body")
};
}
const pdfOptions = Object.assign(
{
printBackground: true,
format: 'A4',
margin: { top: '0.4in', right: '0.4in', bottom: '0.4in', left: '0.4in' }
},
eventBody.options
);
const pdfStream = await page.pdf(pdfOptions);
return {
statusCode: 200,
isBase64Encoded: true,
headers: {
"Content-type": "application/pdf"
},
body: pdfStream.toString("base64")
};
} finally {
await browser.close();
}
};