js several printing methods

1. Use the printJs plug-in (priority)

printjs official website

// 官网文档很详细!
// 举例如下:
printJS({
    
    
   printable: [this.blobUrl],
   type: 'pdf'
})

2. Using window.open

// 举例如下:
// 其中imgUrl为base64格式:'data:image/' + type + ';base64,' + ...
 let oWin = window.open(
  '',
    'pringwindow',
    'menubar=no,location=no,resizable=yes,scrollbars=no,status=no,width=1000,height=660'
  )
  oWin.document.fn = function () {
    
    
    if (oWin) {
    
    
      oWin.print()
      oWin.close()
    }
  }
  let html =
    '<div style="height: 100%;width: 100%;">' +
    `<img src="${
      
      this.imgUrl}" οnlοad="fn()" style="max-height:100%;max-width: 100%;" />` +
    '</div>'
  oWin.document.open()
  oWin.document.write(html)
  oWin.document.close()

3. Use iframe method

// 举例如下:
const iframe = document.createElement('iframe')

     iframe.style.height = 0
     iframe.style.visibility = 'hidden'
     iframe.style.width = 0

     iframe.setAttribute('srcdoc', '<html><body></body></html>')
     document.body.appendChild(iframe)

     iframe.addEventListener('load', function () {
    
    
       // 这里获取image的前提是html中有一个id为image的dom
       // 例如:<img id="image" :src="图片路径"/>
       const image = document.getElementById('image').cloneNode()
       image.style.maxWidth = '100%'

       const body = iframe.contentDocument.body
       body.style.textAlign = 'center'
       body.appendChild(image)
       image.addEventListener('load', function () {
    
    
         iframe.contentWindow.print()
       })
     })

	iframe.contentWindow.addEventListener('afterprint', function () {
    
    
	   iframe.parentNode.removeChild(iframe)
	})

4. Encapsulate a method of printing pdf in electron (this is generally not used)

 const reader = new FileReader()
 // blobUrl: 一个blob流
   reader.readAsDataURL(blobUrl)
    reader.addEventListener('loadend', () => {
    
    
      nodeApi.sendnew('printResponsePdf', {
    
    
        buffer: Buffer.from(
          reader.result.split('base64,')[1],
          'base64'
        ),
    })
})

// 提供一个base64转blob的方式吧
 base64ToBlob() {
    
    
   let imgSrc = this.imgUrl // imgUrl为base64格式的路径

   let arr = imgSrc.split(',')
   let array = arr[0].match(/:(.*?);/)
   let mime = (array && array.length > 1 ? array[1] : type) || type
   // 去掉url的头,并转化为byte
   let bytes = window.atob(arr[1])
   // 处理异常,将ascii码小于0的转换为大于0
   let ab = new ArrayBuffer(bytes.length)
   // 生成视图(直接针对内存):8位无符号整数,长度1个字节
   let ia = new Uint8Array(ab)
   for (let i = 0; i < bytes.length; i++) {
    
    
    ia[i] = bytes.charCodeAt(i)
   }
   return new Blob([ab], {
    
    
     type: mime,
   })
 },

Guess you like

Origin blog.csdn.net/weixin_45630345/article/details/129850789