js打印图片

实现方案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()
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值