vue中使用html2canvas+jspdf将页面生成PDF

vue中使用html2canvas+jspdf将页面生成PDF


废话少说,直接上代码

1.htmlToPdf.js 代码片.

import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
function downloadPDF(ele, pdfName) {
  setTimeout(() => {
    var opts = { useCORS: true, // 允许加载跨域的图片
      allowTaint: false,
      tainttest: true, // 检测每张图片都已经加载完成
      logging: true,
      backgroundColor: 'white'
    }
    html2Canvas(document.querySelector(ele),opts).then(function (canvas) {
        let contentWidth = canvas.width
        let contentHeight = canvas.height
        let pageHeight = contentWidth / 592.28 * 841.89
        let leftHeight = contentHeight
        let position = 0
        let imgWidth = 595.28
        let imgHeight = 592.28 / contentWidth * contentHeight

        let pageData = canvas.toDataURL('image/jpeg', 0.2)   //第二个参数表示清晰度
        // console.log(pageData)
        let 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(pdfName + '.pdf')
      }
    )
  }, 1000);
}

export default {
  downloadPDF
}

vue中使用html2canvas+jspdf将页面生成PDF_第1张图片

页面调用代码片.

<el-button type="primary" size="small" @click="getPdf()">导出</el-button>

引用代码片.

  import htmlToPdf from "@/assets/js/htmlToPdf";

方法代码片.

   getPdf() {
      //导出PDF
      htmlToPdf.downloadPDF("#of-box", this.projectTitle + "统计分析");
    },

文章参考:https://blog.csdn.net/Cirzearchenille/article/details/103737045

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