-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
74 lines (59 loc) · 1.78 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
const express = require('express');
const puppeteer = require('puppeteer');
const app = express();
function rawBody(req, res, next) {
req.setEncoding('utf8');
req.rawBody = '';
req.on('data', function (chunk) {
req.rawBody += chunk;
});
req.on('end', function () {
next();
});
}
app.use(rawBody);
app.post('/', async (req, res) => {
try {
console.log("Converting...");
const pdf = await generatePDF(req.rawBody);
res.set('Content-Type', 'application/pdf');
res.set('Content-Length', pdf.length);
res.send(pdf);
} catch (e) {
console.error(e);
return res.sendStatus(500);
}
});
app.listen(3000, () => {
console.log('Listening');
});
async function generatePDF(html) {
console.log("Launching browser...");
const browser = await puppeteer.launch({
headless: true,
args: ['--no-sandbox'],
});
try {
console.log("Opening new page...");
const page = await browser.newPage();
page.on('requestfailed', request => {
console.error(`Request failed: url: ${request.url()}, text: ${request.failure().errorText}, method: ${request.method()}`)
});
// Catch console log errors
page.on("pageerror", err => {
console.error(`Page error: ${err}`);
});
page.on('error', err => {
console.error(`Error: ${err}`);
})
console.log("Setting content...");
await page.setContent(html, {'waitUntil': 'networkidle0'});
console.log("Print to PDF...");
return await page.pdf({format: 'A4', printBackground: true});
} catch (e) {
console.error(e);
} finally {
console.log("Close browser...");
await browser.close();
}
}