react中打印的使用


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM