chrome实现直接打印
预览页自动点击打印
准备工作:
-
电脑连接打印机,并设置一个默认打印机
-
--kiosk-printing (chrome启动加该参数,这是在预览页自动点击打印按钮的)
在chrome的快捷方式这里加上该参数,重启chrome
function dayin(){
var newWindow=window.open('','_blank','width=1,height=1,top=10000,left=10000');
var html = "";// 这里的html可由别处传参,也可自己去接口获取
newWindow.document.write(html);
newWindow.document.close();
newWindow.print();
newWindow.close();
}
这样在chrome中调用这段js打印内容时,就可以实现直接打印。
window.open的方式有个缺陷,就是会弹出新窗口,虽然设置其位置不可见了,但是有的用户chrome的设置在弹出新窗口时会拦截,可以用iframe来解决。
var iframe = document.createElement('IFRAME');
iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;');
document.body.appendChild(iframe);
var doc = iframe.contentWindow.document;
doc.innerHTML = '要打印的html内容';
iframe.contentWindow.focus();
iframe.contentWindow.print();
document.body.removeChild(iframe);
r