# jsPDF使用技巧
## jar 包
<script type="text/javascript" src="style/jspdf/jspdf.min.js"></script>
### 程式碼
```
<button id="downloadPdf" type="button" class="btn btn-outline-secondary btn-sm" style="margin-bottom: 4px" onclick="exportapply();"><%=export %></button>
function exportapply(){
// 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({
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;
}
});
var pdf = new jsPDF('1', 'pt', 'a4');
//將canvas轉為圖片,最後在加到jsPDF中
var image = $(pdfCanvas)[0].toDataURL("image/png");
// 20, 40, 控制文字距離左邊,與上邊的距離
pdf.addImage(image, 'PNG', 40,100);
// download the pdf
pdf.save('filename.pdf');
}
```
### 坑:因為輸出的文件都是黑色的,一直找不到原因,請來才知道,要將canvas轉為圖片,最後在加到jsPDF中
```
var image = $(pdfCanvas)[0].toDataURL("image/png");
```
留言列表