1 /**html转换成pdf */ 2 function exportpdf() { 3 //$('#htmltopdf').css('padding', '100px 150px'); 4 var htmltopdf = $(".htmltopdf"); 5 $.each(htmltopdf, function (i, item) { 6 html2canvas($(item), { 7 onrendered: function (canvas) { 8 var contentwidth = canvas.width; 9 var contentheight = canvas.height; 10 var pageheight = contentwidth / 592.28 * 841.89; 11 //未生成pdf的html页面高度 12 var leftheight = contentheight; 13 //页面偏移 14 var position = 0; 15 //a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高 16 var imgwidth = 595.28; 17 var imgheight = 592.28 / contentwidth * contentheight; 18 19 var pagedata = canvas.todataurl('image/png', 1.0); 20 21 var pdf = new jspdf('', 'pt', 'a4'); 22 23 //有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89) 24 //当内容未超过pdf一页显示的范围,无需分页 25 if (leftheight < pageheight) { 26 pdf.addimage(pagedata, 'png', 0, 0, imgwidth, imgheight); 27 } else { 28 while (leftheight > 0) { 29 pdf.addimage(pagedata, 'png', 0, position, imgwidth, imgheight) 30 leftheight -= pageheight; 31 position -= 841.89; 32 //避免添加空白页 33 if (leftheight > 0) { 34 pdf.addpage(); 35 } 36 } 37 } 38 39 pdf.save('report_' + new date().gettime() + '.pdf'); 40 61 }, 62 background: "#fff", 63 //这里给生成的图片默认背景,不然的话,如果你的html根节点没设置背景的话,会用黑色填充。 64 allowtaint: true //避免一些不识别的图片干扰,默认为false,遇到不识别的图片干扰则会停止处理html2canvas 65 }); 66 67 68 }); 69 }
引入js :html2canvas.js、jspdf.debug.js 链接:https://files.cnblogs.com/files/kitty-blog/jspdf.debug.js https://files.cnblogs.com/files/kitty-blog/html2canvas.js
作者:linwalker 链接:http://www.jianshu.com/p/570c84ee2e8d 來源:简书
如对本文有疑问, 点击进行留言回复!!
VScode中的react自动补全标签代码及黄色or红色警告
关于React处理input的方法和多个input共用一个方法(不用jQuery)
网友评论