我正在构建带有手把和操纵up的pdf报告,以保存到我的数据库中。 pdf正常运行,除了我似乎无法获取存储在资产目录中的图像以进行加载。我在控制台上记录尝试获取图像时遍历的filePath,并且它们通过了适当的路径。只是不确定为什么不加载图像,需要任何帮助。
到目前为止,这是我的代码。
const puppeteer = require("puppeteer");
const hbs = require("handlebars");
const fs = require("fs-extra");
const path = require("path");
// compiles the handlebars docs
const compile = async (templateName, data) => {
const filePath = path.join(__dirname, "templates", `${templateName}.hbs`);
if (!filePath) {
throw new Error(`Could not find ${templateName}.hbs in generatePDF`);
}
const html = await fs.readFile(filePath, "utf-8");
return hbs.compile(html)(data);
};
// helper for getting the images
hbs.registerHelper("getIntro", (context, idx) => {
const filePath = path.join(
__dirname,
"assets",
`${context}_intro_${idx}.png`
);
return filePath;
});
// use puppeteer to take in compiled hbs doc and create a pdf
const generatePDF = async (fileName, data) => {
const preparedData = prepareDataForPDF(data);
const browser = await puppeteer.launch({
args: ["--no-sandbox"],
headless: true
});
const page = await browser.newPage();
const content = await compile(fileName, preparedData);
await page.goto(`data: text/html;charset=UTF-8, ${content}`, {
waitUntil: "networkidle0"
});
await page.setContent(content);
await page.emulateMedia("screen");
await page.waitFor(100);
const pdf = await page.pdf({
format: "A4",
printBackground: true
});
return pdf;
};
module.exports = generatePDF;
<!-- handlebars partial that handles image loading -->
{{#loop 14}}
<div class="page">
<img src="{{getIntro assessmentType this}}" class="intro-page-content">
</div>
{{/loop}}
<!-- used like this in my main file -->
{{> intro assessmentType="Leadership"}}