项目场景:

例如:需要导出PDF格式


问题描述

发现:自己导出的PDF,有表格超出之后,只会截取当前屏幕可视区,下面的并不会导出

原因分析:

提示:问题出现在滚动条加错地方


解决方案:

首先:

npm install html2canvas

npm install jspdf

第二:新建一个htmlToPdf.js文件存放

// 导出页面为PDF格式

import html2Canvas from './html2canvas'

import JsPDF from './jsPdf.debug'

export default{

  name:'wwutils',

  toolExportPdf(fileName) {

    let isCompeleted = false;

    setTimeout(() => {

        // 获取需要打印的区域,以div为单位,此处使用的是vue的选择器

        $("iframe").remove();

        var pdfDom = document.getElementById("exportImg");

        $("#exportImg").scrollTop(0);

        // 设置背景色

        pdfDom.style.background = "#F4F7FC";

        let _this = this;

        var exportName = fileName; // 导出生成文件的名称

        var height = $("#exportImg").outerHeight();

        const Dom_height = $("#exportImg").height();

        const targetDom = document.querySelector("#exportImg");

        const copyDom = targetDom.cloneNode(true);

        copyDom.style.width = targetDom.scrollWidth + "px";

        copyDom.style.height = targetDom.scrollHeight + "px";

        document.body.appendChild(copyDom);

        html2Canvas(pdfDom, {

            allowTaint: false,

            useCORS: true,

            height: targetDom.scrollHeight,

            width: targetDom.scrollWidth,

            onrendered: function (canvas) {

                let contentWidth = canvas.width; //画布宽度

                let contentHeight = canvas.height; //画布高度

                let pageHeight = (contentWidth / 592.28) * 841.89;

                let leftHeight = contentHeight;

                let position = 0;

                let imgWidth = 592.28;

                let imgHeight = (592.28 / contentWidth) * contentHeight;

                let pageData = canvas.toDataURL("image/jpeg", 1.0);

                let PDF = new JsPDF("", "pt", "a4");

                if (leftHeight < pageHeight) {

                    PDF.addImage(pageData,"JPEG",0,0,imgWidth,imgHeight);

                } else {

                    while (leftHeight > 0) {

                        PDF.addImage(pageData,"JPEG",0,position + 4,imgWidth,imgHeight);

                        leftHeight -= pageHeight;

                        position -= 841.89;

                        if (leftHeight > 0) {

                            PDF.addPage();

                        }

                    }

                }

                PDF.save(exportName + ".pdf");

                document.body.removeChild(copyDom);

                isCompeleted = true;

                // PubSub.publish("isExportPdfCompleted", {

                //     state: true,

                // });

            },

            background: "#F4F7FC",

            windowHeight: targetDom.scrollHeight, // 获取y方向滚动条中的内容

            y: targetDom.scrollHeight // 页面在垂直方向的滚动距离

        });

    }, 1000);

    return isCompeleted

 },

}

 可以使用在main.js中引用,也可以在本地文件直接引用

 

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐