-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhtml-render.js
More file actions
94 lines (85 loc) · 2.52 KB
/
Copy pathhtml-render.js
File metadata and controls
94 lines (85 loc) · 2.52 KB
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
import puppeteer from "puppeteer";
import Promise from "bluebird";
import hb from "handlebars";
import crypto from "node:crypto";
// import inlineCss from "inline-css"; // если нужно
function hash(str) {
return crypto.createHash("sha256").update(str).digest("hex");
}
let cache = {};
let browser;
export async function init(options) {
let args = ["--no-sandbox", "--disable-setuid-sandbox"];
if (options.args) {
args = options.args;
delete options.args;
}
browser = await puppeteer.launch({
args,
headless: options.puppeteer?.headless ?? true,
});
}
async function run(file, options) {
if (file.content) {
let h = hash(file.content);
if (cache[h]) return cache[h];
const page = await browser.newPage();
const data = file.content; // await inlineCss(file.content, { url: "/" })
console.log("Compiling the template with handlebars");
const template = hb.compile(data, { strict: true });
const html = template(data);
await page.setContent(html, {
waitUntil: "networkidle0",
timeout: options.puppeteer?.wait_timeout ?? 60000,
});
try {
await page.waitForFunction("window.wait <= 0", {
timeout: options.puppeteer?.wait_timeout ?? 60000,
});
} catch {
// игнорируем timeout
}
cache[h] = page;
return page;
} else {
let h = hash(file.url);
if (cache[h]) return cache[h];
const page = await browser.newPage();
await page.goto(file.url, {
waitUntil: ["load", "networkidle0"],
});
cache[h] = page;
return page;
}
}
/**
* Генерация одного PDF
* @param {Object} file { content?: string, url?: string }
* @param {Object} options опции Puppeteer
* @param {Function} [callback] колбэк
* @returns {Promise<Buffer>}
*/
export async function generatePdf(file, options, callback) {
const page = await run(file, options);
return Promise.props(page.pdf(options))
.then(async function (data) {
return Buffer.from(Object.values(data));
})
.asCallback(callback);
}
/**
* Генерация одного
* @param {Object} file { content?: string, url?: string }
* @param {Object} options опции Puppeteer
* @returns {Promise<string>}
*/
export async function generateHtml(file, options) {
const page = await run(file, options);
return page.evaluate(() => {
document.querySelectorAll("script").forEach(s => s.remove());
return document.documentElement.outerHTML;
})
}
export async function close() {
await browser.close();
}