Export HTML content with Chart.jscanvases to PDF

痞子三分冷 提交于 2020-02-23 03:57:41

问题


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.

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.


回答1:


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

Here is an example :

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>


来源:https://stackoverflow.com/questions/46264021/export-html-content-with-chart-jscanvases-to-pdf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!