實現方案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】插件,遇到在當前窗口彈出打印預覽時,動態路由會重新加載,並且頁面會初始化(不是動態路由的話,是沒問題的)(沒有打印預覽的瀏覽器也是沒問題的)