js 实现 html 转pdf

本文介绍如何使用jspdf和html2canvas将网页内容转换为PDF文件。重点讲解了配置参数、解决跨域问题的方法,并提供了完整的代码示例。

新建HTML页面文件

头部引入刚才所下载的 jspdf 和 html2canvas,再导入主要的 js 文件例如:

<script src="/js/jspdf.debug.js"></script>
<script src="/js/html2canvas.js"></script>
<script src="/main.js"></script>
  •  

页面里面内容自己想怎么写就怎么写啦,提供一个按钮来触发导出pdf的功能,例如:


<button id="btn-html2canvas">export PDF by using jspdf + html2canvas</button>
  •  

编辑 main.js

document.getElementById("btn-html2canvas").onclick = function(){

    html2canvas(document.getElementById("content"), {
        onrendered: function(canvas) {

            //通过html2canvas将html渲染成canvas,然后获取图片数据
            var imgData = canvas.toDataURL('image/jpeg');

            //初始化pdf,设置相应格式
            var doc = new jsPDF("p", "mm", "a4");

            //这里设置的是a4纸张尺寸
            doc.addImage(imgData, 'JPEG', 0, 0,210,297);

            //输出保存命名为content的pdf
            doc.save('content.pdf');
        }
    });

}

这里要特别注意 canvas.toDataURL('image/jpeg)的参数 image/jpeg 和 doc.addImage(...,'JPEG',...) 的参数 JPEG务必一致 
而且,我也建议这两个参数分别写 image/jpeg 和 JPEG 。 
因为其他参数例如 image/png 等,导出pdf后内容为空。 
这也是困扰了我一天的问题。(我猜测因为html2canvas输出的图片base64数据是image/jpeg格式,如果写其他格式会导致渲染失败)

 git地址:https://github.com/pwcong/how-transform-html-into-pdf

问题: 有跨域错误;

 解决 :useCORS:true;

可用参数

参数名称类型默认值描述
allowTaintbooleanfalseWhether to allow cross-origin images to taint the canvas---允许跨域
backgroundstring#fffCanvas background color, if none is specified in DOM. Set undefined for transparent---canvas的背景颜色,如果没有设定默认透明
heightnumbernullDefine the heigt of the canvas in pixels. If null, renders with full height of the window.---canvas高度设定
letterRenderingbooleanfalseWhether to render each letter seperately. Necessary if letter-spacing is used.---在设置了字间距的时候有用
loggingbooleanfalseWhether to log events in the console.---在console.log()中输出信息
proxystringundefinedUrl to the proxy which is to be used for loading cross-origin images. If left empty, cross-origin images won't be loaded.---代理地址
taintTestbooleantrueWhether to test each image if it taints the canvas before drawing them---是否在渲染前测试图片
timeoutnumber0Timeout for loading images, in milliseconds. Setting it to 0 will result in no timeout.---图片加载延迟,默认延迟为0,单位毫秒
widthnumbernullDefine the width of the canvas in pixels. If null, renders with full width of the window.---canvas宽度
useCORSbooleanfalseWhether to attempt to load cross-origin images as CORS served, before reverting back to proxy--这个我也不知道是干嘛的

 

   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值