forked from Szpadel/chrome-headless-render-pdf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
431 lines (383 loc) · 14.2 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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
const CDP = require('chrome-remote-interface');
const fs = require('fs');
const cp = require('child_process');
const net = require('net');
const commandExists = require('command-exists');
class StreamReader {
constructor(stream) {
this.data = '';
stream.on('data', (chunk) => {
this.data += chunk.toString();
});
}
}
class RenderPDF {
constructor(options) {
this.setOptions(options || {});
this.chrome = null;
if (this.options.remoteHost) {
this.host = this.options.remoteHost;
this.port = this.options.remotePort;
}
}
selectFreePort() {
return new Promise((resolve) => {
let port = Math.floor(Math.random() * 30000) + 30000;
const server = net.createServer({allowHalfOpen: true});
server.on('listening', () => {
server.close(() => {
resolve(port);
});
});
server.on('error', () => {
port = Math.floor(Math.random() * 30000) + 30000;
server.listen(port);
});
server.listen(port);
})
}
setOptions(options) {
this.options = {
printLogs: def('printLogs', false),
printErrors: def('printErrors', true),
chromeBinary: def('chromeBinary', null),
chromeOptions: def('chromeOptions', []),
remoteHost: def('remoteHost', null),
remotePort: def('remotePort', 9222),
noMargins: def('noMargins', false),
landscape: def('landscape', undefined),
paperWidth: def('paperWidth', undefined),
paperHeight: def('paperHeight', undefined),
includeBackground: def('includeBackground', undefined),
pageRanges: def('pageRanges', undefined),
scale: def('scale', undefined),
displayHeaderFooter: def('displayHeaderFooter', false),
headerTemplate: def('headerTemplate', undefined),
footerTemplate: def('footerTemplate', undefined),
jsTimeBudget: def('jsTimeBudget', 5000),
animationTimeBudget: def('animationTimeBudget', 5000),
};
this.commandLineOptions = {
windowSize: def('windowSize', undefined),
};
function def(key, defaultValue) {
return options[key] === undefined ? defaultValue : options[key];
}
}
static async generateSinglePdf(url, filename, options) {
const renderer = new RenderPDF(options);
await renderer.connectToChrome();
try {
const buff = await renderer.renderPdf(url, renderer.generatePdfOptions());
fs.writeFileSync(filename, buff);
renderer.log(`Saved ${filename}`);
} catch (e) {
renderer.error('error:', e);
}
renderer.killChrome();
}
static async generatePdfBuffer(url, options) {
const renderer = new RenderPDF(options);
await renderer.connectToChrome();
try {
return await renderer.renderPdf(url, renderer.generatePdfOptions());
} catch (e) {
renderer.error('error:', e);
} finally {
renderer.killChrome();
}
}
static async generateMultiplePdf(pairs, options) {
const renderer = new RenderPDF(options);
await renderer.connectToChrome();
for (const job of pairs) {
try {
const buff = await renderer.renderPdf(job.url, renderer.generatePdfOptions());
fs.writeFileSync(job.pdf, buff);
renderer.log(`Saved ${job.pdf}`);
} catch (e) {
renderer.error('error:', e);
}
}
renderer.killChrome();
}
async renderPdf(url, options) {
const client = await CDP({host: this.host, port: this.port});
this.log(`Opening ${url}`);
const {Page, Emulation, LayerTree} = client;
await Page.enable();
await LayerTree.enable();
const loaded = this.cbToPromise(Page.loadEventFired);
const jsDone = this.cbToPromise(Emulation.virtualTimeBudgetExpired);
await Page.navigate({url});
await Emulation.setVirtualTimePolicy({policy: 'pauseIfNetworkFetchesPending', budget: this.options.jsTimeBudget});
await this.profileScope('Wait for load', async () => {
await loaded;
});
await this.profileScope('Wait for js execution', async () => {
await jsDone;
});
await this.profileScope('Wait for animations', async () => {
await new Promise((resolve) => {
setTimeout(resolve, this.options.animationTimeBudget); // max waiting time
let timeout = setTimeout(resolve, 100);
LayerTree.layerPainted(() => {
clearTimeout(timeout);
timeout = setTimeout(resolve, 100);
});
});
});
const pdf = await Page.printToPDF(options);
const buff = Buffer.from(pdf.data, 'base64');
client.close();
return buff;
}
generatePdfOptions() {
const options = {};
if (this.options.landscape !== undefined) {
options.landscape = !!this.options.landscape;
}
if (this.options.noMargins) {
options.marginTop = 0;
options.marginBottom = 0;
options.marginLeft = 0;
options.marginRight = 0;
}
if (this.options.includeBackground !== undefined) {
options.printBackground = !!this.options.includeBackground;
}
if(this.options.paperWidth !== undefined) {
options.paperWidth = parseFloat(this.options.paperWidth);
}
if(this.options.paperHeight !== undefined) {
options.paperHeight = parseFloat(this.options.paperHeight);
}
if(this.options.pageRanges !== undefined) {
options.pageRanges = this.options.pageRanges;
}
if (this.options.displayHeaderFooter !== undefined) {
options.displayHeaderFooter = !!this.options.displayHeaderFooter;
}
if (this.options.headerTemplate !== undefined) {
options.headerTemplate = this.options.headerTemplate;
}
if (this.options.footerTemplate !== undefined) {
options.footerTemplate = this.options.footerTemplate;
}
if(this.options.scale !== undefined) {
let scale = this.options.scale;
if(scale < 0.1) {
console.warn(`scale cannot be lower than 0.1, using 0.1`);
scale = 0.1;
}
if(scale > 2) {
console.warn(`scale cannot be higher than 2, using 2`);
scale = 2;
}
options.scale = scale;
}
return options;
}
error(...msg) {
if (this.options.printErrors) {
console.error(...msg);
}
}
log(...msg) {
if (this.options.printLogs) {
console.log(...msg);
}
}
async cbToPromise(cb) {
return new Promise((resolve) => {
cb((resp) => {
resolve(resp);
})
});
}
getPerfTime(prev) {
const time = process.hrtime(prev);
return time[0] * 1e3 + time[1] / 1e6;
}
async profileScope(msg, cb) {
const start = process.hrtime();
await cb();
this.log(msg, `took ${Math.round(this.getPerfTime(start))}ms`);
}
browserLog(type, msg) {
const lines = msg.split('\n');
for (const line of lines) {
this.log(`(chrome) (${type}) ${line}`);
}
}
async spawnChrome() {
if(!this.port) {
this.port = await this.selectFreePort();
}
const chromeExec = this.options.chromeBinary || await this.detectChrome();
this.log('Using', chromeExec);
const commandLineOptions = [
'--headless',
`--remote-debugging-port=${this.port}`,
'--disable-gpu',
...this.options.chromeOptions,
'about:blank'
];
if (this.commandLineOptions.windowSize !== undefined ) {
commandLineOptions.push(`--window-size=${this.commandLineOptions.windowSize[0]},${this.commandLineOptions.windowSize[1]}`);
}
this.chrome = cp.spawn(
chromeExec,
commandLineOptions
);
const stdout = new StreamReader(this.chrome.stdout);
const stderr = new StreamReader(this.chrome.stderr);
this.chrome.on('close', (code) => {
this.log(`Chrome stopped (${code})`);
this.browserLog('out', stdout.data);
this.browserLog('err', stderr.data);
});
}
async connectToChrome() {
if (!this.options.remoteHost) {
await this.spawnChrome();
}
await this.waitForDebugPort();
}
async isCommandExists(cmd) {
return new Promise((resolve, reject) => {
commandExists(cmd, (err, exists) => {
if (err) {
reject(err);
} else {
resolve(exists);
}
})
});
}
async detectChrome() {
if (await this.isCommandExists('google-chrome-unstable')) {
return 'google-chrome-unstable';
}
if (await this.isCommandExists('google-chrome-beta')) {
return 'google-chrome-beta';
}
if (await this.isCommandExists('google-chrome-stable')) {
return 'google-chrome-stable';
}
if (await this.isCommandExists('google-chrome')) {
return 'google-chrome';
}
if (await this.isCommandExists('chromium')) {
return 'chromium';
}
if (await this.isCommandExists('chromium-browser')) {
return 'chromium-browser';
}
// windows
if (await this.isCommandExists('chrome')) {
return 'chrome';
}
if (await this.isCommandExists('C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe')) {
return 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe';
}
if (await this.isCommandExists('C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe')) {
return 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe';
}
// macos
if (await this.isCommandExists('/Applications/Google\ Chrome\ Canary.app/Contents/MacOS/Google\ Chrome')) {
return '/Applications/Google\ Chrome\ Canary.app/Contents/MacOS/Google\ Chrome';
}
if (await this.isCommandExists('/Applications/Google\ Chrome\ Dev.app/Contents/MacOS/Google\ Chrome')) {
return '/Applications/Google\ Chrome\ Dev.app/Contents/MacOS/Google\ Chrome';
}
if (await this.isCommandExists('/Applications/Google\ Chrome\ Beta.app/Contents/MacOS/Google\ Chrome')) {
return '/Applications/Google\ Chrome\ Beta.app/Contents/MacOS/Google\ Chrome';
}
if (await this.isCommandExists('/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome')) {
return '/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome';
}
throw Error('Couldn\'t detect chrome version installed! use --chrome-binary to pass custom location');
}
killChrome() {
if (!this.options.remoteHost) {
this.chrome.kill(cp.SIGKILL);
}
}
async detectOpenPort() {
if (this.host) {
// Use existing configuration
return await this.isPortOpen(this.host, this.port);
}else {
const v4Host = "127.0.0.1";
const v6Host = "::1";
const v6 = this.isPortOpen(v6Host, this.port);
const v4 = this.isPortOpen(v4Host, this.port);
try {
const ok = await v6;
this.log('Detected ipv6 connection');
this.host = v6Host;
return ok;
}catch(e) {
try {
const ok = await v4;
this.log('Detected ipv4 connection');
this.host = v4Host;
return ok;
}catch(e) {
throw e
}
}
}
}
async waitForDebugPort() {
this.log('Waiting for chrome to became available');
while (true) {
try {
await this.detectOpenPort();
this.log('Chrome port open!');
await this.checkChromeVersion();
return;
} catch (e) {
await this.wait(10);
}
}
}
async checkChromeVersion() {
const client = await CDP({host: this.host, port: this.port});
try {
const {Browser} = client;
const version = await Browser.getVersion();
if (version.product.search('/64.') !== -1) {
this.error(' ===== WARNING =====');
this.error(' Detected Chrome in version 64.x');
this.error(' This version is known to contain bug in remote api that prevents this tool to work');
this.error(' This issue is resolved in version 65');
this.error(' More info: https://github.com/Szpadel/chrome-headless-render-pdf/issues/22');
}
this.log(`Connected to ${version.product}, protocol ${version.protocolVersion}`);
} catch (e) {
this.error(`Wasn't able to check chrome version, skipping compatibility check.`);
}
}
async isPortOpen(host, port) {
return new Promise(function (resolve, reject) {
const connection = new net.Socket();
connection.connect({host, port});
connection.on('connect', () => {
connection.end();
resolve();
});
connection.on('error', () => {
reject();
})
});
}
async wait(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
}
module.exports = RenderPDF;
module.exports.default = RenderPDF;