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 }