html2Canvas,jspdf,jszip,file-saver实现html批量导出pdf,打包成压缩包功能

<div v-for="item in currentData.codeList"
    :key="item.recipeCode">
  <recipeDetail :ref="'recipeDetail-'+item.recipeCode"
                :recipe-code="item.recipeCode"
                class="recipe-detail"
                @batchPrintNum="batchPrintNum" />
  <div style="page-break-after: always;" />
</div>
import html2Canvas from 'html2canvas'
import JSZip from 'jszip'
import FileSaver from 'file-saver'
import JsPDF from 'jspdf'

// 下载PDF
async getPoster() {
    
    
  try {
    
    
    await this.$nextTick()
    const doms = document.querySelectorAll('.detail') // 这里绑定你要转换的页面
    const zip = new JSZip()
    for (let i = 0; i < doms.length; i++) {
    
    
      const dom = doms[i]
      dom.style.background = '#FFFFFF'
      const canvas = await html2Canvas(dom, {
    
     // 开始截图
        scale: 4,
        allowTaint: true,
        useCORS: true,
        timeout: 10000
      })
      await this.$nextTick()

      const canvasWidth = canvas.width
      const canvasHeight = canvas.height
      const page = document.createElement('canvas')
      const a4w = 184.6 // pdf横向宽 210mm
      const vM = 12.7 // pdf横向边距和 25.4mm
      const hM = 15.9 // pdf纵向边距和 31.8mm
      page.width = canvasWidth
      page.height = canvasHeight // 可能内容不足一页
      const pdf = new JsPDF('p', 'mm', 'a4') // 纵向
      const ctx = canvas.getContext('2d')

      page.getContext('2d').putImageData(ctx.getImageData(0, 0, canvasWidth, canvasHeight), 0, 0) // 用getImageData剪裁指定区域,并画到前面创建的canvas对象中
      pdf.addImage(page.toDataURL('image/jpeg', 1.0), 'JPEG', vM, hM, a4w, a4w * page.height / page.width) // 添加图像到页面,保留10mm边距
      // 注意:this.currentData.codeList[i].name如果存在相同名称,则会覆盖,所以需要加-${i}区分
      await zip.file(`${
      
      this.currentData.codeList[i].name}-${
      
      i}.pdf`, pdf.output('blob'))
    }
    const content = await zip.generateAsync({
    
     type: 'blob' }) // 生成二进制流
    FileSaver.saveAs(content, 'XXX.zip') // 利用file-saver保存文件  自定义文件名
    this.loading.close()
    this.isVisible = false
  } catch (error) {
    
    
    this.isVisible = false
    this.loading.close()
    console.error(error)
    this.$message.warning('下载失败,请重试!')
  }
}

猜你喜欢

转载自blog.csdn.net/dncsdnf/article/details/127966485