问题描述
我正在尝试将html转换为pdf,我想在其中传递一些动态值,此后,当我使用此代码并创建了外部html文件时,我想生成一个pdf。转换pdf,这是该代码
invoice.html
<!DOCTYPE html>
<html lang="en">
<head>
<Meta charset="UTF-8" />
<Meta name="viewport" content="width=device-width,initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h2>Approve Page,</h2>
</body>
</html>
这是pdf.js文件
const fs = require("fs");
const path = require("path");
const utils = require("util");
const puppeteer = require("puppeteer");
const hb = require("handlebars");
const readFile = utils.promisify(fs.readFile);
async function getTemplateHtml() {
console.log("Loading template file in memory");
try {
const invoicePath = path.resolve("./invoice.html");
return await readFile(invoicePath,"utf8");
} catch (err) {
console.log(err);
}
}
async function generatePdf() {
let data = {};
getTemplateHtml()
.then(async (res) => {
console.log("Compiing the template with handlebars");
const template = hb.compile(res,{ strict: true });
const result = template(data);
const html = result;
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setContent(html);
await page.pdf({ path: "invoice.pdf",format: "A4" });
await browser.close();
console.log("PDF Generated");
return;
})
.catch((err) => {
console.error(err);
});
}
generatePdf();
但是我想以这种方式实现
const fs = require("fs");
const path = require("path");
const utils = require("util");
const puppeteer = require("puppeteer");
const hb = require("handlebars");
const readFile = utils.promisify(fs.readFile);
const A = "invoice";
const html = `<!DOCTYPE html>
<html lang="en">
<head>
<Meta charset="UTF-8" />
<Meta name="viewport" content="width=device-width,${A}</h2>
</body>
</html>
`;
async function getTemplateHtml() {
console.log("Loading template file in memory");
try {
return await readFile(html,"text/html utf8");
} catch (err) {
console.log(err);
}
}
async function generatePdf() {
let data = {};
getTemplateHtml()
.then(async (res) => {
console.log("Compiing the template with handlebars");
const template = hb.compile(res,format: "A4" });
await browser.close();
console.log("PDF Generated");
return;
})
.catch((err) => {
console.error(err);
});
}
generatePdf();
但收到此错误
消息: '您必须将字符串或Handlebars AST传递给Handlebars.compile。您通过了未定义”, 名称:“错误”,
解决方法
我能够用很少的代码解决此问题,但想问一问是否有可能将其转换为base64而不是创建pdf文件。 这是解决方案
const fs = require("fs");
const path = require("path");
const utils = require("util");
const puppeteer = require("puppeteer");
const hb = require("handlebars");
const readFile = utils.promisify(fs.readFile);
(async () => {
const A = "invoice";
const htmlContent = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h2>Approve Page,${A}</h2>
</body>
</html>
`;
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setContent(htmlContent);
await page.pdf({ path: "html.pdf",format: "A4" });
await browser.close();
})();