Skip to content

前端实现返回的Blob流PDF文件打印

使用iframe并解决跨域问题

js
btn_dyfp() { // 打印按钮触发方法
  downloadBswj({}).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)
},
btn_dyfp() { // 打印按钮触发方法
  downloadBswj({}).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)
},