本文提供一段 JS 打印功能的程式碼,可實現打印、打印預覽與打印頁面設置等操作,分享給大家參考。
這個範例透過 @media print 樣式隱藏不需要打印的元素,並呼叫瀏覽器的 ActiveX 打印控制項來實現進階的打印操作。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>打印功能示例</title>
<style>
@media print{ .noprint{ display:none } }
</style>
<script language=javascript>
function printsetup(){ // 打印頁面設置
wb.execwb(8,1);
}
function printpreview(){ // 打印頁面預覽
wb.execwb(7,1);
}
function printit(){
if (confirm('確定打印嗎?')){
wb.ExecWB(6,1) // 打印
}
}
</script>
</head>
<body>
<div class="noprint" style="width:640px;height:20px;margin:100px auto 0 auto;font-size:12px;text-align:right;">
<input value="打印" type="button" onclick="javascript:window.print()" />
<OBJECT classid="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2" height="0" id="wb" name="wb" width="0"></OBJECT>
<input type=button name=button_print style="display:none;" value="打印本單據" onclick="javascript:printit()">
<input type=button name=button_setup value="打印頁面設置" onclick="javascript:printsetup();">
<input type=button name=button_show value="打印預覽" onclick="javascript:printpreview();">
<input type=button name=button_fh value="關閉" onclick="javascript:window.close();">
</div>
<div style="width:640px;height:624px;margin:20px auto;">
這裡放置需要打印的內容
</div>
<div id="dd"></div>
</body>
</html>
程式碼中 wb.ExecWB 的參數對應不同的打印指令,例如 6 代表打印、7 代表打印預覽、8 代表打印頁面設置。透過 @media print 下的 .noprint 樣式,可以讓操作按鈕在打印時自動隱藏,只輸出真正需要打印的內容。需留意的是,這種基於 ActiveX 控制項的進階打印方式主要適用於 IE 系列瀏覽器,其他瀏覽器則可退回使用標準的 window.print()。