网页vue3导出pdf

需求:统计页面导出pdf;

利用插件:html2canvas和jspdf库;

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

jsPDF
html2canvas

废话不多说 上代码

在utils下新建文件 htmlToPdf.ts

typescript 复制代码
/* 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;

在使用的地方

typescript 复制代码
import htmlToPdf from '@/utils/htmlToPdf';


const exportPDF = () => {
  // eslint-disable-next-line spellcheck/spell-checker
  htmlToPdf.getPdf('离缝报告', '#pdfDom');
};

参考文档

相关推荐
哆啦A梦15882 小时前
搜索页面布局
前端·vue.js·node.js
_院长大人_3 小时前
el-table-column show-overflow-tooltip 只能显示纯文本,无法渲染 <p> 标签
前端·javascript·vue.js
SevgiliD3 小时前
el-table中控制单列内容多行超出省略及tooltip
javascript·vue.js·elementui
哆啦A梦15884 小时前
axios 的二次封装
前端·vue.js·node.js
阿珊和她的猫4 小时前
深入理解与手写发布订阅模式
开发语言·前端·javascript·vue.js·ecmascript·状态模式
爱看书的小沐5 小时前
【小沐杂货铺】基于Three.js渲染三维风力发电机(WebGL、vue、react、WindTurbine)
javascript·vue.js·webgl·three.js·opengl·风力发电机·windturbine
罚时大师月色7 小时前
Vue+ts 如何实现父组件和子组件通信
javascript·vue.js·ecmascript
fury_1238 小时前
vue3:数组的.includes方法怎么使用
前端·javascript·vue.js
宁&沉沦8 小时前
Cursor 科技感的登录页面提示词
前端·javascript·vue.js
武天8 小时前
如果使用Vue3.0实现一个 Modal,你会怎么进行设计?
vue.js