网页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');
};

参考文档

相关推荐
康小汪2 小时前
AI 写 Vue 总写成同一个味道:给它装 Skills,装的不是知识是边界
前端·vue.js·人工智能·ai编程·最佳实践
北冥有鱼6 小时前
发版后动态路由点击报 `Failed to fetch dynamically imported module`」问题上的完整排查与修复过程
前端·vue.js
apollo_qwe9 小时前
大模型 API 接通了,AI 聊天页面为什么还是不好用?
前端·vue.js·人工智能
wuyk55513 小时前
PyQt6-第10讲-PDF工具箱
python·microsoft·pdf·pyqt
小郎君65814 小时前
keep-alive 页面怎么“真刷新”?别改外层 key——一个 refreshVersion 的完整实现
vue.js·算法
徐小夕15 小时前
JitWord 4.3 发布!Word 内嵌 Visio 图表、原生流程图一键无损解析
前端·vue.js·github
开开心心就好18 小时前
免安装PDF盖章工具,透明度和位置可调
运维·服务器·前端·javascript·pdf·ocr·1024程序员节
king王一帅18 小时前
做了三年 ProseMirror 后,我用四个月自研排版引擎实现 WPS / Google Docs 替代品,整套框架 MIT 开源
前端·vue.js·开源
仰望.1 天前
vue 表格组件 vxe-table 树表格懒加载支持拖拽排序的详细用法
前端·javascript·vue.js·vxe-table
康小旺1 天前
AI 写 Vue 总写成同一个味道:给它装 Skills,装的不是知识是边界
vue.js·typescript