老实说,这似乎是最简单的方法是只提供了“下载到PDF”链接,弹出浏览器的打印页面,并指导用户选择“打印成PDF”。
如果这种方法对您(或您的用户)不起作用,那么这是一个粗略的方法。
基本上,我们创建了一个新的canvas
元素,它是报表页面的大小,并将您现有的chart.js canvas
图表中的像素递增绘制为新的canvas
。完成后,您可以使用jsPDF
将新画布作为图像添加到PDF文档并下载文件。
下面是一个示例实现。
$('#downloadPdf').click(function(event) {
// get size of report page
var reportPageHeight = $('#reportPage').innerHeight();
var reportPageWidth = $('#reportPage').innerWidth();
// create a new canvas object that we will populate with all other canvas objects
var pdfCanvas = $('<canvas />').attr({
id: "canvaspdf",
width: reportPageWidth,
height: reportPageHeight
});
// keep track canvas position
var pdfctx = $(pdfCanvas)[0].getContext('2d');
var pdfctxX = 0;
var pdfctxY = 0;
var buffer = 100;
// for each chart.js chart
$("canvas").each(function(index) {
// get the chart height/width
var canvasHeight = $(this).innerHeight();
var canvasWidth = $(this).innerWidth();
// draw the chart into the new canvas
pdfctx.drawImage($(this)[0], pdfctxX, pdfctxY, canvasWidth, canvasHeight);
pdfctxX += canvasWidth + buffer;
// our report page is in a grid pattern so replicate that in the new canvas
if (index % 2 === 1) {
pdfctxX = 0;
pdfctxY += canvasHeight + buffer;
}
});
// create new pdf and add our new canvas as an image
var pdf = new jsPDF('l', 'pt', [reportPageWidth, reportPageHeight]);
pdf.addImage($(pdfCanvas)[0], 'PNG', 0, 0);
// download the pdf
pdf.save('filename.pdf');
});
你可以看到它在这个codepen的行动。
现在让我们来讨论一下这种方法的一些问题。首先,您必须控制每个chart.js canvas
在新对象canvas
中的位置。要做到这一点的唯一方法是了解您的报表页面的结构和实现相同的结构。在我的例子中,我的图表是一个2×2的网格,逻辑处理这个相应的。如果你有一个3x2网格或其他不同的东西,那么你将不得不改变定位逻辑。
最后,最终的PDF输出文件尺寸远远大于原始图表页面(来自网页)。我认为这是因为我的图表“容器”div横跨整页。因此,您可能想要使用不同的方法来设置新的canvas
的大小。
长期以来,上述示例旨在演示一种方法,而不是您的最终解决方案。
祝你好运!
谢谢你的例子。它工作完美。 如何添加更多页面,如果内容更多。请帮帮我。 – VSK