天天看點

在react中實作局部頁面列印功能

最近遇到了列印頁面的問題。

使用window.print()列印,取消列印頁面,頁面會出現bug,需要用window.reload()重新加載一下頁面,使用者體驗很差。

1.為了解決該問題,可以使用iframe的方式解決:(但是設定列印區域樣式是個問題,隻能寫行内樣式)

代碼:

//确認列印
  printOk() {
  //擷取列印區域
    const printDiv= document.getElementById('printDiv');
    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;
    // 列印時去掉頁眉頁腳
    doc.write('<style media="print">@page {size: auto;  margin: 0mm; }</style>');
    
    doc.write(printDiv.innerHTML);
    doc.close();
    // 擷取iframe的焦點,從iframe開始列印
    iframe.contentWindow.focus();
    iframe.contentWindow.print();
    if (navigator.userAgent.indexOf("MSIE") > 0) {
    //列印完删除iframe
      document.body.removeChild(iframe);
    }
  }
           

2.去掉頁眉頁腳

3.列印内容可以通過設定style="page-break-before:always"實作分頁效果.

<div id='all' style={{marginTop:'20px',pageBreakAfter:'always'}}>
        </div>
      </div>