VUE 获取PDF文档流直接打印

一、项目需求

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

 

二、踩坑

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

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

 

三、解决方法

  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)
}

 

posted @ 2022-11-09 18:02  Vition  阅读(4713)  评论(6编辑  收藏  举报