-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.js
More file actions
54 lines (45 loc) · 1.44 KB
/
Copy pathhandler.js
File metadata and controls
54 lines (45 loc) · 1.44 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
const AWS = require('aws-sdk');
const S3 = new AWS.S3();
const chromium = require('@sparticuz/chromium');
const puppeteer = require('puppeteer-core');
module.exports.generatePDF = async (event) => {
const { url } = JSON.parse(event.body);
const bucketName = process.env.PDF_BUCKET;
const ttlSeconds = 60 * 60; // 1 hour
try {
const browser = await puppeteer.launch({
args: chromium.args,
defaultViewport: chromium.defaultViewport,
executablePath: await chromium.executablePath(),
headless: chromium.headless,
});
const page = await browser.newPage();
await page.goto(url, { waitUntil: 'networkidle0' });
const pdfBuffer = await page.pdf({ format: 'A4', printBackground: true });
const timestamp = Date.now();
const pdfKey = `pdfs/${timestamp}.pdf`;
await S3.putObject({
Bucket: bucketName,
Key: pdfKey,
Body: pdfBuffer,
ContentType: 'application/pdf',
ACL: 'private',
Expires: new Date(Date.now() + ttlSeconds * 1000),
}).promise();
const pdfUrl = S3.getSignedUrl('getObject', {
Bucket: bucketName,
Key: pdfKey,
Expires: ttlSeconds,
});
return {
statusCode: 200,
body: JSON.stringify({ pdfUrl }),
};
} catch (error) {
console.error('Error generating the PDF:', error);
return {
statusCode: 500,
body: JSON.stringify({ message: 'Error generating the PDF', error: error.message }),
};
}
};