<head>
@*須要引用的js庫*@
<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> </head> <body> <div id="pdfDom" class="right-aside"> 1232132131sd </div> <input type="button" value="點擊" onclick="makeMpdf('建設工程施工安全監督抽查記錄', 'pdfDom')" /> <script type="text/javascript">//將html頁面導出.pdf格式文件(適用於jQuery、vue庫) -- xzz 2018/04/24 function makeMpdf(pdfName,elementId) { if (confirm("您確認下載該PDF文件嗎?")) { //var target = document.getElementsByClassName("right-aside")[0]; var target = document.getElementById(elementId); target.style.background = "#FFFFFF"; if (pdfName == '' || pdfName == undefined) pdfName = "content"; html2canvas(target, { 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; //頁面偏移 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(pdfName + ".pdf"); } }) } } </script> </body>