react实现打印
基于window.print(),使用react-easy-print实现打印;
打印方式一:使用react-easy-print中组件包裹,调用windows.print()
<PrintProvider>
<Print printOnly name='disposal'>
<div>打印出来的样式,使用相对定位到左上角</div>
</Print>
<NoPrint>
<div>不打印DIV显示使用</div>
</NoPrint>
</PrintProvider>
// 打印
<div
className='list-table-button'
onClick={()=>{
windows.print()
}}
>
打印
</div>
打印方式二:使用iframe引入页面,打印页面;
print=(id)=>{
const el = document.getElementById(id);
const iframe = document.createElement('IFRAME');
let doc = null;
iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:500px;top:500px;');
document.body.appendChild(iframe);
doc = iframe.contentWindow.document;
// 引入打印的专有CSS样式,根据实际修改
// doc.write('<LINK rel="stylesheet" type="text/css" href="css/print.css">');
doc.write(el.innerHTML);
doc.close();
// 获取iframe的焦点,从iframe开始打印
iframe.contentWindow.focus();
iframe.contentWindow.print();
if (navigator.userAgent.indexOf("MSIE") > 0)
{
document.body.removeChild(iframe);
}
}
or
// 在app.js注册路由
<Route exact path='/print' component={Prints} />
// 在页面中使用
<iframe
frameBorder='0'
height={500}
width='100%'
src='/#/print'
rendermoney={JSON.stringify(capitalData)}
data={JSON.stringify(basicData)}
id='printIframe'
/>
// print页面接收参数
接收普通参数
componentDidMount() {
const printIframe = window.parent.document.getElementById('printIframe')
this.setState({
data:JSON.parse(printIframe.getAttribute('data')),
capitalData:JSON.parse(printIframe.getAttribute('rendermoney')),
}
}
接收函数 挂载在window对象上,组件注销时删除对象
window.printIframes = ()=>{
if(props.render){
return props.render()
}
return null
}
}
// 使用
{parent.printIframes()}
// 卸载
componentWillUnmount() {
delete window.printIframes;
}