• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

我的博客我做主

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

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 來源:简书
作者:胡倩倩0903
出处:https://www.cnblogs.com/kitty-blog/
本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。

posted on 2018-09-04 11:45  kitty20180903suzhou  阅读(345)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3