1. 程式人生 > >JSP頁面匯出PDF格式檔案

JSP頁面匯出PDF格式檔案

JSP頁面匯出PDF格式檔案基本在前端頁面可以全部完成

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.debug.js"></script>

新增下載連結的點選事件
<script type="text/javascript">
var downPdf = document.getElementById("downLoad");
downPdf.onclick = function() {
downPdf.parentNode.removeChild(downPdf);
html2canvas(document.body, {
onrendered:function(canvas) {

var contentWidth = canvas.width;
var contentHeight = canvas.height;

//一頁pdf顯示html頁面生成的canvas高度;
var pageHeight = contentWidth / 592.28 * 841.89;
//未生成pdf的html頁面高度
var leftHeight = contentHeight;
//pdf頁面偏移
var position = 0;
//a4紙的尺寸[595.28,841.89],html頁面生成的canvas在pdf中圖片的寬高
var imgWidth = 595.28;
var imgHeight = 592.28/contentWidth * contentHeight;

var pageData = canvas.toDataURL('image/jpeg', 1.0);

var pdf = new jsPDF('', 'pt', 'a4');

//有兩個高度需要區分,一個是html頁面的實際高度,和生成pdf的頁面高度(841.89)
//當內容未超過pdf一頁顯示的範圍,無需分頁
if (leftHeight < pageHeight) {
pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight );
} else {
while(leftHeight > 0) {
pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
leftHeight -= pageHeight;
position -= 841.89;
//避免新增空白頁
if(leftHeight > 0) {
pdf.addPage();
}
}
}
pdf.save('content.pdf');
}
})
}
</script>
<a id="downLoad" href="javascript:void(0)">列印檔案</a>
最終生成檔案