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)
相关推荐
持久的棒棒君4 分钟前
ElementUI 2.x 输入框回车后在调用接口进行远程搜索功能
前端·javascript·elementui
2401_8572979115 分钟前
秋招内推2025-招联金融
java·前端·算法·金融·求职招聘
undefined&&懒洋洋1 小时前
Web和UE5像素流送、通信教程
前端·ue5
大前端爱好者3 小时前
React 19 新特性详解
前端
小程xy3 小时前
react 知识点汇总(非常全面)
前端·javascript·react.js
随云6323 小时前
WebGL编程指南之着色器语言GLSL ES(入门GLSL ES这篇就够了)
前端·webgl
随云6323 小时前
WebGL编程指南之进入三维世界
前端·webgl
寻找09之夏4 小时前
【Vue3实战】:用导航守卫拦截未保存的编辑,提升用户体验
前端·vue.js
多多米10055 小时前
初学Vue(2)
前端·javascript·vue.js
柏箱5 小时前
PHP基本语法总结
开发语言·前端·html·php