-
Notifications
You must be signed in to change notification settings - Fork 25
/
index.js
executable file
·222 lines (197 loc) · 5.87 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
#!/usr/bin/env node
const puppeteer = require('puppeteer');
const parseUrl = require('url-parse');
const fileUrl = require('file-url');
const isUrl = require('is-url');
// common options for both print and screenshot commands
const commonOptions = {
'sandbox': {
boolean: true,
default: true
},
'timeout': {
default: 30 * 1000,
number: true,
},
'wait-until': {
string: true,
default: 'load'
},
'cookie': {
describe: 'Set a cookie in the form "key:value". May be repeated for multiple cookies.',
type: 'string'
}
};
const argv = require('yargs')
.command({
command: 'print <url> [output]',
desc: 'Print an HTML file or URL to PDF',
builder: {
...commonOptions,
'background': {
boolean: true,
default: true
},
'margin-top': {
default: '6.25mm'
},
'margin-right': {
default: '6.25mm'
},
'margin-bottom': {
default: '14.11mm'
},
'margin-left': {
default: '6.25mm'
},
'format': {
default: 'Letter'
},
'landscape': {
boolean: true,
default: false
},
'display-header-footer': {
boolean: true,
default: false
},
'header-template': {
string: true,
default: ''
},
'footer-template': {
string: true,
default: ''
}
},
handler: async argv => {
try {
await print(argv);
} catch (err) {
console.error('Failed to generate pdf:', err);
process.exit(1);
}
}
}).command({
command: 'screenshot <url> [output]',
desc: 'Take screenshot of an HTML file or URL to PNG',
builder: {
...commonOptions,
'full-page': {
boolean: true,
default: true
},
'omit-background': {
boolean: true,
default: false
},
'viewport': {
describe: 'Set viewport to a given size, e.g. 800x600',
type: 'string'
}
},
handler: async argv => {
try {
await screenshot(argv);
} catch (err) {
console.error('Failed to take screenshot:', err);
process.exit(1);
}
}
})
.demandCommand()
.help()
.argv;
async function print(argv) {
const browser = await puppeteer.launch(buildLaunchOptions(argv));
const page = await browser.newPage();
const url = isUrl(argv.url) ? parseUrl(argv.url).toString() : fileUrl(argv.url);
if (argv.cookie) {
console.error(`Setting cookies`);
await page.setCookie(...buildCookies(argv));
}
console.error(`Loading ${url}`);
await page.goto(url, buildNavigationOptions(argv));
console.error(`Writing ${argv.output || 'STDOUT'}`);
const buffer = await page.pdf({
path: argv.output || null,
format: argv.format,
landscape: argv.landscape,
printBackground: argv.background,
margin: {
top: argv.marginTop,
right: argv.marginRight,
bottom: argv.marginBottom,
left: argv.marginLeft
},
displayHeaderFooter: argv.displayHeaderFooter,
headerTemplate: argv.headerTemplate,
footerTemplate: argv.footerTemplate
});
if (!argv.output) {
await process.stdout.write(buffer);
}
console.error('Done');
await browser.close();
}
async function screenshot(argv) {
const browser = await puppeteer.launch(buildLaunchOptions(argv));
const page = await browser.newPage();
const url = isUrl(argv.url) ? parseUrl(argv.url).toString() : fileUrl(argv.url);
if (argv.viewport) {
const formatMatch = argv.viewport.match(/^(?<width>\d+)[xX](?<height>\d+)$/);
if (!formatMatch) {
console.error('Option --viewport must be in the format ###x### e.g. 800x600');
process.exit(1);
}
const { width, height } = formatMatch.groups;
console.error(`Setting viewport to ${width}x${height}`);
await page.setViewport({
width: parseInt(width),
height: parseInt(height)
});
}
if (argv.cookie) {
console.error(`Setting cookies`);
await page.setCookie(...buildCookies(argv));
}
console.error(`Loading ${url}`);
await page.goto(url, buildNavigationOptions(argv));
console.error(`Writing ${argv.output || 'STDOUT'}`);
const buffer = await page.screenshot({
path: argv.output || null,
fullPage: argv.fullPage,
omitBackground: argv.omitBackground
});
if (!argv.output) {
await process.stdout.write(buffer);
}
console.error('Done');
await browser.close();
}
function buildLaunchOptions({ sandbox }) {
const args = [];
if (sandbox === false) {
args.push('--no-sandbox', '--disable-setuid-sandbox');
}
return {
args
};
}
function buildNavigationOptions({ timeout, waitUntil }) {
return {
timeout,
waitUntil
};
}
function buildCookies({ url, cookie }) {
return [...cookie].map(cookieString => {
const delimiterOffset = cookieString.indexOf(':');
if (delimiterOffset == -1) {
throw new Error('cookie must contain : delimiter');
}
const name = cookieString.substr(0, delimiterOffset);
const value = cookieString.substr(delimiterOffset + 1);
return { name, value, url };
});
}