-
Notifications
You must be signed in to change notification settings - Fork 119
/
index.js
94 lines (86 loc) · 2.67 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
const puppeteer = require('puppeteer');
var Promise = require('bluebird');
const hb = require('handlebars')
const inlineCss = require('inline-css')
module.exports
async function generatePdf(file, options, callback) {
// we are using headless mode
let args = [
'--no-sandbox',
'--disable-setuid-sandbox',
];
if(options.args) {
args = options.args;
delete options.args;
}
const browser = await puppeteer.launch({
args: args
});
const page = await browser.newPage();
if(file.content) {
data = await inlineCss(file.content, {url:"/"});
console.log("Compiling the template with handlebars")
// we have compile our code with handlebars
const template = hb.compile(data, { strict: true });
const result = template(data);
const html = result;
// We set the page content as the generated html by handlebars
await page.setContent(html, {
waitUntil: 'networkidle0', // wait for page to load completely
});
} else {
await page.goto(file.url, {
waitUntil:[ 'load', 'networkidle0'], // wait for page to load completely
});
}
return Promise.props(page.pdf(options))
.then(async function(data) {
await browser.close();
return Buffer.from(Object.values(data));
}).asCallback(callback);
}
async function generatePdfs(files, options, callback) {
// we are using headless mode
let args = [
'--no-sandbox',
'--disable-setuid-sandbox',
];
if(options.args) {
args = options.args;
delete options.args;
}
const browser = await puppeteer.launch({
args: args
});
let pdfs = [];
const page = await browser.newPage();
for(let file of files) {
if(file.content) {
data = await inlineCss(file.content, {url:"/"})
console.log("Compiling the template with handlebars")
// we have compile our code with handlebars
const template = hb.compile(data, { strict: true });
const result = template(data);
const html = result;
// We set the page content as the generated html by handlebars
await page.setContent(html, {
waitUntil: 'networkidle0', // wait for page to load completely
});
} else {
await page.goto(file.url, {
waitUntil: 'networkidle0', // wait for page to load completely
});
}
let pdfObj = JSON.parse(JSON.stringify(file));
delete pdfObj['content'];
pdfObj['buffer'] = Buffer.from(Object.values(await page.pdf(options)));
pdfs.push(pdfObj);
}
return Promise.resolve(pdfs)
.then(async function(data) {
await browser.close();
return data;
}).asCallback(callback);
}
module.exports.generatePdf = generatePdf;
module.exports.generatePdfs = generatePdfs;