js几种打印方法
1、使用printJs插件(优先使用)
printjs官网
// 官网文档很详细!
// 举例如下:
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 ='' +`
${this.imgUrl}" οnlοad="fn()" />` +''oWin.document.open()oWin.document.write(html)oWin.document.close()
3、使用iframe方式
// 举例如下:
const iframe = document.createElement('iframe')iframe.style.height = 0iframe.style.visibility = 'hidden'iframe.style.width = 0iframe.setAttribute('srcdoc', '')document.body.appendChild(iframe)iframe.addEventListener('load', function () {// 这里获取image的前提是html中有一个id为image的dom// 例如:
const image = document.getElementById('image').cloneNode()image.style.maxWidth = '100%'const body = iframe.contentDocument.bodybody.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转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的头,并转化为bytelet bytes = window.atob(arr[1])// 处理异常,将ascii码小于0的转换为大于0let 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,})},
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
