react项目内,要兼容不同的浏览器实现打印、打印预览功能,非IE浏览器统一采用了window.print()方法,IE浏览器采用它自带的ActiveX。代码如下:
const Wtest = (props) =>{
const printOpeation = (val) => {
switch (val) {
case 1:
//点击打印
if (!!window.ActiveXObject || "ActiveXObject" in window) {
document.getElementById("factory").printing.portrait = true;//设置打印方向
document.all.WebBrowser.ExecWB(6, 1)
} else {
print('printDiv')
}
break;
case 2: //打印预览
if (!!window.ActiveXObject || "ActiveXObject" in window) {
document.getElementById("factory").printing.portrait = true;//设置打印方向
document.all.WebBrowser.ExecWB(7, 1)
} else {
print('printDiv')
}
break;
default:
break;
}
}
//打印
const print = (id) => {
var newstr = document.getElementById(id).innerHTML;
var oldstr = document.body.innerHTML;
document.body.innerHTML = newstr;
window.print();
document.body.innerHTML = oldstr;
//此处针对需求写的,可不写
if (myBrowser() !== 'Chrome') {
window.location.reload();
}
}
return(
<div style={{ width: '600px', margin: 'auto', padding: '20px 0', display: propsData.type ? 'inline-block' : 'block' }}>
{/* 将不打印的内容设置noprint样式 */}
<div style={{ textAlign: 'center' }} className="Noprint">
<object id="WebBrowser" classID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2" style={{ height: 0, width: 0 }}>
</object>
<input type="button" style={{ marginRight: 8 }} value="打印" onClick={() => printOpeation(1)} />
<input type="button" style={{ marginRight: 8 }} value="打印预览" onClick={() => printOpeation(2)} />
</div>
<div id='printDiv'>
打印的内容
</div>
)
}
主要代码如上所示,在非IE浏览器内都没有什么问题,window.print()自带预览,也可正常打印,但在IE浏览器内打印预览时只显示第一页的内容,打印也只有一页,研究很久发现是react的问题。
react组件内使用IE的ActiveX会导致多页打印时只显示一页!!!
目前采用的解决办法是针对IE浏览器单独写了一份要打印的页面的html文件,文件内全部采用原生的方法,将文件放入public文件夹内,打包后文件也会存在。
我的项目内在进入打印页面前有一个点击操作,在这里判断浏览器类型,然后直接进入不同的页面。
if (!!window.ActiveXObject || "ActiveXObject" in window) { //判断是否为IE浏览器
sessionStorage.setItem('IEDatasource', xxx);//可以将需要的数据存进sessionStorage
window.open('about:blank').location.href = `http://${window.location.host}/IEPage.html`;
return;
}