vue html生成pdf

一、安装依赖

1、npm install jspdf

2、npm install html2canvas

二、页面引入

import html2Canvas from "html2canvas";
import jsPDF from "jspdf";

三、导出pdf

htmltopdf() {
            // let tempNode = document.createElement('div');
            // tempNode.innerHTML = document.querySelector('#test').innerHTML;
            html2Canvas(document.querySelector('#test'), {
                allowTaint: true,
                taintTest: false,
                useCORS: true,
                async: true,
                scale: '2',
                dpi: '192'
            }).then(function(canvas) {
                const contentWidth = canvas.width
                const contentHeight = canvas.height
                // 一页pdf显示html页面生成的canvas高度;
                const pageHeight = Math.ceil(contentWidth / 595.28 * 841.89)
                // 未生成pdf的html页面高度
                let leftHeight = contentHeight
                // pdf页面偏移
                let position = 0
                // a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
                const imgWidth = 595.28
                const imgHeight = 595.28 / contentWidth * contentHeight
                // console.log(canvas)
                const pageData = canvas.toDataURL('image/jpeg/png', 1)
                const PDF = new jsPDF('', 'pt', 'a4', true)
                // console.log(PDF)
                if (leftHeight < pageHeight) {
                PDF.addImage(pageData, 'JPEG', 0, 20, imgWidth, imgHeight)
                } else {
                    while (leftHeight > 0) {
                        PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
                        leftHeight -= pageHeight
                        position -= 841.89
                        if (leftHeight > 0) {
                            PDF.addPage()
                        }
                    }
                }
                document.getElementById("iframe123").src = PDF.output('datauristring');//在iframe中显示
                // PDF.save('test.pdf') 
                // window.open(PDF.output('bloburl'));  //在新页面打开当前pdf
                // return PDF.output('datauristring')
            })
        },

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值