打印當前頁面,一開始我認爲是須要輸出pdf的,後來瞭解的需求是可以打印就能夠了。需求既然都研究了,記錄下。css
更好的打印方式,window.print();會彈出打印對話框,打印的是window.document.body.innerHTML中的內容。html
這個導出PDF的插件輸出的內容是有點模糊。ajax
引入腳本canvas
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.debug.js"></script> <script src="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.js"></script>
js代碼jsp
1 var downPdf = document.getElementById("exportToPdf"); 2 downPdf.onclick = function() { 3 html2canvas( 4 document.getElementById("export_content"), { 5 dpi: 172, //導出pdf清晰度 6 onrendered: function(canvas) { 7 var contentWidth = canvas.width; 8 var contentHeight = canvas.height; 9 10 //一頁pdf顯示html頁面生成的canvas高度; 11 var pageHeight = contentWidth / 592.28 * 841.89; 12 //未生成pdf的html頁面高度 13 var leftHeight = contentHeight; 14 //pdf頁面偏移 15 var position = 0; 16 //html頁面生成的canvas在pdf中圖片的寬高(a4紙的尺寸[595.28,841.89]) 17 var imgWidth = 595.28; 18 var imgHeight = 592.28 / contentWidth * contentHeight; 19 20 var pageData = canvas.toDataURL('image/jpeg', 1.0); 21 var pdf = new jsPDF('', 'pt', 'a4'); 22 23 //有兩個高度須要區分,一個是html頁面的實際高度,和生成pdf的頁面高度(841.89) 24 //當內容未超過pdf一頁顯示的範圍,無需分頁 25 if(leftHeight < pageHeight) { 26 pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight); 27 } else { 28 while(leftHeight > 0) { 29 pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight) 30 leftHeight -= pageHeight; 31 position -= 841.89; 32 //避免添加空白頁 33 if(leftHeight > 0) { 34 pdf.addPage(); 35 } 36 } 37 } 38 pdf.save('content.pdf'); 39 }, 40 //背景設爲白色(默認爲黑色) 41 background: "#fff" 42 }) 43 }