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('下载失败,请重试!')
  }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值