【JavaScript 】纯JS实现html生成导出保存为PDF文件
当前位置:点晴教程→知识管理交流
→『 技术文档交流 』
1,整体思路2,准备工作<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">导出为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 // 提升画面质量,但是会增加文件大小 }).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,结果该文章在 2023/5/15 19:08:54 编辑过
|
关键字查询
相关文章
正在查询... |