实现方案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://yuan30-1304488464.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() }
以上实现demo https://yuan30-1304488464.cos.ap-guangzhou.myqcloud.com/blog/demo/print-img.html
对比
两种方法都能完美的实现打印预览效果
实现方案1 可以不影响当前窗口的任何结构,在新窗口进行打印操作
但是对于一些浏览器,打开新窗口是多余的
实现方案2 可以在当前窗口打开打印预览,这是很正常的操作
但是在react项目中,对于layout动态路由组件,我是使用的【react-loadable】插件,遇到在当前窗口弹出打印预览时,动态路由会重新加载,并且页面会初始化(不是动态路由的话,是没问题的)(没有打印预览的浏览器也是没问题的)