-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathurlConverter.js
93 lines (71 loc) · 1.87 KB
/
urlConverter.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
const puppeteer = require('puppeteer');
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function urlToImage(url, options, path) {
const browser = await puppeteer.launch({
defaultViewport: null,
args: [
'--window-size=1366,768'
],
});
const page = await browser.newPage();
await page.goto(url, {
waitUntil: ['load', 'domcontentloaded', 'networkidle0'],
})
await sleep(3000);
const imageBinary = await page.screenshot({ path: 'example.png', fullPage: true });
await browser.close();
return imageBinary
}
async function urlToPDF(url, {
puppeteerOptions,
pdfOptions,
sleepTime = 0,
emulateMediaType = 'screen'
} = {})
{
const puppeteerDefaultOptions = {
defaultViewport: null,
args: [
'--window-size=1366,768'
],
}
const defaultPdfOptions = {
margin: { top: '100px', right: '50px', bottom: '100px', left: '50px' },
printBackground: true,
scale: 0.5,
}
puppeteerOptions = {
...puppeteerDefaultOptions,
...puppeteerOptions
}
pdfOptions = {
...defaultPdfOptions,
...pdfOptions
}
const browser = await puppeteer.launch(puppeteerOptions);
let pdf
try {
const page = await browser.newPage();
await page.goto(url, {
waitUntil: ['load', 'domcontentloaded', 'networkidle0'],
})
if (emulateMediaType) {
await page.emulateMediaType(emulateMediaType);
}
if (sleepTime) {
await sleep(sleepTime);
}
pdf = await page.pdf(pdfOptions);
await browser.close();
} catch (err) {
await browser.close();
throw err
}
return pdf
}
module.exports = {
urlToImage,
urlToPDF
}