【问题标题】:Adding graphs to PDFKIT using Chartjs使用 Chartjs 将图形添加到 PDFKIT
【发布时间】:2025-11-24 09:55:02
【问题描述】:

我正在运行一个 NodeJS 应用程序(MongoDB、Express、Vue),我需要使用 PDFKIT 将一些数据导出为 pdf,这些数据也通过 vue 文件以 html 形式显示。

我试图以多种方式向 pdf 添加图表,但我做不到。我的主要重点是创建图像,以便我可以将其传递给 PDFKIT。

我对 ChartJS 的问题是你必须为其提供一个 ctx 元素,但我的代码是从后端的一个 js 文件运行的,我没有 html 元素可以提供它,我也不希望显示此图表(只是为它创建一个图像,所以我可以将图像传递给 PDFKIT)。

我也尝试使用我的 vue 文件中的 html2canvas,但它没有用。

如果有任何想法可以解决我使用 ChartJS 或其他方法的问题,我将不胜感激。

【问题讨论】:

标签: javascript node.js charts pdfkit


【解决方案1】:

您可以使用 Google 图表。通过将其转换为图像并渲染为pdf。

const GoogleChartsNode = require('google-charts-node');

// Define your chart drawing function
function drawChart() {
  const data = google.visualization.arrayToDataTable([
    ['City', '2010 Population',],
    ['New York City, NY', 8175000],
    ['Los Angeles, CA', 3792000],
    ['Chicago, IL', 2695000],
    ['Houston, TX', 2099000],
    ['Philadelphia, PA', 1526000]
  ]);

  const options = {
    title: 'Population of Largest U.S. Cities',
    chartArea: {width: '50%'},
    hAxis: {
      title: 'Total Population',
      minValue: 0
    },
    vAxis: {
      title: 'City'
    }
  };

  const chart = new google.visualization.BarChart(container);
  chart.draw(data, options);
}

// Render the chart to image
const image = await GoogleChartsNode.render(drawChart);

更多信息请参考:Server-side image rendering for Google Charts by quickchart.io

【讨论】:

  • 将变量添加到您的 doc.image(image) 方法中