forked from rubys/awdwr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
screenshot.js
executable file
·65 lines (53 loc) · 1.82 KB
/
screenshot.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
#!/usr/bin/env node
'use strict';
//
// Use puppeteer to convert a web page to PDF.
//
const path = require('path');
const puppeteer = require(path.resolve(__dirname, 'node_modules/puppeteer'));
const fs = require('fs');
// extract instructions from the argument passed
const params = JSON.parse(process.argv[2]);
console.error(JSON.stringify(params, null, 2));
// form_data is not supported yet
// if an exception is raised asynchronously, shut down
process.on('unhandledRejection', (reason, promise) => {
console.log(reason.stack || reason);
process.exit(1);
});
// convert page to PDF
puppeteer.launch().then(async browser => {
const page = await browser.newPage();
// fetch the page in question
await page.goto(params.uri, {waitUntil: 'networkidle0'});
// fill in forms
if (params.form_data) {
for (const [selector, text] of Object.entries(params.form_data)) {
await page.type(selector, text);
}
}
// optionally submit form
if (params.submit_form) {
if (typeof params.submit_form == "number") {
let element = (await page.$$("*[type=submit]"))[params.submit_form];
await element.click();
} else {
await Promise.all([
page.waitForNavigation({ waitUntil: 'networkidle0' }),
page.click("*[type=submit]")
]);
}
}
// produce the PDF
const pdf = await page.pdf({ ...params.dimensions, pageRanges: '1'});
// replace the content of the output file if anything changes EXCEPT
// for PDF date metadata.
const dest = path.join(params.output_dir, params.filename);
const before = fs.existsSync(dest) ? fs.readFileSync(dest, 'utf8') : '';
const strip = /^\/\w+Date \(D:[-+\d']+\)/gm
if (before.replace(strip, '') !== pdf.toString().replace(strip, '')) {
fs.writeFileSync(dest, pdf, 'utf8');
}
// wait for completion
await browser.close();
});