当前位置:   article > 正文

网页vue3导出pdf

网页vue3导出pdf

需求:统计页面导出pdf;
利用插件:html2canvas和jspdf库;
原理就是:我们把需要转换的元素【例如一个div元素】使用html2canvas库将它转换为一个canvas对象,使用jspdf库创建PDF文档,用addImage方法将图像添加到PDF文件中 最后使用save方法将PDF文件保存到用户的设备上。

jsPDF
html2canvas
废话不多说 上代码
在utils下新建文件 htmlToPdf.ts

/* eslint-disable spellcheck/spell-checker */
// 页面导出为pdf格式
import html2Canvas from 'html2canvas';
import jsPDF from 'jspdf';

const htmlToPdf = {
  getPdf(title: string, id: any) {
    html2Canvas(document.querySelector(id), {
      allowTaint: false,
      logging: false,
      useCORS: true,
      scale: 4, //按比例增加分辨率// 提升画面质量,但是会增加文件大小
      // 需要注意,高度 宽度一定要在这里定义一下,不然会存在只下载了当前你能看到的页面!!!
      // height: document.getElementById('pdfDom').scrollHeight,
      // windowHeight: document.getElementById('pdfDom').scrollHeight,
      height: 2700,
      windowHeight: 2700
    }).then(canvas => {
      const pdf = new jsPDF('p', 'mm', 'a4'); //A4纸,纵向
      const ctx = canvas.getContext('2d'),
        a4w = 210,
        a4h = 297, //A4大小,210mm x 297mm
        imgHeight = Math.floor((a4h * canvas.width) / a4w); //按A4显示比例换算一页图像的像素高度
      let renderedHeight = 0;

      while (renderedHeight < canvas.height) {
        const page = document.createElement('canvas');
        page.width = canvas.width;
        page.height = Math.min(imgHeight, canvas.height - renderedHeight); //可能内容不足一页

        //用getImageData剪裁指定区域,并画到前面创建的canvas对象中
        (page.getContext('2d') as any).putImageData(
          ctx?.getImageData(0, renderedHeight, canvas.width, Math.min(imgHeight, canvas.height - renderedHeight)),
          0,
          0
        );
        pdf.addImage(
          page.toDataURL('image/jpeg', 1.0),
          'JPEG',
          0,
          0,
          a4w,
          Math.min(a4h, (a4w * page.height) / page.width)
        ); //添加图像到页面,保留10mm边距

        renderedHeight += imgHeight;
        if (renderedHeight < canvas.height) {
          pdf.addPage(); //如果后面还有内容,添加一个空页
        }
        // delete page;
      }
      pdf.save(title + '.pdf');
    });
  }
};

export default htmlToPdf;

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58

在使用的地方

import htmlToPdf from '@/utils/htmlToPdf';


const exportPDF = () => {
  // eslint-disable-next-line spellcheck/spell-checker
  htmlToPdf.getPdf('离缝报告', '#pdfDom');
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

参考文档

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/451299
推荐阅读