我正在使用 puppeteer 和 Handbars 从 html 示例生成 pdf。一切正常,除了图像显示在浏览器中(无头模式),但生成 pdf 时图像消失。我不知道为什么会这样。
这很奇怪,因为我没有收到任何错误,图像(徽标)只是没有出现,只是出现在浏览器视图中。
我通过sample.html中的img标签中的外部链接调用图像。
我给你留下我的代码
文件.json
const puppeteer = require("puppeteer");
const hbs = require("handlebars");
const path = require("path");
const fs = require("fs-extra");
const data = {
date: sale.transaction.createdAt,
time: sale.transaction.createdAt,
raffleDate: sale.transaction.createdAt,
description:
"Zapatos NikeZapatos NikeZapatos NikeZapatos NikeZapatos NikeZapatos NikeZapatos NikeZapatos NikeZapatos Nike",
"name-customer": sale.transaction.customer.firstName,
"lastname-customer": sale.transaction.customer.lastName,
"raffle-code": raffleId,
tickets: ticks,
quantity: tickets.length,
total: sale.transaction.amount,
};
const compile = async (templateName, data) => {
const filePath = path.join(
process.cwd(),
`./controllers/sample-email/${templateName}.html`
);
const html = await fs.readFileSync(filePath, "utf-8");
return hbs.compile(html)(data);
};
(async () => {
try {
const browser = await puppeteer.launch({
headless: false,
});
const page = await browser.newPage();
const content = await compile("sample", data);
await page.setContent(content, { waitUntil: "domcontentloaded" });
await page.addStyleTag({
path: "./controllers/sample-email/sample.css",
});
await page.emulateMediaType("screen");
await page.pdf({
path: "./controllers/sample-email/sample.pdf",
format: "A4",
printBackground: true,
});
} catch (error) {
console.log(error);
}
})();
样本.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="/controllers/sample-email/sample.css" />
<title>Invoice</title>
</head>
<body>
<header>
<section class="logo">
<img src="https://res.cloudinary.com/baltasar-montero-vidaurreta-175/image/upload/v1687201343/algira/thumbnails/ALGIRA.webp"
alt="algira"
/>
</section>
</header>
</body>
</html>
我认为问题出在这里:
{ waitUntil: "domcontentloaded" }
根据 MDN:
当 HTML 文档已完全解析并且所有延迟脚本 ( 和 ) 已下载并执行时,将触发 DOMContentLoaded 事件。它不会等待图像、子帧和异步脚本等其他内容完成加载。
最好等待
load
或networkidle0
。