VUE页面导出PDF踩坑指南


一、VUE导出PDF中遇到的问题总结

导出方案用的是html2canvas+jspdf,简单的导出很容易实现,但是也会有一些问题:
一是不同分辨率下导出内容不同的问题,这个需要固定导出内容的宽度;
二是会遇到页面内容被切割的问题,因为导出原理是先使用html2canvas将DOM元素转换为canvas,再利用 canvas 的 toDataURL 方法输出为图片,之后使用jspdf添加图片生成PDF。图片生成PDF过程中必然用统一的格式切割图片分页,所以内容很容易被切割;
三是导出内容过多时,会导出失败只生成空白页,因为内容过多,超出了canvas的 toDataURL 方法的处理范围。

二、基础版的VUE导出PDF(也是所有导出方案的基础)
1、引入两个依赖
npm i html2canvas 
npm i jspdf
2、在utils文件夹下新建htmlToPdf.js文件
/* eslint-disable */
//不使用JQuery版的
import html2canvas from 'html2canvas';
import JsPDF from 'jspdf';

/**
 * @param  ele          要生成 pdf 的DOM元素(容器)
 * @param  padfName     PDF文件生成后的文件名字
 * */

 export function downloadPDF(ele, pdfName){
   

    let eleW = ele.offsetWidth;// 获得该容器的宽
    let eleH = ele.offsetHeight;// 获得该容器的高
    let eleOffsetTop = ele.offsetTop;  // 获得该容器到文档顶部的距离
    let eleOffsetLeft = ele.offsetLeft; // 获得该容器到文档最左的距离

    var canvas = document.createElement("canvas");
    var abs = 0;

    let win_in = document.documentElement.clientWidth || document.body.clientWidth; // 获得当前可视窗口的宽度(不包含滚动条)
    let win_out = window.innerWidth; // 获得当前窗口的宽度(包含滚动条)

    if(win_out>win_in){
   
        // abs = (win_o - win_i)/2;    // 获得滚动条长度的一半
        abs = (win_out - win_in)/2;    // 获得滚动条宽度的一半
        // console.log(a, '新abs');
    }
    canvas.width = eleW * 2;    // 将画布宽&&高放大两倍
    canvas.height = eleH * 2;

    var context = canvas.getContext("2d");
    context.scale(2, 2);
    context.translate(-eleOffsetLeft -abs, -eleOffsetTop);
    // 这里默认横向没有滚动条的情况,因为offset.left(),有无滚动条的时候存在差值,因此
    // translate的时候,要把这个差值去掉

    html2canvas( ele, {
   
        dpi: 300,
        // allowTaint: true,  //允许 canvas 污染, allowTaint参数要去掉,否则是无法通过toDataURL导出canvas数据的
        useCORS:true  //允许canvas画布内 可以跨域请求外部链接图片, 允许跨域请求。
    } ).then( (canvas)=>{
   
        var contentWidth = canvas.width;
        var contentHeight = canvas.height;
        //一页pdf显示html页面生成的canvas高度;
        var pageHeight = contentWidth / 592.28 * 841.89;
        //未生成pdf的html页面高度
        var leftHeight = contentHeight;
        //页面偏移
        var position = 0;
        //a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
        var imgWidth = 595.28;
        var imgHeight = 595.28/contentWidth * contentHeight;
        var pageData = canvas.toDataURL('image/jpeg', 1.0);
        var pdf = new JsPDF('', 'pt', 'a4');
        //有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
        //当内容未超过pdf一页显示的范围,无需分页
        if (leftHeight < pageHeight) {
   
            //在pdf.addImage(pageData, 'JPEG', 左,上,宽度,高度)设置在pdf中显示;
            pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
            // pdf.addImage(pageData, 'JPEG', 20, 40, 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(pdfName);
    })
}

3、使用方法如下:
<template>
    <div class="app-container">
        <div class="main-wrap">
            <div class="export-main">
                <el-button type="primary" @click="exportPdf">导出</el-button>
                <div class="export-wrap">
                    <div id="pdfBox">
                        <div class="pdf-content"></div>
                        <div class="pdf-content"></div>
                        <div class="pdf-content"></div>
                        <div class="pdf-content"></div>
                        <div class="pdf-content"></div>
                        <div class="pdf-content"></div>
                        <div class="pdf-content"></div>
                        <div class="pdf-content"></div>
                        <div class="pdf-content"></div>
                        <div class="pdf-content"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import {
    downloadPDF } from '@/utils/htmlToPdf';
export default {
   
    data() {
   
        return {
   

        };
    },
    methods: {
   
        exportPdf() {
   
            const ele = document.querySelector('#pdfBox');
            downloadPDF(ele, 'pdf');
        }

    }
};
</script>
<style lang="scss" scoped>
@import '@/assets/styles/mixin.scss';
    .export-main {
   
        .export-wrap {
   
            overflow: auto;
            max-height: calc((100vh - 1rem) - 40px);;
            @include scrollBarNone;
            #pdfBox {
   
                padding: 0 20px;
                width: 1080px;
                margin: 0 auto;
                overflow: hidden;
                .pdf-content {
   
                    width: 100%;
                    height: 300px;
                    margin-top: 20px;
                    background-color: #065cad;
                }
            }
        }
    }
</style>




因为导出DOM设置了宽度 width: 1080px; ,所以不论哪个分辨率下导出内容都如下图所示,也就解决了第一个问题。

在这里插入图片描述

二、内容被分割问题
1、简单内容时,解决导出内容分割问题

在上图中可以清晰的看到蓝色方块有的被分割了。所有导出元素都需要添加上相同的class,如pdf-content这种,之后就可以判断截断时在截断内容头部添加等高空白内容即可。解决方案如下:

(1)在utils文件夹下新建htmlToPdf2.js文件
/* eslint-disable */
//不使用JQuery版的
import html2canvas from 'html2canvas';
import JsPDF from 'jspdf';

/**
 * @param  ele          要生成 pdf 的DOM元素(容器)
 * @param  item         不分割的DOM内容class
 * @param  padfName     PDF文件生成后的文件名字
 * */
function isSplit(nodes, index, pageHeight) {
   
    // 计算当前这块dom是否跨越了a4大小,以此分割
    return !!(nodes[index].offsetTop + nodes[index].offsetHeight < pageHeight && nodes[index + 1] && nodes[index + 1].offsetTop + nodes[index + 1].offsetHeight > pageHeight);
}
 export function downloadPDF(ele, item, pdfName){
   
    // 获取分割dom,此处为class类名为item的dom
    const lableListID = document.getElementsByClassName(item);
    // console.log(lableListID);
    // const pageHeight = ele.scrollWidth / 841.89 * 595.28;// (横版pdf)
    const pageHeight = ele.scrollWidth / 595.28 * 841.89;
    // 进行分割操作,当dom内容已超出a4的高度,则将该dom前插入一个空dom,把他挤下去,分割
    for (let i = 0; i < lableListID.length; i++) {
   
        const multiple = Math.ceil((lableListID[i].offsetTop + lableListID[i].offsetHeight) / pageHeight);
        if (isSplit(lableListID, i, multiple * pageHeight)) {
   
            const divParent = lableListID[i].parentNode; // 获取该div的父节点
            const newNode = document.createElement('div');
            newNode.className = 'emptyDiv';
            newNode.style.background = '#ffffff';
            const _H = multiple * pageHeight - (lableListID[i].offsetTop + lableListID[i].offsetHeight);
            newNode.style.height = _H + 60 + 'px';
            newNode.style.width = '100%';
            const next = lableListID[i].nextSibling; // 获取div的下一个兄弟节点
            // 判断兄弟节点是否存在
            // console.log(next);
            if (next) {
   
                // 存在则将新节点插入到div的下一个兄弟节点之前,即div之后
                divParent.insertBefore(newNode, next);
            } else {
   
                // 不存在则直接添加到最后,appendChild默认添加到divParent的最后
                divParent.appendChild(newNode);
            }
        }
    }

    html2canvas(ele, {
   
        dpi: 300,
        // allowTaint: true,  //允许 canvas 污染, allowTaint参数要去掉,否则是无法通过toDataURL导出canvas数据的
        useCORS:true  //允许canvas画布内 可以跨域请求外部链接图片, 允许跨域请求。
    }).then((canvas) => {
   
        const contentWidth = canvas.width;
        const contentHeight = canvas.height;
        const pageHeight = contentWidth / 595.28 * 841.89 // 一页pdf显示html页面生成的canvas高度;
        // const pageHeight = contentWidth / 841.89 * 595.28; // 一页pdf显示html页面生成的canvas高度(横版pdf);
        let leftHeight = contentHeight; // 未生成pdf的html页面高度
        let position = 0; // pdf页面偏移

        // a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
        // let imgWidth = 595.28
        let imgWidth = 595.28  //宽度
        let imgHeight = 595.28 / contentWidth * contentHeight
        // const imgWidth = 841.89; // 宽度(横版pdf)
        // const imgHeight = 841.89 / contentWidth * contentHeight;// (横版pdf)
        const pageData = canvas.toDataURL('image/jpeg', 1.0);
        const pdf = new JsPDF('', 'pt', 'a4');
        if (leftHeight < pageHeight) {
   
            pdf
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值