萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript/jQuery 頁面列印與局部列印完整解決方案:CSS @media print、iframe 隔離、PrintArea 插件實戰

網頁列印完全指南:從簡單 window.print() 到專業級局部列印、樣式控制、分頁處理

列印功能看似簡單,實際專案中常面臨:只列印局部區域、隱藏導航/廣告、調整列印樣式、處理分頁斷行、跨瀏覽器相容等挑戰。本文系統整理三種主流方案,提供生產可用的程式碼與最佳實踐。

方案一:CSS @media Print (最輕量、無依賴、標準做法)

核心原理

利用 CSS @media print 定義列印專用樣式,配合 window.print() 觸發列印對話框。

實作範例

<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>列印 Demo</title>
<style>
  /* 螢幕樣式 */
  .noprint { display: block; }
  .print-only { display: none; }
  .page-break { page-break-after: always; }

  /* 列印樣式 */
  @media print {
    .noprint { display: none !important; }      /* 隱藏導航、按鈕、廣告 */
    .print-only { display: block !important; }  /* 顯示僅列印內容 (如水印、版權) */
    .page-break { page-break-after: always; }   /* 強制分頁 */
    body { font-size: 12pt; margin: 0; }        /* 列印字體/邊距 */
    a[href]::after { content: " (" attr(href) ")"; } /* 顯示連結網址 */
  }
</style></head><body>

<button class="noprint" onclick="window.print()">列印本頁</button>
<div class="noprint">這行不會被列印</div>

<div class="print-only">機密文件 - 僅限內部列印</div>

<h1>報表標題</h1>
<div class="content">...大量內容...</div>
<div class="page-break"></div> <!-- 強制分頁 -->
<h1>續頁標題</h1>
<div class="content">...續頁內容...</div>

<script>
// 可選:列印前/後事件 (IE/Edge 支援有限)
window.onbeforeprint = () => console.log('準備列印');
window.onafterprint = () => console.log('列印完成/取消');
</script>
</body></html>

關鍵 CSS 列印屬性

屬性作用值範例
page-break-before元素前強制分頁always, avoid, left, right
page-break-after元素後強制分頁always, avoid
page-break-inside避免元素內部分頁avoid (表格、卡片必加)
@page頁面邊距/方向/尺寸@page { margin: 2cm; size: A4 landscape; }
orphans/widows段落首尾行最少保留行數orphans: 3; widows: 3;

方案二:jQuery PrintArea 插件 (局部列印、舊專案常用)

原理:將目標區域複製到隱藏 <iframe>,觸發 iframe 列印,避免污染主頁面樣式。

引入與使用

<script src="jquery.min.js"></script>
<script src="jquery.PrintArea.js"></script> <!-- 需自行下載 -->

<button id="btn-print-area">列印報表區域</button>
<div id="report-area">
  <h2>銷售報表</h2>
  <table>...</table>
</div>

<script>
$('#btn-print-area').on('click', function () {
    $('#report-area').printArea({
        mode: 'iframe',        // 'popup' 或 'iframe' (推薦 iframe)
        popHt: 600,            // popup 高度
        popWd: 800,            // popup 寬度
        popTitle: '報表列印',   // 標題
        standard: 'html5',     // 文件型別
        extraCss: '/css/print-report.css', // 額外列印樣式
        retainAttr: ['id', 'class', 'style'], // 保留屬性
        onPrint: function () { console.log('列印觸發'); }
    });
});
</script>

PrintArea 核心流程 (源碼簡析)

  1. 建立隱藏 <iframe> 附加到 body。
  2. 複製目標元素 outerHTML 寫入 iframe document.body。
  3. 引入 extraCss 與頁面現有 <link rel="stylesheet" media="print">。
  4. 呼叫 iframe.contentWindow.print()。
  5. 列印完成後移除 iframe。

方案三:原生 iframe 手動實現 (無依賴、完全可控)

function printElement(elementId, options = {}) {
    const el = document.getElementById(elementId);
    if (!el) return;

    const iframe = document.createElement('iframe');
    iframe.style.cssText = 'position:absolute;width:0;height:0;border:none;left:-9999px;';
    document.body.appendChild(iframe);

    const doc = iframe.contentDocument || iframe.contentWindow.document;
    // 複製樣式
    const styles = Array.from(document.querySelectorAll('style, link[rel="stylesheet"]'))
        .map(n => n.outerHTML).join('');
    // 寫入內容
    doc.write('' + styles +
              (options.extraCss ? '' : '') +
              '' + el.outerHTML + '');
    doc.close();

    iframe.onload = function () {
        iframe.contentWindow.focus();
        iframe.contentWindow.print();
        // 延遲移除,確保列印對話框已開啟
        setTimeout(() => document.body.removeChild(iframe), 1000);
    };
}

// 使用
printElement('report-area', { extraCss: '/css/print.css' });

方案對比與選型建議

方案優點缺點適用場景
CSS @media print零依賴、標準、效能最好、SEO 友善、支援 @page 精細控制無法「只列印某區域」需靠隱藏其他區域實現全頁列印、報表、發票、簡單頁面
PrintArea 插件API 簡單、自動處理 iframe、支援 extraCss依賴 jQuery、維護停滯、iframe 樣式隔離有時不完美舊專案 jQuery 技術棧、快速加入局部列印
原生 iframe 手寫零依賴、完全可控、可注入任意 CSS/JS需自行處理樣式複製、跨域 iframe 限制、字體載入時序現代專案、需高度客製化列印輸出
html2canvas + jsPDF像素級截圖生成 PDF、跨瀏覽器像素一致大量 DOM 效能差、字體/陰影/Canvas 尺寸限制、文字不可選證書生成、複雜圖表導出 PDF、需離線存檔

進階技巧:列印前動態生成內容

// 列印前從 API 獲取最新資料渲染,再列印
async function printLatestReport() {
    showLoading();
    const data = await fetch('/api/report/latest').then(r => r.json());
    renderReport(data); // 更新 DOM
    await waitForFontsAndImages(); // 確保字體/圖片載入完成
    window.print();
    hideLoading();
}

function waitForFontsAndImages() {
    return Promise.all([
        document.fonts.ready,
        ...Array.from(document.images).filter(img => !img.complete)
            .map(img => new Promise(r => { img.onload = img.onerror = r; }))
    ]);
}

常見問題 FAQ

  1. 列印出來空白/樣式錯亂:檢查 iframe 寫入時機 (onload 後)、CSS 路徑是否為絕對路徑、@media print 是否生效。
  2. 表格跨頁被切斷:加 table { page-break-inside: avoid; }、thead { display: table-header-group; } 重複表頭。
  3. 背景顏色/圖片不列印:瀏覽器預設不列印背景,用戶需在列印對話框勾選「背景圖形」,或改用 border 模擬。
  4. 頁碼/水印:@page { @bottom-center { content: counter(page); } } (支援度有限),或用 html2pdf.js 產生 PDF 後列印。

根據專案技術棧與需求複雜度選擇方案,CSS @media print 為首選,局部列印次之,複雜報表導出 PDF 再列印最專業。

copyright © 萬盛學電腦網 all rights reserved