使用 Chart.js 的 Puppeteer

o..*_*..o 1 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();
Run Code Online (Sandbox Code Playgroud)

谢谢

ty.*_*ty. 9

您需要让 Puppeteer 等待 Javascript 执行并渲染图形。

您可以提供一个waitUntil选项page.setContentdoc):

await page.setContent(reuslt, {
    waitUntil: ["load","networkidle0"]
});
Run Code Online (Sandbox Code Playgroud)

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

您还没有共享您的 HTML/Javascript,所以我不能肯定地说,但如果您的 Javascript 仍未执行,那么您可以等待waitForFunction图表加载。有关详细信息,请参阅此答案