使用html2canvas+jspdf将页面转为pdf并下载

发布时间 2023-03-24 09:45:06作者: 潇潇mini

1、安装html2canvas和jspdf

npm install html2canvas
npm install jspdf

2、新建文件htmlToPdf.ts

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

export function getPdf(title: string) {
  const pdfDom: any = document.querySelector('#pdfDom');
  pdfDom.classList.add("pdfDom-print");   //重写样式

  html2Canvas(pdfDom, {
    allowTaint: true
  })
    .then(function (canvas) {
      const contentWidth = canvas.width
      const contentHeight = canvas.height
      const pageHeight = contentWidth / 592.28 * 841.89
      let leftHeight = contentHeight;
      let position = 0
      const imgWidth = 595.28
      const imgHeight = 592.28 / contentWidth * contentHeight
      const pageData = canvas.toDataURL('image/jpeg', 1.0)
      const PDF = new JsPDF(undefined, 'pt', 'a4');     //方向,pt:页面计算单位,a4:页面大小为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');
    })

  // 移除样式
  pdfDom.classList.remove("pdfDom-print");
}

3、引用ts文件并声明此方法

import { getPdf } from '@/core/utils/htmlToPdf2';

 getPdf() {
    getPdf("黄浦区适龄幼儿入园报名信息");   //下载文件名
  }

4、页面使用

<button @click.native="getPdf">导出至PDF</button>