2021-12-23

写入mixins里面做成公用的

 

 

npm install jspdf

npm i html2canvas

 

import html2canvas from "html2canvas"
import jsPDF from "jspdf"
export const download = {
    methods: {
        addcanvas() {

            html2canvas(this.$refs.wrapper, {
                allowTaint: true,
                useCORS: true // 解决跨域问题
            }).then(canvas => {
                let dataURL = canvas.toDataURL("image/png", 1);
                console.info(dataURL)
                    // let oA = document.createElement("a");
                    // oA.download = '';// 设置下载的文件名,默认是'下载'
                    // oA.href = dataURL;
                    // document.body.appendChild(oA);
                    // oA.click();
                    // oA.remove(); // 下载之后把创建的元素删除

                let contentWidth = canvas.width;
                let contentHeight = canvas.height;
                //一页pdf显示html页面生成的canvas高度;
                let pageHeight = contentWidth / 592.28 * 841.89;
                //未生成pdf的html页面高度
                let leftHeight = contentHeight;
                //页面偏移
                let position = 0;
                //a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
                let imgWidth = 595.28;
                let imgHeight = 592.28 / contentWidth * contentHeight;
                let pdf = new jsPDF('', 'pt', 'a4')
                if (leftHeight < pageHeight) {
                    pdf.addImage(dataURL, 'png', 0, 0, imgWidth, imgHeight);
                } else {
                    while (leftHeight > 0) {
                        pdf.addImage(dataURL, 'png', 0, position, imgWidth, imgHeight)
                        leftHeight -= pageHeight;
                        position -= 841.89;
                        //避免添加空白页
                        if (leftHeight > 0) {
                            pdf.addPage();
                        }
                    }
                }
                pdf.save("tsx.pdf");
            });



        },
    },
}
posted on 2021-12-23 11:02  假装新手  阅读(104)  评论(0编辑  收藏  举报