1、使用printJs插件(優(yōu)先使用)
printjs官網(wǎng)文章來源地址http://www.zghlxwxcb.cn/news/detail-515415.html
// 官網(wǎng)文檔很詳細(xì)!
// 舉例如下:
printJS({
printable: [this.blobUrl],
type: 'pdf'
})
2、使用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、使用iframe方式
// 舉例如下:
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、在electron中封裝一個打印pdf的方法(這個一般用不到)
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轉(zhuǎn)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的頭,并轉(zhuǎn)化為byte
let bytes = window.atob(arr[1])
// 處理異常,將ascii碼小于0的轉(zhuǎn)換為大于0
let ab = new ArrayBuffer(bytes.length)
// 生成視圖(直接針對內(nèi)存):8位無符號整數(shù),長度1個字節(jié)
let ia = new Uint8Array(ab)
for (let i = 0; i < bytes.length; i++) {
ia[i] = bytes.charCodeAt(i)
}
return new Blob([ab], {
type: mime,
})
},
文章來源:http://www.zghlxwxcb.cn/news/detail-515415.html
到了這里,關(guān)于js幾種打印方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!