html2canvas+jspdf导出html代码为pdf文件


由于项目需求需要导出页面内容为pdf文件,最开始的思路是调用后端接口,但是由于接口跨域问题导致调用失败经过多方面沟通后决定前端完成导出。
思路:使用html2canvas先将指定代码片段转为canvas图片,然后再将canvas使用jspdf转为pdf文件下载(上代码)。

1.引入html2canvas和jspdf的包
2.新建pdf.js用于定义html2canvas 和 jspdf的配置

import html2Canvas from 'html2canvas';
import JsPDF from 'jspdf';
export default {
    install(Vue) {
        Vue.prototype.getPdf = function(dom, title) {
            let that = this;
            let width = document.querySelector(dom).clientWidth; //获取dom 宽度
            let height = document.querySelector(dom).clientHeight; //获取dom 高度
            document.querySelector(dom).style.color = '#000';//默认导出时页面的字体更改为黑色,防止页面字体为白色时导出的pdf看不到字体
            console.log(document.querySelector(dom));
            console.log(width);
            console.log(height);
            let canvas = document.createElement('canvas'); //创建一个canvas节点
            let scale = 1; //定义任意放大倍数 支持小数
            canvas.width = width * scale; //定义canvas 宽度 * 缩放
            canvas.height = height * scale; //定义canvas高度 *缩放
            canvas.getContext('2d').scale(scale,scale); //获取context,设置scale
            let opts = {
                tainttest: true, //检测每张图片都已经加载完成
                scale, // 添加的scale 参数
                useCORS: true,
                canvas, //自定义 canvas
                logging: true, //日志开关
                width, //dom 原始宽度
                height, //dom 原始高度
            };

            html2Canvas(document.querySelector(dom), {
                allowTaint: true,
                ...opts,
            }).then(function(canvas) {
                console.log(canvas);
                let contentWidth = canvas.width;
                let contentHeight = canvas.height;
                console.log(canvas.height);
                let pageHeight = contentWidth / 592.28 * 841.89;
                let leftHeight = contentHeight;
                let position = 0;
                let imgWidth = 595.28;
                let imgHeight = 592.28 / contentWidth * contentHeight;
                let pageData = canvas.toDataURL('image/jpeg');
                let PDF = new JsPDF('', 'pt', 'a4');
                // return
                if (leftHeight < pageHeight) {
                    PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
                } else {
                    while (leftHeight > 0) {
                        PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight);
                        leftHeight -= pageHeight;
                        position -= 841.89;
                        if (leftHeight > 0) {
                            PDF.addPage();
                        }
                    }
                }

                PDF.save(title + '.pdf');
                that.isPrint = true;
            });
        };
    },
};
//vue文件使用



相关