2017-03-31 73 views
0

我已經使用chart.js來生成具有多個圖表的報表頁面。我需要將此報告導出爲PDF。有很多解決方案可以通過搜索,但我找不到一個具有多個畫布元素的解決方案。帶有多個chart.js圖表​​的頁面到pdf

唯一可用的解決方案似乎是遍歷所有圖像,並使用圖像重新創建報告,然後將其下載爲pdf。

有沒有更簡單/更有效的方法來實現這個目標?

<body> 
<h1> Chart 1 </h1> 
<div style="width:800px; height:400px;"> 
<canvas id="chart_1" width="50" height="50"></canvas> 
</div> 

<h1> Chart 2 </h1> 
<div style="width:800px; height:400px;"> 
<canvas id="chart_2" width="50" height="50"></canvas> 
</div> 

<h1> Chart 3 </h1> 
<div style="width:800px; height:400px;"> 
<canvas id="chart_3" width="50" height="50"></canvas> 
</div> 
</body> 

回答

1

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

長期以來,上述示例旨在演示一種方法,而不是您的最終解決方案。

祝你好運!

+0

謝謝你的例子。它工作完美。 如何添加更多頁面,如果內容更多。請幫幫我。 – VSK