forked from JarvusInnovations/puppeteer-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·101 lines (91 loc) · 2.59 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
#!/usr/bin/env node
const puppeteer = require('puppeteer');
const parseUrl = require('url-parse');
const fileUrl = require('file-url');
const isUrl = require('is-url');
const argv = require('yargs')
.command({
command: 'print <input> <output>',
desc: 'Print an html file to pdf',
builder: {
background: {
default: true
},
marginTop: {
default: '6.25mm'
},
marginRight: {
default: '6.25mm'
},
marginBottom: {
default: '14.11mm'
},
marginLeft: {
default: '6.25mm'
},
format: {
default: 'Letter'
},
landscape: {
boolean: true,
default: false
}
},
handler: async argv => {
try {
await print(argv);
} catch (err) {
console.error('Failed to generate pdf:', err);
process.exit(1);
}
}
}).command({
command: 'screenshot <input> <output>',
desc: 'Take screenshot of an html file',
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();
const page = await browser.newPage();
const url = isUrl(argv.input) ? parseUrl(argv.input).toString() : fileUrl(argv.input);
console.log(`Loading ${url}`);
await page.goto(url);
console.log(`Writing ${argv.output}`);
await page.pdf({
path: argv.output,
format: argv.format,
landscape: argv.landscape,
printBackground: argv.background,
margin: {
top: argv.marginTop,
right: argv.marginRight,
bottom: argv.marginBottom,
left: argv.marginLeft
}
});
console.log('Done');
await browser.close();
}
async function screenshot(argv) {
const browser = await puppeteer.launch();
const page = await browser.newPage();
const url = isUrl(argv.input) ? parseUrl(argv.input).toString() : fileUrl(argv.input);
console.log(`Loading ${url}`);
await page.goto(url);
console.log(`Writing ${argv.output}`);
await page.screenshot({
path: argv.output
});
console.log('Done');
await browser.close();
}