VUE 获取PDF文档流直接打印

2023-10-25  本文已影响0人  我是七月

一、项目需求

前端点击按钮直接调起打印对应pdf文档。

1663602-20221109172929800-510189448.png

二、踩坑

刚开始通过api获取后端给的PDF地址,创建一个隐藏的iframe标签src设置为pdf地址;前端通过获取隐藏的iframe标签的id来实现打印指定内容;

存在iframe跨域问题,不能直接调起print()方法,取消iframe隐藏虽然能看到加载出pdf,但多了点击打印按钮的步骤。

1663602-20221109173842631-2004083627.png

三、解决方法

api改为获取pdf文档流,前端将文档流转为blob地址,放到js创建的隐藏iframe标签内;再执行print()方法。

PrintBtnClick(record){
      PrintApplication({projectId:record.projectId}).then(res=>{
          const blob = new Blob([res.data], { type: 'application/pdf' })
          var date = (new Date()).getTime()
          var ifr = document.createElement('iframe')
          ifr.style.frameborder = 'no'
          ifr.style.display = 'none'
          ifr.style.pageBreakBefore = 'always'
          ifr.setAttribute('id', 'printPdf' + date)
          ifr.setAttribute('name', 'printPdf' + date)
          ifr.src = window.URL.createObjectURL(blob)
          document.body.appendChild(ifr)
          this.doPrint('printPdf' + date)
          window.URL.revokeObjectURL(ifr.src) // 释放URL 对象
      })
},
doPrint(val) {
      var ordonnance = document.getElementById(val).contentWindow
      setTimeout(() => {
        ordonnance.print()
      }, 100)
}
1663602-20221109180215062-1243190305.gif
上一篇 下一篇

猜你喜欢

热点阅读