1. Use the printJs plug-in (priority)
printjs official website
printJS({
printable: [this.blobUrl],
type: 'pdf'
})
2. Using window.open
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 () {
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()
reader.readAsDataURL(blobUrl)
reader.addEventListener('loadend', () => {
nodeApi.sendnew('printResponsePdf', {
buffer: Buffer.from(
reader.result.split('base64,')[1],
'base64'
),
})
})
base64ToBlob() {
let imgSrc = this.imgUrl
let arr = imgSrc.split(',')
let array = arr[0].match(/:(.*?);/)
let mime = (array && array.length > 1 ? array[1] : type) || type
let bytes = window.atob(arr[1])
let ab = new ArrayBuffer(bytes.length)
let ia = new Uint8Array(ab)
for (let i = 0; i < bytes.length; i++) {
ia[i] = bytes.charCodeAt(i)
}
return new Blob([ab], {
type: mime,
})
},