PDF Generation with Puppeteer and Chart.js Integration

Using Puppeteer to create a PDF that includes a Chart.js graph in a template. Although the HTML shows the graph, the PDF remains blank. See the revised code sample below.

async function buildPdfDocument() {
  try {
    const contextData = { item: 'example' };
    const templateContent = await loadTemplateContent();
    const compileFn = require('handlebars').compile(templateContent);
    const finalHtml = compileFn(contextData);
    const browserSession = await puppeteer.launch({ args: ['--no-sandbox'] });
    const page = await browserSession.newPage();
    await page.setContent(finalHtml);
    await page.pdf({
      path: 'document.pdf',
      format: 'A4',
      margin: { top: '25mm', bottom: '25mm', left: '25mm', right: '25mm' },
      displayHeaderFooter: true,
      headerTemplate: '<div style="text-align:center;"></div>',
      footerTemplate: '<div style="font-size:10px; text-align:right;">Footer note</div>'
    });
    await browserSession.close();
    console.log('PDF creation successful!');
  } catch (error) {
    console.error('Error generating PDF:', error);
  }
}

async function loadTemplateContent() {
  return `
    <html>
      <head>
        <script>// Placeholder for Chart.js library</script>
      </head>
      <body>
        <canvas id="chartCanvas" width="400" height="200"></canvas>
        <script>
          var ctx = document.getElementById('chartCanvas').getContext('2d');
          new Chart(ctx, {
            type: 'bar',
            data: {
              labels: ['Red', 'Blue', 'Green'],
              datasets: [{
                label: 'Votes',
                data: [10, 15, 5],
                backgroundColor: ['red', 'blue', 'green']
              }]
            }
          });
        </script>
      </body>
    </html>
  `;
}

buildPdfDocument();

hey, try add a small wait after page.setContent so the chart js time to render. i had a similar issue with puppetter not loading all external scripts. check you r including proper chart.js library, not just the placeholder. hope this helps!