首页 > 解决方案 > Puppeteer - PDFPrint 但 pdf 为空白

问题描述

我对 puppeteer 和 pdf 打印有疑问。

一切看起来都很好,没有错误代码,...但是 pdf 是空白的。和 templateHtml 很好!也许这是函数调用中的错误 await ?

请帮我 !

async function createPDF(quotation, quoteurl, quotname){

var templateHtml = fs.readFileSync(path.join(process.cwd(), './templates/quotation2.html'), 'utf8');
//console.log(templateHtml);
var template = handlebars.compile(templateHtml);
//console.log(template);
var html = template(quotation);
//console.log(html);



var pdfPath = path.join(`${quoteurl}`, `${quotname}.pdf`);
console.log(pdfPath)

var options = {
    width: '1230px',
    headerTemplate: "<p></p>",
    footerTemplate: "<p></p>",
    displayHeaderFooter: false,
    margin: {
        top: "10px",
        bottom: "30px"
    },
    printBackground: true,
    path: pdfPath
}

const browser = await puppeteer.launch({
    //args: ['--no-sandbox'],
    headless: true
});

var page = await browser.newPage();
console.log('OH YES');
await page.goto(`data:text/html;charset=UTF-8,${html}`,{ waitUntil: ['domcontentloaded', 'load'] }).then(function (response) {
    //    page.emulateMedia('screen')
        page.pdf({ path: pdfPath
        , format: 'letter' })
          .then(function (res) {
            browser.close();
          }).catch(function (e) {
            browser.close();
          })
      })


}

我不明白为什么它不起作用。

标签: node.jspuppeteer

解决方案


我改变了这个内容,它的工作原理!但是 logo.png 没有出现在 pdf 中(或者它与 html 文件位于同一文件夹中。

有什么东西可以添加到 puppeteer 以在 pdf 中包含图像文件吗?(它在 html 文件中声明)

await page.setContent(html,{ waitUntil: ['domcontentloaded', 'load', "networkidle0"] }).then(function (response) {
    //    page.emulateMedia('screen')
        page.pdf({ path: pdfPath,
            format: 'A4',
            printBackground: true,

            margin: {
              top: '20px',
              bottom: '20px',
              right: '20px',
              left: '20px' }})
          .then(function (res) {
            browser.close();
          }).catch(function (e) {
            browser.close();
          })
      })

推荐阅读