实现方案1
通过打开新窗口的方式打印图片
function printNewWindow(imgSrc) {
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="${imgSrc}" onload="fn()" style="max-height:100%;max-width: 100%;" />` + '</div>'
oWin.document.open()
oWin.document.write(html)
oWin.document.close()
}
// printNewWindow('https://web03-1252477692.cos.ap-guangzhou.myqcloud.com/blog/images/67628ac324e240f8bf8d29232a87fde0.jpg')"
实现方案2
将img放入iframe,然后在当前窗口调用打印iframe
function printThisWindow(imgSrc) {
let iframe = document.createElement('IFRAME')
let doc = null
iframe.setAttribute('class', 'print-iframe')
iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;')
document.body.appendChild(iframe)
doc = iframe.contentWindow.document
// 取一个不重复的方法名称,可以随机字符串
doc.___imageLoad___ = function () {
iframe.contentWindow.print()
if (navigator.userAgent.indexOf('MSIE') > 0) {
document.body.removeChild(iframe)
}
}
doc.write('<div style="height: 100%;width: 100%;">' + `<img src="${imgSrc}" style="max-height:100%;max-width: 100%;" onload="___imageLoad___()"/>` + '</div>')
doc.close()
iframe.contentWindow.focus()
}
网页图片打印技巧
1445

被折叠的 条评论
为什么被折叠?



