我通过使用一个名为html-pdf-chrome的甜蜜 nodeJS 包解决了这个问题,该包通过指示 Chrome 等待超时、要调用的回调函数或页面上的选择器存在来解决这个问题。
我的代码:
const PRINT_OPTIONS = {
clearCache: true,
printOptions: {
scale: 0.6
},
completionTrigger: new HtmlPdf.CompletionTrigger.Timer(5000) // Give it 5000ms to render the HTML
};
async function outputHTMLToPDF(sourceHTML, outputFilename) {
console.log("Printing the html using Chrome...");
let pdf = await HtmlPdf.create(sourceHTML, PRINT_OPTIONS);
console.log("Saving the PDF to " + outputFilename + "...");
await pdf.toFile(path.join(DEFAULT_PRINT_PATH, outputFilename));
});