我正在 NodeJs 中使用 puppeteer 创建 PDF 文件。我用车把渲染模板,并通过复杂的方式传递变量,以便车把获取它们。
以下代码是我目前拥有的代码:
const browser = await puppeteer.launch({
headless: 'new',
// `headless: true` (default) enables old Headless;
// `headless: 'new'` enables new Headless;
// `headless: false` enables “headful” mode.
});
const page = await browser.newPage();
// Compila la plantilla Handlebars
const compiledTemplate = handlebars.compile(template);
// Renderiza la plantilla Handlebars con los datos necesarios
const html = compiledTemplate({ datos: datos });
await page.goto('data:text/html,' + encodeURIComponent(html), { waitUntil: 'networkidle0' });
// Agrega el archivo JavaScript al contexto de la página web
await page.addScriptTag({ path: __dirname + '/../public/js/plotly-2.20.0.min.js' });
await page.addScriptTag({ path: __dirname + '/../public/js/GRAPH/PDF/' + nameFilePPV_L + '.js' });
await page.addScriptTag({ path: __dirname + '/../public/js/GRAPH/PDF/' + nameFilePPV_T + '.js' });
await page.addScriptTag({ path: __dirname + '/../public/js/GRAPH/PDF/' + nameFilePPV_V + '.js' });
await page.addScriptTag({ path: __dirname + '/../public/js/GRAPH/PDF/' + nameFileVSUM + '.js' });
if (SwitchPPV_L === "on") {
console.log("SwitchPPV_L: " + SwitchPPV_L)
await page.evaluate(() => {
setGrafico_ppv_l();
});
}
if (SwitchPPV_T === "on") {
console.log("SwitchPPV_T: " + SwitchPPV_T)
await page.evaluate(() => {
setGrafico_ppv_t();
});
}
if (SwitchPPV_V === "on") {
console.log("SwitchPPV_V: " + SwitchPPV_V)
await page.evaluate(() => {
setGrafico_ppv_v();
});
}
if (SwitchVSUMALL === "on") {
console.log("SwitchVSUMALL: " + SwitchVSUMALL)
await page.evaluate(() => {
setGrafico_vsum();
});
}
const pdf = await page.pdf({ format: 'A5', printBackground: true });
await browser.close();
fs.promises.unlink(__dirname + '/../public/js/GRAPH/PDF/' + nameFilePPV_L + '.js')
fs.promises.unlink(__dirname + '/../public/js/GRAPH/PDF/' + nameFilePPV_T + '.js')
fs.promises.unlink(__dirname + '/../public/js/GRAPH/PDF/' + nameFilePPV_V + '.js')
fs.promises.unlink(__dirname + '/../public/js/GRAPH/PDF/' + nameFileVSUM + '.js')
res.contentType('application/pdf');
res.send(pdf);
代码可以工作,但是当我在 hbs 模板中添加条件时,代码会抛出以下错误,表明它找不到定义的帮助程序。如何访问助手以便 puppeteer 可以正确渲染 hbs 模板?
车把模板
{{#if (test datos.SwitchPPV_L)}}
<h1>True SwitchPPV_L</h1>
{{else}}
<h1>False</h1>
{{/if}}
助手测试
helpers.test = (SwitchPPV_L) => {
if (SwitchPPV_L === "on") {
return true
}else{
return false
}
}
日志:
Error: Missing helper: "test"
我无法运行您的示例代码,因为它不完整(有许多未定义的变量),但这是一个完全可运行的示例,您希望可以将其转换为您的用例。具体来说,它将
test
助手注册到 Handlebars 以避免“缺少助手”错误。
const datos = {SwitchPPV_L: "on"};
Handlebars.registerHelper("test", SwitchPPV_L => SwitchPPV_L === "on");
const html = document.querySelector("#template").innerHTML;
const template = Handlebars.compile(html);
document.body.innerHTML = template({datos});
<script id="template" type="text/x-handlebars-template">
{{#if (test datos.SwitchPPV_L)}}
<h1>True SwitchPPV_L</h1>
{{else}}
<h1>False</h1>
{{/if}}
</script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/handlebars.js"></script>
使用 Puppeteer 和 Express:
const express = require("express"); // ^14.18.2
const Handlebars = require("handlebars"); // ^4.7.8
const puppeteer = require("puppeteer"); // ^21.4.1
const html = `{{#if (test datos.SwitchPPV_L)}}
<h1>True SwitchPPV_L</h1>
{{else}}
<h1>False</h1>
{{/if}}`;
const app = express();
app.set("port", process.env.PORT || 3001)
app.get("/", async (req, res) => {
let browser;
try {
browser = await puppeteer.launch({headless: "new"});
const [page] = await browser.pages();
const datos = {SwitchPPV_L: "on"};
Handlebars.registerHelper("test", SwitchPPV_L => SwitchPPV_L === "on");
const template = Handlebars.compile(html);
await page.setContent(template({datos}));
const pdf = await page.pdf();
res.contentType("application/pdf");
// optionally:
res.setHeader(
"Content-Disposition",
"attachment; filename=test.pdf"
);
res.send(pdf);
}
catch (err) {
res.sendStatus(500);
}
finally {
await browser?.close();
}
});
app.listen(
app.get("port"),
() => console.log(`running on ${app.get("port")}`)
);