VUE页面导出PDF方案

1,技术方案为:html2canvas把页面生成canvas图片,再通过jspdf生成PDF文件;

2,安装依赖:

复制代码
npm i html2canvas -S
npm i jspdf -S

3,封装导出pdf方法exportPdf.js:

html 复制代码
// 页面导出为pdf格式 //title表示为下载的标题,html表示document.querySelector('#myPrintHtml')
import html2Canvas from 'html2canvas';
import JsPDF from 'jspdf';

let noTableHeight = 0; //table外的元素高度
export function pageToPDF(title, html, lableList, type) {
  // type传有效值pdf则为横版
  if (lableList) {
    const pageHeight = Math.floor((277 * html.scrollWidth) / 190) + 20; //计算pdf高度
    for (let i = 0; i < lableList.length; i++) {
      //循环获取的元素
      const multiple = Math.ceil((lableList[i].offsetTop + lableList[i].offsetHeight) / pageHeight); //元素的高度
      if (isSplit(lableList, i, multiple * pageHeight)) {
        //计算是否超出一页
        var _H = ''; //向pdf插入空白块的内容高度
        if (lableList[i].localName !== 'tr') {
          //判断是不是表格里的内容
          _H = multiple * pageHeight - (lableList[i].offsetTop + lableList[i].offsetHeight);
        } else {
          _H = multiple * pageHeight - (lableList[i].offsetTop + lableList[i].offsetHeight + noTableHeight) + 20;
        }
        var newNode = getFooterElement(_H); //向pdf插入空白块的内容
        const divParent = lableList[i].parentNode; // 获取该div的父节点
        const next = lableList[i].nextSibling; // 获取div的下一个兄弟节点
        // 判断兄弟节点是否存在
        if (next) {
          // 存在则将新节点插入到div的下一个兄弟节点之前,即div之后
          divParent.insertBefore(newNode, next);
        } else {
          // 否则向节点添加最后一个子节点
          divParent.appendChild(newNode);
        }
      }
    }
  }
  html2Canvas(html, {
    allowTaint: false,
    taintTest: false,
    logging: false,
    useCORS: true,
    dpi: window.devicePixelRatio * 1,
    scale: 1, // 按比例增加分辨率
  }).then(canvas => {
    var pdf = new JsPDF('p', 'mm', 'a4'); // A4纸,纵向
    var ctx = canvas.getContext('2d');
    var a4w = type ? 277 : 190;
    var a4h = type ? 190 : 277; // A4大小,210mm x 297mm,四边各保留10mm的边距,显示区域190x277
    var imgHeight = Math.floor((a4h * canvas.width) / a4w); // 按A4显示比例换算一页图像的像素高度
    var renderedHeight = 0;
    while (renderedHeight < canvas.height) {
      var page = document.createElement('canvas');
      page.width = canvas.width;
      page.height = Math.min(imgHeight, canvas.height - renderedHeight); // 可能内容不足一页

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

      renderedHeight += imgHeight;
      if (renderedHeight < canvas.height) {
        pdf.addPage(); // 如果后面还有内容,添加一个空页
      }
      // delete page;
    }
    // 保存文件
    pdf.save(title + '.pdf');
  });
}
// pdf截断需要一个空白位置来补充
function getFooterElement(remainingHeight, fillingHeight = 0) {
  const newNode = document.createElement('div');
  newNode.style.background = '#ffffff';
  newNode.style.width = 'calc(100% + 8px)';
  newNode.style.marginLeft = '-4px';
  newNode.style.marginBottom = '0px';
  newNode.classList.add('divRemove');
  newNode.style.height = remainingHeight + fillingHeight + 'px';
  return newNode;
}
function isSplit(nodes, index, pageHeight) {
  // 判断是不是tr 如果不是高度存起来
  // 表格里的内容要特殊处理
  // tr.offsetTop 是tr到table表格的高度
  // 所以计算高速时候要把表格外的高度加起来
  // 生成的pdf没有表格了这里可以不做处理 直接计算就行
  if (nodes[index].localName !== 'tr') {
    //判断元素是不是tr
    noTableHeight += nodes[index].clientHeight;
  }

  if (nodes[index].localName !== 'tr') {
    return (
      nodes[index].offsetTop + nodes[index].offsetHeight < pageHeight &&
      nodes[index + 1] &&
      nodes[index + 1].offsetTop + nodes[index + 1].offsetHeight > pageHeight
    );
  } else {
    return (
      nodes[index].offsetTop + nodes[index].offsetHeight + noTableHeight < pageHeight &&
      nodes[index + 1] &&
      nodes[index + 1].offsetTop + nodes[index + 1].offsetHeight + noTableHeight > pageHeight
    );
  }
}

4,调用方式及页面id和class值添加,添加class="pdf-details"是为了处理分页隔断:

html 复制代码
function downloadPdf() {

  const lableList = document.getElementsByClassName('pdf-details');

  pageToPDF('降雨结论报告', document.querySelector('#rainReport'), lableList);

}
相关推荐
FungLeo2 小时前
成为全栈·React 管理后台篇·总复盘:从“接口能调通”到“后台值得使用”
前端·react.js·前端框架·项目复盘·成为全栈
Csvn3 小时前
并发模式:让渲染学会排队、插队和让路
前端
可乐鸡翅yeah_4 小时前
新手梳理:M3U8 线上问题,哪些是前端锅,哪些是后端锅
前端·ios·音视频·实时音视频·m3u8·音视频在线播放
Flynt4 小时前
Linear 用 1000 个 PR 换掉 styled-components,我写了 200 个按钮,把这笔账复现了一遍
前端·css·preact
JavaGuide5 小时前
NVIDIA 又开源了!这次给 AI Agent 加上权限管控
前端·后端
excel5 小时前
prisma 如何处理数据库竞态
前端·数据库·后端
莪_幻尘6 小时前
Skill 体检:30 个 Skill 全凭感觉?体检器先自曝了 8 个“假 0 分
前端·人工智能·llm
风骏时光牛马6 小时前
AI模型综合能力评测:性能、指令遵循与多场景实测对比
前端
Frag0ut6 小时前
Chrome与Chromium内核浏览器在Windows 11上的新特性全景解析
前端·chrome·windows·web安全·chromium·gemini ai·playready drm
hiahiahia1237 小时前
实现完整 Tool Dispatcher
开发语言·前端