JS利用iframe实现局部打印 - 戴向天

大家好!我叫戴向天

QQ群:602504799

如若有不理解的,可加QQ群进行咨询了解
sheetToSelf 代码===》https://blog.csdn.net/weixin_41088946/article/details/106767106

由于我在开发的时候项目中含有echart。所以在开始的时候对canvas进行了下处理

// 将canvas的内容转换成图片并进行插入到dom里面去
    document.querySelectorAll('canvas').forEach(canvas => {
      const img = document.createElement('img')
      img.setAttribute('src', canvas.toDataURL("image/png"))
      img.setAttribute('class', 'canvasImage')
      const parentNode = canvas.parentNode.parentNode
      parentNode.parentNode.insertBefore(img, parentNode)
    })
    // 获取到打印的内容
    const jubuData = document.getElementById("print").innerHTML;
    // 去掉新增的图片
    document.getElementById("print").querySelectorAll('.canvasImage').forEach(item => {
      item.parentNode.removeChild(item)
    })
    const containerBox = document.createElement('div');
    const container = document.createElement('div');
    containerBox.appendChild(container)
    container.innerHTML = jubuData
    container.querySelectorAll('canvas').forEach(canvas => {
      canvas.parentNode.parentNode.parentNode.removeChild(canvas.parentNode.parentNode)
    })
    document.body.appendChild(containerBox)
    sheetToSelf(container)
    const iframe = document.getElementById('printf') as any;
    const doc = document.all ? iframe.contentWindow.document : iframe.contentDocument;
    doc.open();
    doc.write(container.innerHTML);
    doc.close();
    document.body.removeChild(containerBox)
    iframe.contentWindow.focus();
    // iframe加载完成后再执行打印
    iframe.contentWindow.onload = function () {
      iframe.contentWindow.print()
    }

猜你喜欢

转载自blog.csdn.net/weixin_41088946/article/details/106810632