原生js打印 几种思路

155 阅读1分钟

借鉴参考抄袭 【解决方案】window.print()打印指定元素

print()只有在window对象种调用,不能指定需要打印的页面元素。

window对象只有在三个地方获取:

1、当前页面的window对象

2、iframe元素内的window对象

3、window.open方法生成的window对象

打印页面所有内容

window.print();

打印页面某个元素内容

  1. 当前页面的window对象
//将需要打印内容的元素内容覆盖到body下面去,调用window.print()。
//目标元素内容
let target = document.querySelector("#target").innerHTML;
//页面内容给body
document.body.innerHTML = target;
//页面打印
window.print();
//页面重新加载
window.location.reload()
  1. iframe元素内的window对象
//获取目标元素
let target = document.querySelector("#target-el");
//生成iframe
let iframeEl = document.createElement('iframe');
//元素放到底部
iframeEl.style.position = "fixed";
iframeEl.style.zIndex = -99;
//iframeEl添加到body
document.querySelector('body').append(iframeEl);
//获取iframe document
const documentEl = iframeEl.contentDocument;
documentEl.body.append(target.cloneNode(true));
//去除页眉页脚
const style = document.createElement('style');
style.media="print";
style.innerText = `
    @page{
        size:auto;
        margin:0mm;
    }
`;
documentEl.head.append(style);
//打印
documentEl.contentWindow.print();
//移除iframe
iframeEl.remove();
  1. window.open方法生成的window对象
let openWindow = window.open('','','','');
openWindow.document.write(document.querySelector("#target").innerHTML);
openWindow.print();
openWindow.close();
缺点:
当前窗口的window对象
  1. 当前窗口的window对象打印指定元素内容需要先把原来的页面内容置换
  2. 一些js生成的canvas内容无效,如echarts等,一些三方框架生成的页面,body里面夹杂着js,css替换了也会失效甚至报错。
iframe元素内的window对象
  1. 使用前后需要生成删除,且生成的iframe还不能影响原页面。
window.open方法生成的window对象
  1. 会有真实的弹窗影响视觉效果
思考
  1. 删除除了需要打印元素之外的所有元素,不好实现
  2. 其他的一些打印解决方案js后续我们继续探。