测试HTML转换为PDF

思路是先转换成图片,再转换成PDF,转换过程中使用到了两个库:


https://github.com/niklasvh/html2canvas
https://github.com/MrRio/jsPDF

html2canvas官网例子:

html2canvas(document.querySelector("#capture")).then(canvas => {
    document.body.appendChild(canvas)
});

jsPDF官网例子:

Then you're ready to start making your document:

// Default export is a4 paper, portrait, using milimeters for units
var doc = new jsPDF()

doc.text('Hello world!', 10, 10)
doc.save('a4.pdf')


If you want to change the paper size, orientation, or units, you can do:

// Landscape export, 2×4 inches
var doc = new jsPDF({
  orientation: 'landscape',
  unit: 'in',
  format: [4, 2]
})

doc.text('Hello world!', 1, 1)
doc.save('two-by-four.pdf')

简单的demo: 

<body>
    <div id="capture" style="padding: 10px; background: #f5da55">
        <h4 style="color: #000; ">Hello world!</h4>
    </div>
    <button id="capBtn">点击下载</button>
<script src="html2canvas.js" type="text/javascript" charset="utf-8"></script>
<script src="jspdf.min.js" type="text/javascript" charset="utf-8"></script>
<script>
    document.querySelector('#capBtn').onclick = function(){
        html2canvas(document.querySelector("#capture")).then(canvas => {
            // document.body.appendChild(canvas);
            var imgData = canvas.toDataURL('image/jpeg');
            //初始化pdf,设置相应格式
            var doc = new jsPDF("p", "mm", "a4");
            //设置a4纸张尺寸
            doc.addImage(imgData, 'JPEG', 0, 0,210,297);
           
            doc.save('content.pdf');
        });
    }
</script>
</body>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值