本文介绍了使用Chart.jscanvases将HTML内容导出为PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个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 .
这里是一个例子:
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>
这篇关于使用Chart.jscanvases将HTML内容导出为PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!