前端导出pdf文件

373 阅读1分钟

##前端导出pdf文件 在这上面我们需要采用两个安装包 // 导出页面为PDF格式

import html2Canvas from "html2canvas";
import JsPDF from "jspdf";

需要npm 下载 在pdfUtil.jf文件中创建方法

// 导出页面为PDF格式
import html2Canvas from "html2canvas";
import JsPDF from "jspdf";

export const htmlToPdf = async (dom, title) => {
  var pdfTitle = title; //pdf的名称
  var pdfDom = document.querySelector(dom);
  html2Canvas(pdfDom, {
    allowTaint: false,
    useCORS: true,
  }).then(function (canvas) {
    console.log(canvas);
    const marginBottom = 34; // 项目页面显示微处理 以下用到的地方 可以忽略
    let canvasWidth = canvas.width; //页面生成canvas宽度
    let canvasHeight = canvas.height + marginBottom; //页面生成canvas高度
    let pageHeight = (canvasWidth / 592.28) * 841.89 + marginBottom; //分页 每页的高度
    let allPageHeight = canvasHeight; // 所有页面的高度
    let position = 0; //偏移量
    let imgWidth = 595.28; //生成canvas 图片的宽度
    let imgHeight = (592.28 / canvasWidth) * canvasHeight; //生成canvas 图片的高度
    let pageData = canvas.toDataURL("image/jpeg", 3.0);
    // console.log(canvasWidth)
    // console.log(canvasHeight)
    // console.log(pageHeight)
    // console.log(allPageHeight)
    // console.log(position)
    // console.log(imgWidth)
    // console.log(imgHeight)
    // console.log(pageData)
    let PDF = new JsPDF("", "pt", "a4");
    if (allPageHeight < pageHeight) {
      PDF.addImage(pageData, "JPEG", 0, 0, imgWidth, imgHeight);
    } else {
      //循环生成分页
      while (allPageHeight > 0) {
        PDF.addImage(pageData, "JPEG", 0, position, imgWidth, imgHeight);
        allPageHeight = allPageHeight - pageHeight - marginBottom;
        position = position - 841.89 - marginBottom;
        if (allPageHeight > 0) {
          PDF.addPage(); //添加新的一页
        }
      }
    }
    PDF.save(pdfTitle + ".pdf"); //保存pdf
  });
};

在使用时 直接调用就可以了 👧