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;
}