-
Notifications
You must be signed in to change notification settings - Fork 0
/
remarkprinter.js
97 lines (76 loc) · 2.66 KB
/
remarkprinter.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
94
95
96
97
// Requires chrome-launcher, sleep-promise, minimist, and chrome-remote-interface
const chromeLauncher = require('chrome-launcher');
const CDP = require('chrome-remote-interface');
var argv = require('minimist')(process.argv.slice(2));
if (!("filename" in argv)) {
showUsage("You must add the filename with --filename.");
}
if (!("ratio" in argv)) {
showUsage("You must add the ratio with --ratio.");
}
if (!("url" in argv)) {
showUsage("You must add the url with --url.");
}
function showUsage(missingParam) {
console.log(missingParam)
console.log("Usage: --filename pathtooutput --ratio [16x9|4x3] --url pageurl")
process.exit()
}
console.log("Writing to " + argv["filename"] + " from page " + argv["url"])
function launchChrome(headless=true) {
return chromeLauncher.launch({
chromeFlags: [
headless ? '--headless' : ''
]
});
}
launchChrome().then(async chrome => {
const protocol = await CDP({port: chrome.port});
// Extract the DevTools protocol domains we need and enable them.
// See API docs: https://chromedevtools.github.io/devtools-protocol/
const {Console, Page} = protocol;
await Promise.all([Console.enable(), Page.enable()]);
await Console.clearMessages();
Console.messageAdded((params) => {
console.log(params.message.text);
});
try {
await Page.enable();
await Page.navigate({url: argv["url"]});
await Page.loadEventFired();
// TODO: Change from hard coded sleep to wait on a completion event
console.log("Sleeping")
var sleep = require('sleep-promise');
await sleep(5000);
console.log("Printing")
printOptions = {
printBackground: true,
marginTop: 0,
marginBottom: 0,
marginLeft: 0,
marginRight: 0
}
if (argv["ratio"] == "16x9") {
printOptions["paperWidth"] = 12.6
printOptions["paperHeight"] = 7.1
} else if (argv["ratio"] == "4x3") {
printOptions["paperWidth"] = 9.46
printOptions["paperHeight"] = 7.1
} else {
throw new Error("Unsupported ratio \"" + argv["ratio"] + "\"")
}
// TODO: Add option for printing specific pages using pageRanges
const {data} = await Page.printToPDF(printOptions);
console.log("Writing")
var fs = require('fs');
fs.writeFileSync(argv["filename"], Buffer.from(data, 'base64'));
console.log("Done writing")
chrome.kill();
} catch (err) {
console.error(err);
} finally {
await client.close();
protocol.close();
chrome.kill();
}
});