老實說,這似乎是最簡單的方法是隻提供了「下載到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