【JavaScript 】純JS實現(xiàn)html生成導(dǎo)出保存為PDF文件
當(dāng)前位置:點晴教程→知識管理交流
→『 技術(shù)文檔交流 』
1,整體思路2,準(zhǔn)備工作<script src="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.debug.js"></script> 3,dome<button id="btn">導(dǎo)出為PDF文件</button> <div id="pdfDom"> <table> <th></th> </table> <ul id="box"></ul> </div> <script> let obox = document.getElementById("box") let opdfdom = $("#pdfDom") let obtn = document.getElementById("btn") let lihtml = '' for(let i = 0; i < 50; i++){ lihtml += "<li>條目"+i+"</li>" } obox.innerHTML = lihtml obtn.onclick = function(){ downLoadPdf(opdfdom) } function downLoadPdf(content){ content = content ? content : null; // 條件判斷是否打印 if(!content){ alert("打印失敗,請重新操作") return false } // 開始打印 console.log(content) var contentWidth = content.width(); var contentHeight = content.height(); var canvas = document.createElement("canvas") canvas.width = contentWidth canvas.height = contentHeight var context = canvas.getContext("2d"); html2canvas(content,{ allowTaint:true, scale:2 // 提升畫面質(zhì)量,但是會增加文件大小 }).then(function(canvas){ var pdfWidth = canvas.width; var pdfHeight = canvas.height; var pageHeight = pdfWidth / 592.28 * 841.89; var leftHeight = pdfHeight; var position = 0; var imgWidth = 595.28; var imgHeight = 595.28 / pdfWidth * pdfHeight; var pageData = canvas.toDataURL("img/jpeg",1.0); var pdf = new jsPDF('', 'pt', 'a4'); // 判斷打印dom高度是否需要分頁,如果需要進行分頁處理 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("案例.pdf") }) } </script> 4,結(jié)果該文章在 2023/5/15 19:08:54 編輯過
|
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |