瀏覽器(尤其 IE)提供了不少列印控制能力,從整頁列印、只印部分內容,到自訂頁首頁尾、列印背景色,都能用程式或設定達成。以下依情境整理。(註:其中多數 ActiveX/WebBrowser 做法僅適用於舊版 IE。)
window.print();
方法一:用 CSS 的 @media print 控制顯示,把不想列印的部分設為隱藏:
@media print {
.a { display: block; }
.Noprint { display: none; } /* 不想列印的元素加上這個 class */
}
方法二:用 JavaScript 擷取標記之間的內容再列印:
<script language="javascript">
function doPrint() {
var bdhtml = window.document.body.innerHTML;
var sprnstr = "<!--startprint-->";
var eprnstr = "<!--endprint-->";
var prnhtml = bdhtml.substr(bdhtml.indexOf(sprnstr) + 17);
prnhtml = prnhtml.substring(0, prnhtml.indexOf(eprnstr));
window.document.body.innerHTML = prnhtml;
window.print();
}
</script>
<a href="javascript:;" onClick="doPrint()">列印</a>
只要在要列印的正文前後加上 <!--startprint--> 與 <!--endprint--> 註解即可。
透過寫入 IE 的 PageSetup 登錄機碼,可清空或設定頁首頁尾:
<script language="JavaScript">
var hkey_root, hkey_path, hkey_key;
hkey_root = "HKEY_CURRENT_USER";
hkey_path = "Software\\Microsoft\\Internet Explorer\\PageSetup";
function pagesetup_null(){ // 清空頁首頁尾
try{
var RegWsh = new ActiveXObject("WScript.Shell");
RegWsh.RegWrite(hkey_root+hkey_path+"header", "");
RegWsh.RegWrite(hkey_root+hkey_path+"footer", "");
}catch(e){}
}
</script>
頁首頁尾可用的符號:&w 網頁標題、&u 網址、&d/&D 短/長日期、&t/&T 時間、&p 當前頁碼、&P 總頁數、&b 右對齊、&& 單個 & 號。例如頁腳設為 &b第 &p 頁 / 共 &P 頁&b 可置中顯示頁碼。
可用 IE 的 WebBrowser 元件,透過 ExecWB 呼叫各項功能:
<OBJECT classid="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2" height="0" id="WebBrowser" width="0"></OBJECT> <input type="button" value="列印" onClick="document.all.WebBrowser.ExecWB(6,1)"> <input type="button" value="直接列印" onClick="document.all.WebBrowser.ExecWB(6,6)"> <input type="button" value="列印預覽" onClick="document.all.WebBrowser.ExecWB(7,1)"> <input type="button" value="頁面設定" onClick="document.all.WebBrowser.ExecWB(8,1)">
也可使用 ScriptX.cab 之類的第三方控件,設定頁首頁尾、邊界、紙張與列印範圍等進階參數。使用 ActiveX 時,需在 IE 安全性設定中允許「未標記為安全的 ActiveX 控件」;在 Visual Studio 編輯時也要留意它可能自動加入多餘參數而導致出錯。
IE 預設不印背景,若需要,可到【工具】→【Internet 選項】→【進階】→ 勾選「列印背景色彩和圖像」。
最簡單的方式:用滑鼠選取要列印的內容,按右鍵選「列印」,在列印視窗的「頁面範圍」中選擇「選取範圍」即可。