html2canvas+jsPDF实现前端导出pdf

html2canvas+jsPDF实现前端导出pdf

  1. 安装插件包
javascript 复制代码
npm install jspdf
npm install html2canvas
  1. 引入插件
javascript 复制代码
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
  1. 生成pdf
javascript 复制代码
        const perCanvas = document.createElement('canvas');
        perCanvas.style.backgroundColor = '#fff'
        const context = perCanvas.getContext('2d');
        html2canvas(this.$refs.pdfContent, {
          scale: 4, //放大防止模糊
          dpi: 300 // 处理模糊问题
        }).then((canvas) => {
          const canvasData = canvas.toDataURL('image/jpeg', 1.0);
          // pdf的尺寸
          const pdfWidth = canvas.width;
          const pdfHeight = pdfWidth * 1.414;
          //切割后的canvas图片的宽高,就等于每页pdf的宽高
          perCanvas.width = canvas.width;
          perCanvas.height = pdfHeight;
          // 每张图片的高度:适当减少100,上下各留50页边距
          const perHeight = pdfHeight - 100;

          // 计算切割次数
          let splitCount = Math.ceil(canvas.height / perHeight);
          if (splitCount * perHeight < canvas.height) splitCount++;

          //创建img对象,加载完整的canvas图片
          const img = new Image();
          img.src = canvasData;

          //创建pdf对象

          //待图片加载完成
          setTimeout(() => {
            let pdf = new jsPDF('p', 'pt', [pdfWidth, pdfHeight]);
            //切割canvas图片,贴到每一页pdf中
            for (let i = 0; i < splitCount; i++) {
              const startY = i * perHeight; // 起始y坐标
              // 清空画布
              context.clearRect(0, 0, perCanvas.width, pdfHeight);
              context.fillStyle = '#fff';
              context.fillRect(0, 0, perCanvas.width, pdfHeight);
              // 绘制当前切割区域的图片
              context.drawImage(img, 0, startY, perCanvas.width, perHeight, 0, 0, perCanvas.width, perHeight);
              const perCanvasData = perCanvas.toDataURL('image/jpeg', 1.0);
              pdf.addImage(perCanvasData, 'JPEG', 0, 50, perCanvas.width, perCanvas.height, '', 0);
              if (i < splitCount - 1) pdf.addPage();
            };

            let pdfBlob = pdf.output('blob');
            // pdf.save("content.pdf"); 执行此api会直接下载
            this.showpdf = false
            let signBlob = new FormData() //把文件上传到后台
            signBlob.append('file', pdfBlob, ".pdf")
            //此处将signBlob上传即可
          }, 0)
相关推荐
在逃的吗喽5 小时前
Spring Boot的web基础配置
前端·spring boot
玲小珑5 小时前
LangChain.js 完全开发手册(十九)前端 AI 开发进阶技巧
前端·langchain·ai编程
哆啦A梦15885 小时前
46 修改购物车数据
前端·vue.js·node.js
程序员ys5 小时前
Vue的响应式系统是怎么实现的
前端·javascript·vue.js
Sailing6 小时前
🔥 React 高频 useEffect 导致页面崩溃的真实案例:从根因排查到彻底优化
前端·react.js·面试
aduzhe6 小时前
关于在嵌入式中打印float类型遇到的bug
前端·javascript·bug
Sailing6 小时前
🔥 大模型时代最讽刺的职业出现了:“大模型善后工程师”
前端·openai·ai编程
o***Z4486 小时前
前端组件表单验证,React Hook Form与VeeValidate
前端·react.js·前端框架
xiaoxue..6 小时前
Vibe Coding之道:从Hulk扩展程序看Prompt工程的艺术
前端·人工智能·prompt·aigc
程序猿小蒜6 小时前
基于springboot的汽车资讯网站开发与实现
java·前端·spring boot·后端·spring