-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
65 lines (57 loc) · 1.85 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
const { URL } = require("url");
const puppeteer = require("puppeteer");
let page;
async function getBrowserPage() {
const browser = await puppeteer.launch({
args: [
"--allow-running-insecure-content",
"--disable-background-networking",
"--disable-default-apps",
"--disable-dev-shm-usage",
"--disable-extensions",
"--disable-gpu",
"--disable-new-tab-first-run",
"--disable-notifications",
"--disable-sync",
"--disable-translate",
"--font-render-hinting=none",
"--headless",
"--hide-scrollbars",
"--ignore-certificate-errors",
"--metrics-recording-only",
"--mute-audio",
"--no-default-browser-check",
"--no-first-run",
"--no-sandbox",
"--no-startup-window",
"--no-zygote",
"--safebrowsing-disable-auto-update",
],
});
return browser.newPage();
}
exports.pdfByURL = async (req, res) => {
const acceptedMethods = ["GET", "POST"];
if (acceptedMethods.indexOf(req.method.toUpperCase()) === -1) {
return res
.status(400)
.send(
`invalid HTTP method: ${req.method} (only GET or POST allowed)`
);
}
let parsedUrl = null;
try {
parsedUrl = new URL(req.query.url);
} catch (err) {
return res.status(400).send(`invalid URL: ${req.query.url}`);
}
if (!page) {
page = await getBrowserPage();
}
await page.goto(parsedUrl.toString());
const mediaType = req.query.mediaType || "screen";
await page.emulateMediaType(mediaType);
const pdfBuffer = await page.pdf({ printBackground: true });
res.set("Content-Type", "application/pdf");
res.status(200).send(pdfBuffer);
};