-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathpdf.js
More file actions
81 lines (67 loc) · 2.04 KB
/
Copy pathpdf.js
File metadata and controls
81 lines (67 loc) · 2.04 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
"use strict";
const chromium = require("chrome-aws-lambda");
var AWS = require("aws-sdk");
const fs = require("fs");
const path = require("path");
const handlebars = require("handlebars");
AWS.config.update({ region: "us-east-1" });
const s3 = new AWS.S3();
module.exports.pdf = async (event, context, callBack) => {
const data = {
title: " Pdf generation using puppeteer",
text: " Handlebar is awesome!"
}
const executablePath = event.isOffline
? "./node_modules/puppeteer/.local-chromium/mac-674921/chrome-mac/Chromium.app/Contents/MacOS/Chromium"
: await chromium.executablePath;
const file = fs.readFileSync(path.resolve(__dirname, "template.hbs"), 'utf8')
const template = handlebars.compile(file)
const html = template(data)
let browser = null;
try {
browser = await chromium.puppeteer.launch({
args: chromium.args,
defaultViewport: chromium.defaultViewport,
executablePath,
headless: chromium.headless
});
const page = await browser.newPage();
page.setContent(html);
const pdf = await page.pdf({
format: "A4",
printBackground: true,
margin: { top: "1cm", right: "1cm", bottom: "1cm", left: "1cm" }
});
// TODO: Response with PDF (or error if something went wrong )
const response = {
headers: {
"Content-type": "application/pdf",
"content-disposition": "attachment; filename=test.pdf"
},
statusCode: 200,
body: pdf.toString("base64"),
isBase64Encoded: true
};
const output_filename = 'pdf-demo.pdf';
const s3Params = {
Bucket: "pdf-demo-pipesort",
Key: `public/pdfs/${output_filename}`,
Body: pdf,
ContentType: "application/pdf",
ServerSideEncryption: "AES256"
};
s3.putObject(s3Params, err => {
if (err) {
console.log("err", err);
return callBack(null, { error });
}
});
context.succeed(response);
} catch (error) {
return context.fail(error);
} finally {
if (browser !== null) {
await browser.close();
}
}
};