react + antd 實現打印功能(踩了很多坑)

最近在有網頁打印需求,嘗試了一下react的打印功能,遇到了很多的坑:css

1.react自己有一些打印的組件,但都很差用,都是基於window.print(),可是window.print()若是直接打印的話,沒有樣式。處理直接當前網頁的body設置爲你要打印的區域,可是當你取消打印的時候你會發現整個網頁都被你要打印的區域佔滿了,你還得用window.reload()從新加載一下頁面,用戶交互很很差,建議不要採用這種方式。前端

2.樣式的問題,咱們能夠經過寫內聯樣式解決,嘗試了react的react-inline-css也沒試成功。因此,當你頁面有打印功能時,打印的區域最好是用內聯樣式完成。react

3.爲了解決1中提到的用戶交互問題,可使用iframe的方式解決,具體單面以下:canvas

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

4.二維碼沒法打印問題:react中通常生成二維碼都是用react.qrcode,可是發現這玩意生成的是canvas,不是圖片,打印的時候預覽不出來。因此我想進一切辦法去把canvas轉成圖片,無奈拿不到這個canvas標籤。最後仍是用js的qrcode來生成二維碼,這樣生成的默認是base64位的圖片,打印正常。代碼以下:app

const QRCode =  require('qrcode')

// 因爲是異步的生成,因此最好是經過設置狀態來改變二維碼圖片
getCode =(value) =>{ QRCode.toDataURL(value) .then(url => { this.setState({ qrcodeImg:url }) }) .catch(err => { console.error(err) }) }
// 前端經過<div><img src={this.state.qrcodeImg} style={{width:"100px",height:"
100px"}}></img></div> 得到

踩了很多坑,但願對你們有幫助。。。。異步

相關文章
相關標籤/搜索