使用 Chart.jscanvases 将 HTML 内容导出为 PDF

2022-01-22 00:00:00 javascript chart.js jspdf

我有一个 HTML 页面,其中包含由 chart.js 生成的大约 10 个图表(所以这些是画布元素).我希望能够将页面内容导出为 PDF 文件.

I have an HTML page with around 10 charts generated by chart.js (so these are canvas elements). I want to be able to export the page content into a PDF file.

我尝试过使用 jsPDF 的 .fromHTML 函数,但它似乎不支持导出画布内容.(要么是那个,要么我做错了).我只是做了类似的事情:

I've tried using jsPDF's .fromHTML function, but it doesn't seem to support exporting the canvas contents. (Either that or I'm doing it wrong). I just did something like:

    $(".test").click(function() {
  var doc = new jsPDF()

  doc.fromHTML(document.getElementById("testExport"));
  doc.save('a4.pdf')
});

任何替代方法将不胜感激.

Any alternative approaches would be appreciated.

推荐答案

你应该使用 html2canvas (支持画布导出并更好地表示 html 元素),以及 jsPDF.

You should use html2canvas (to support canvas export and get a better representation of html elements), along with jsPDF.

这是一个例子:

var chart = new Chart(ctx, {
   type: 'line',
   data: {
      labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
      datasets: [{
         label: 'DST',
         data: [3, 1, 4, 2, 5],
         backgroundColor: 'rgba(0, 119, 290, 0.2)',
         borderColor: 'rgba(0, 119, 290, 0.6)',
         fill: false
      }]
   },
   options: {
      scales: {
         yAxes: [{
            ticks: {
               beginAtZero: true,
               stepSize: 1
            }
         }]
      }
   }
});

function saveAsPDF() {
   html2canvas(document.getElementById("chart-container"), {
      onrendered: function(canvas) {
         var img = canvas.toDataURL(); //image data of canvas
         var doc = new jsPDF();
         doc.addImage(img, 10, 10);
         doc.save('test.pdf');
      }
   });
}

#chart-container {
   background: white;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>

<div id="chart-container">
   ChartJS - Line Chart
   <canvas id="ctx"></canvas>
</div><br>
<button onclick="saveAsPDF();">save as pdf</button>

相关文章