DIV CSS 佈局教程網

用 jQuery 列印 PDF、圖片與文字檔的簡便寫法
編輯:JQuery特效代碼     

有些需求是「讓使用者點一下就列印某個檔案」,可能是 PDF、圖片或純文字。與其研究各種格式各自的列印 API,不如讓瀏覽器自己處理:把檔案塞進隱藏的 iframe,再呼叫 iframe 的 print()。

頁面要加的片段

<div style="display:none">
  <div id="to_print"></div>
  <input type="button" id="print_button" value="Print"
         onclick="document.getElementById('FILEtoPrint').focus(); document.getElementById('FILEtoPrint').contentWindow.print();" />
</div>
<script>
function printSome(path) {
    // path 傳入要列印的檔案路徑
    $("#to_print").html('<iframe src=' + path + ' id="FILEtoPrint"></iframe>');
    setTimeout(function () { $("#print_button").click(); }, 500);
}
</script>

運作流程

  1. printSome(path) 被呼叫時,用 jQuery 把一個 iframe 動態塞進 #to_print,src 指向目標檔案。
  2. 間隔 500 毫秒後,程式觸發隱藏按鈕的 click。
  3. 按鈕的 onclick 先 focus() 讓 iframe 取得焦點,再呼叫 contentWindow.print() 叫出瀏覽器列印對話框。

界面上的呼叫方式

在需要列印的位置放一顆按鈕,把路徑傳進去即可:

<input type="button" value="列印報表" onclick="printSome('files/report.pdf')" />

實務上的注意事項

那 500 毫秒是經驗值。iframe 尚未載完就呼叫 print(),會出現空白頁或完全沒反應。比較穩健的做法是監聽 iframe 的 load 事件,在真正載入完成後再觸發列印,而不是用固定延時硬猜。

跨來源檔案會失敗。如果 iframe 的 src 指向不同網域,瀏覽器的同源政策會讓你無法取得 contentWindow,此時需要把檔案放到同來源,或改用後端產生 PDF 再提供下載。

使用者體驗。print() 開啟的是瀏覽器原生對話框,使用者仍可取消,所以別把「按下按鈕」等同於「已經列印」。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved