js實現瀏覽器列印功能

最近接觸到一個新需求,實現印表機列印小票的功能。打的一桌子小票(慚愧),不過也基本滿足了業務上的需求,現在分享一下如何實現(好記性不如爛筆頭)

先上程式碼

// 布局程式碼
<div id=”print”>
    <div id=”print_content”></div>
</div>



//js 部分程式碼
var
f = document.getElementById('printf'); if (f) { document.getElementById("print_content").removeChild(f); } var printhtml = ` <div style="font-size:12px;margin-left: -6px;"> <p style="margin-left:40px;">${this.ticket.title}</p> <p>--------------------------------------</p> <p>提貨點:${this.ticket.pickUpAddress}</p> <p>商品名稱:${this.ticket.commodityName}</p> <p>下單時間:${this.ticket.paymentTime}</p> <p>提貨人:${this.ticket.receiver}</p> <p>聯繫電話:${this.ticket.receiverPhone}</p> <p>提貨碼:${this.ticket.pickUpCode}</p> <p>提貨時間:${this.ticket.submissionTime}</p> <p style="color:#FFFFFF">.</p> </div>` if (!!window.ActiveXObject || "ActiveXObject" in window) { // 針對IE進行適配 var HKEY_Root, HKEY_Path, HKEY_Key; HKEY_Root = "HKEY_CURRENT_USER"; HKEY_Path = "\\Software\\Microsoft\\Internet Explorer\\PageSetup\\"; //設置網頁列印的頁眉頁腳為空 function PageSetup_Null() { var Wsh = new ActiveXObject("WScript.Shell"); HKEY_Key = "header"; Wsh.RegWrite(HKEY_Root + HKEY_Path + HKEY_Key, ""); HKEY_Key = "footer"; Wsh.RegWrite(HKEY_Root + HKEY_Path + HKEY_Key, ""); HKEY_Key = "margin_left" Wsh.RegWrite(HKEY_Root + HKEY_Path + HKEY_Key, "0"); //鍵值設定--左邊邊界 HKEY_Key = "margin_top" Wsh.RegWrite(HKEY_Root + HKEY_Path + HKEY_Key, "0"); //鍵值設定--上邊邊界 HKEY_Key = "margin_right" Wsh.RegWrite(HKEY_Root + HKEY_Path + HKEY_Key, "0"); //鍵值設定--右邊邊界 HKEY_Key = "margin_bottom" Wsh.RegWrite(HKEY_Root + HKEY_Path + HKEY_Key, "0"); //鍵值設定--下邊邊界 } printhtml = ` <div style="font-size:12px;font-weight: 800;height:150px;width:300px"> <p style="margin-left:35px">${this.ticket.title}</p> <p>------------------------------------------------</p> <p>提貨點:${this.ticket.pickUpAddress}</p> <p>商品名稱:${this.ticket.commodityName}</p> <p>下單時間:${this.ticket.paymentTime}</p> <p>提貨人:${this.ticket.receiver}</p> <p>聯繫電話:${this.ticket.receiverPhone}</p> <p>提貨碼:${this.ticket.pickUpCode}</p> <p>提貨時間:${this.ticket.submissionTime}</p> <p style="color:#FFFFFF;font-weight: 100;">.</p> </div>` } var iframe = document.createElement('iframe'); iframe.id = 'printf'; iframe.style.width = '0'; iframe.style.height = '0'; iframe.style.border = "none"; document.getElementById("print_content").appendChild(iframe); setTimeout(() => { iframe.contentDocument.write(printhtml); iframe.contentDocument.close(); iframe.contentWindow.focus(); iframe.contentWindow.print(); }, 100)

因為要求不能把列印的數據顯示在頁面上,所以通過iframe的方式去實現。單純的截取字元串重新賦值body內容能進行列印卻把列印的內容展現在頁面中了,所以不行。

列印針對IE的瀏覽器進行了一定程度的調整,IE列印要做特定的處理,詳見上面判斷程式碼。列印內容通過模板字元串加內聯樣式去實現。滿足了基本需求。

是否應該也通過截取頁面字元串的方式去做可能比較浪費性能些,為什麼這麼說?因為樣式在列印的小票上有一定程度的偏差,修了東牆破了西牆,只能採取相對的方式取捨。如果這種寫法不滿足,可以採取截取字元串寫class嘗試。