如何在没有浏览器的情况下在nodejs上创建条形图图像?

问题描述 投票:0回答:1

有一个使用 PDF 生成器的 Nodejs 项目,需要将条形图粘贴到其中,但该项目运行在无桌面服务器上。

有任何库或方法可以在运行时在nodejs上创建条形图图像,而无需使用Web浏览器将其粘贴到pdf文件中吗?

我使用

puppeteer
创建 PDF,但
Chart.js
库无法渲染画布,例如:

await page.setContent(`<!DOCTYPE html>
<html><body>
<canvas id="chart"></canvas>
<script>
    const ctx = document.getElementById('chart');

    new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
            datasets: [{
                label: '# of Votes',
                data: [12, 19, 3, 5, 2, 3],
                borderWidth: 1
            }]
        },
        options: {
            scales: { y: { beginAtZero: true } }
        }
    });
</script>
</body></html>`,
{ waitUntil: 'domcontentloaded' });

await page.addScriptTag({ url: 'https://cdn.jsdelivr.net/npm/chart.js' })

结果是一个空白页。这就是为什么我正在寻找更好的选项来生成简单图像并直接粘贴。

javascript node.js charts chart.js puppeteer
1个回答
0
投票

您将在运行依赖于该脚本的chart.js 代码后添加该脚本。先尝试添加脚本:

const puppeteer = require("puppeteer"); // ^22.6.0

const html = `<!DOCTYPE html>
<html><body>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="chart"></canvas>
<script>
    const ctx = document.getElementById('chart');
    new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
            datasets: [{
                label: '# of Votes',
                data: [12, 19, 3, 5, 2, 3],
                borderWidth: 1
            }]
        },
        options: {
            scales: { y: { beginAtZero: true } },
            animation: { duration: 0 },
        }
    });
</script>
</body></html>`;

let browser;
(async () => {
  browser = await puppeteer.launch();
  const [page] = await browser.pages();
  await page.setContent(html);
  await page.pdf({path: "test.pdf",});
})()
  .catch(err => console.error(err))
  .finally(() => browser?.close());

请注意,我还禁用了动画,因此屏幕截图捕获的是最终图表,而不是正在进行的渲染。

另请参阅:

© www.soinside.com 2019 - 2024. All rights reserved.