html 转 pdf

 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 來源:简书
原文地址:https://www.cnblogs.com/kitty-blog/p/9583562.html