https://blog.csdn.net/weixin_39166851/article/details/121678381
导入两个JS
链接:https://pan.baidu.com/s/1QO2obUYNDkZ0Om9zaLddoA
提取码:majx
<button id="btn">导出为PDF文件</button> <div id="pdfDom"> <table> <th></th> </table> <ul id="box"> <span style="background-color: rgb(255, 255, 255); font-family: tahoma, arial, verdana, sans-serif;">U<font color="#ff0000">ni</font></span><font face="courier new" style="background-color: rgb(255, 255, 255);"><font color="#ff0000">H</font>TML</font><font face="tahoma, arial, verdana, sans-serif" style="color: rgb(0, 0, 0); background-color: rgb(255, 255, 255);">Me<i>涂</i></font><div style="color: rgb(0, 0, 0); background-color: rgb(255, 255, 255); font-family: tahoma, arial, verdana, sans-serif;"><br></div><div style="color: rgb(0, 0, 0); font-family: tahoma, arial, verdana, sans-serif;"><span style="background-color: rgb(255, 255, 255);">磊</span><b style=""><span style="background-color: rgb(255, 255, 255);">东奔</span><span style="background-color: rgb(255, 255, 0);">西</span></b><span style="background-color: rgb(255, 255, 0);">走m</span><u style="background-color: rgb(255, 255, 255);">o1 </u></div> //要打印的HTML 放在这 </ul> </div> <script> let obox = document.getElementById("box") let opdfdom = $("#pdfDom") let obtn = document.getElementById("btn") 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>
分类:
UniGui学习
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律