方案一:WebBrowser 控件(IE 內核,僅限 Windows/IE 瀏覽器)
核心代碼
<OBJECT classid="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"
id="wb" width="0" height="0"></OBJECT>
<script>
function printSetup() { wb.execWB(8, 1); } // 頁面設置
function printPreview() { wb.execWB(7, 1); } // 打印預覽
function doPrint() {
if (confirm('確定打印?')) wb.execWB(6, 6); // 直接打印
}
</script>
<input type="button" value="頁面設置" onclick="printSetup()">
<input type="button" value="打印預覽" onclick="printPreview()">
<input type="button" value="打印" onclick="doPrint()">
ExecWB 常用命令對照表
| 命令 ID | 功能 |
| 1 | 打開 |
| 4 | 保存網頁 |
| 6 | 打印 |
| 7 | 打印預覽 |
| 8 | 頁面設置 |
| 10 | 屬性 |
| 17 | 全選 |
| 22 | 刷新 |
| 45 | 無提示關閉窗口 |
進階設置腳本(ScriptX/MEADCO 控件)
factory.printing.SetMarginMeasure(2); // 英寸制
factory.printing.header = "頁眉內容";
factory.printing.footer = "頁腳內容";
factory.printing.portrait = false; // 橫向
factory.printing.leftMargin = 1.0;
factory.printing.topMargin = 1.0;
factory.printing.rightMargin = 1.0;
factory.printing.bottomMargin = 1.0;
方案二:CSS 分頁打印(跨瀏覽器,推薦)
<style>
@media print {
.page-break { page-break-after: always; } // 強制分頁
.no-print { display: none; } // 隱藏按鈕等
}
</style>
<body>
<% while (!rs.eof) { %>
<div class="page-break">
<%= rs.getString(1) %>
</div>
<% rs.next(); } %>
</body>
現代替代方案對比
| 方案 | 優點 | 缺點 | 適用場景 |
| WebBrowser 控件 | 功能豐富、可控制打印機參數 | 僅 IE/Windows、需 ActiveX 權限 | 內網 IE 專用系統 |
| CSS @media print | 跨平台、無插件、標準化 | 無法控制打印機硬件設置 | 現代 Web 應用首選 |
| PDF.js + pdfMake | 生成精確 PDF、支持下載存檔 | 需前端生成邏輯 | 報表、發票、合同 |
| JasperReports/iText | 服務端生成複雜報表 | 後端開發成本高 | 企業級報表系統 |
最佳實踐建議
- 優先使用
@media print + 語義化 HTML 結構
- 打印區域獨立模板,隱藏導航/按鈕
.no-print { display:none }
- 表格跨頁處理:
thead { display: table-header-group; }
- 頁碼/水印:
@page { @bottom-center { content: counter(page) } }