vue 生成PDF(A4标准PDF分页)

1.先安装两个插件

//页面转图片

npm install --save html2canvas

//图片转PDF

npm install jspdf --save 

2. 在需要导出的dom节点增加ref='pdf' 例如

<div ref="pdf"> 这是待转换的页面,点击 <button @click="handleExport">导出</button> 点击导出PDF</div>

3.定义导出方法

handleExport() {

      downloadPDF(this.$refs.pdf);

   },

4.在页面导入 import { downloadPDF } from "@/utils/pdf.js";

pdf.js 内容如下

import html2canvas from "html2canvas";

import jsPDF from "jspdf";

export const downloadPDF = page => {

    html2canvas(page).then(function (canvas) {

        canvas2PDF(canvas);

    });

};

const canvas2PDF = canvas => {

    let contentWidth = canvas.width;

    let contentHeight = canvas.height;

    //a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高

    let imgWidth = 595.28;

    let imgHeight = 592.28 / contentWidth * contentHeight;

    //let imgHeight = 700/contentWidth * contentHeight;

    //一页pdf显示html页面生成的canvas高度;

    var pageHeight = contentWidth / 592.28 * 841.89;

    let totalHeight = contentHeight;

    // 第一个参数: l:横向  p:纵向

    // 第二个参数:测量单位("pt","mm", "cm", "m", "in" or "px")

    let pdf = new jsPDF("p", "pt");

    let position = 0;

    //   pdf.addImage(

    //     canvas.toDataURL("image/jpeg", 1.0),

    //     "JPEG",

    //     0,

    //     0,

    //     imgWidth,

    //     imgHeight

    //   );

    if (totalHeight < pageHeight) {

        pdf.addImage( canvas.toDataURL("image/jpeg", 1.0), 'JPEG', 0, 0, imgWidth, imgHeight);

    } else {    

        while (totalHeight > 0) {

            pdf.addImage( canvas.toDataURL("image/jpeg", 1.0), 'JPEG', 0, position, imgWidth, imgHeight)

            totalHeight -= pageHeight;

            position -= 841.89;

            //避免添加空白页

            if (totalHeight > 0) {

                pdf.addPage();

            }

        }

    }

    // pdf.addImage(

    //     canvas.toDataURL("image/jpeg", 1.0),

    //     "JPEG",

    //     0,

    //     position,

    //     imgWidth,

    //     imgHeight

    // );


 

    pdf.save("导出.pdf");

};

5.点击导出即可成功

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值