vue中页面导出为pdf

需要用到html2canvas,JsPDF这2个插件

yarn add html2canvas jspdf
   const loading = this.$loading({
        lock: true,
        text: "正在生成PDF文件...",
        spinner: "el-icon-loading",
        background: "hsla(0,0%,100%,.9)",
      });
     const html = document.getElementById("container"); //需要导出的标签页

	this.savePdf(
	  html,
	  loading,
	  `文件名.pdf`
	);

savePdf

savePdf(el, loading, title) {
  html2canvas(el, {
    useCORS: true,
    allowTaint: true,
  })
    .then((canvas) => {
      // 内容的宽度
      const contentWidth = canvas.width;
      // 内容高度
      const contentHeight = canvas.height;
      // 一页pdf显示html页面生成的canvas高度,a4纸的尺寸[595.28,841.89];
      const pageHeight = (contentWidth / 592.28) * 841.89;
      // 未生成pdf的html页面高度
      let leftHeight = contentHeight;
      // 页面偏移
      let position = 0;
      // a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
      const imgWidth = 595.28;
      const imgHeight = (592.28 / contentWidth) * contentHeight;
      // canvas转图片数据
      const pageData = canvas.toDataURL("image/jpeg", 1.0);
      // 新建JsPDF对象
      const PDF = new JsPDF("", "pt", "a4");
      // 判断是否分页
      if (leftHeight < pageHeight) {
        PDF.addImage(pageData, "JPEG", 0, 0, imgWidth, imgHeight);
      } else {
        while (leftHeight > 0) {
          PDF.addImage(pageData, "JPEG", 0, position, imgWidth, imgHeight);
          leftHeight -= pageHeight;
          position -= 841.89;
          if (leftHeight > 0) {
            PDF.addPage();
          }
        }
      }
      // 保存文件
      PDF.save(title + ".pdf");
    })
    .catch(() => {})
    .finally(() => {
      loading.close();
    });
},

你可能感兴趣的:(vue.js,pdf,前端)