带有Chart.js的木偶

时间:2020-09-01 16:54:27

标签: javascript chart.js puppeteer

我正在尝试使用Puppeteer生成PDF并在其中插入Chart.js图(但整个PDF应该基于文本,而不是网页屏幕截图)。当我打开模板时,可以看到图形已加载,但是在PDF中,只有空白。 我是这样生成的:

async function generatePdf() {
  let data = { value: "myValue" };
  getTemplateHtml()
    .then(async (res) => {
      // Now we have the html code of our template in res object
      // you can check by logging it on console
      // console.log(res)
      console.log("Compiing the template with handlebars");
      const template = hb.compile(res, { strict: true });
      // we have compile our code with handlebars
      const result = template(data);
      // We can use this to add dyamic data to our handlebas template at run time from database or API as per need. you can read the official doc to learn more https://handlebarsjs.com/
      const html = result;
      // we are using headless mode
      const browser = await puppeteer.launch({ args: ["--no-sandbox"] });
      const page = await browser.newPage();
      // We set the page content as the generated html by handlebars
      await page.setContent(html);
      // We use pdf function to generate the pdf in the same folder as this file.
      await page.pdf({
        path: "output2.pdf",
        format: "A4",
        displayHeaderFooter: true,
        margin: {
          top: "2.5cm",
          right: "2.5cm",
          bottom: "2.5cm",
          left: "2.5cm",
        },
        headerTemplate: "<div></div>",
        footerTemplate:
          '<div style="width: 100%; font-size: 11px !important; overflow: auto; margin-left: 2.5cm; margin-right: 2.5cm; color: ghostwhite;"><span>TEST</span><a href="http://test.com" style="float: right; color: #1E90FF; text-decoration: none;">www.test.com</a></div>',
      });
      await browser.close();
      console.log("PDF Generated");
    })
    .catch((err) => {
      console.error(err);
    });
}
generatePdf();

谢谢

1 个答案:

答案 0 :(得分:2)

您需要让Puppeteer等待Javascript执行并呈现图形。

您可以为waitUntildoc)提供page.setContent选项:

await page.setContent(reuslt, {
    waitUntil: ["load","networkidle0"]
});

此外,您应该通过将options.animation.duration设置为0来禁用图表上的动画。

您尚未共享HTML / Javascript,因此无法确定,但是如果您的Javascript仍未执行,则可以使用waitForFunction来等待图形加载。有关详细信息,请参见this answer