萬盛學電腦網

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

window.print 打印指定區域:iframe 隔離法、CSS @media print、Print CSS 最佳實踐、React/Vue 組件打印方案

瀏覽器打印功能常需「只打印表格/報表/證書,不打印導航/廣告」。本文對比四種方案:CSS @media print 隱藏、iframe 隔離打印、新窗口打印、專用打印庫,並提供 React/Vue 組件級打印封裝。

方案一:CSS @media print(最簡單、無 JS 依賴)

@media print {
  .no-print { display: none !important; }
  .only-print { display: block !important; }
  body { margin: 0; background: white; }
  .container { width: 100%; max-width: none; padding: 0; }
  a[href]::after { content: none; } /* 隱藏鏈接地址 */
  .page-break { page-break-before: always; }
}

HTML 標記:<nav class="no-print">...</nav>、<div class="only-print">打印內容</div>。

優點:零 JS、響應式、支援分頁控制。缺點:無法精確控制「僅打印某 DOM 子樹」(需靠隱藏其他所有)。

方案二:iframe 隔離打印(精確控制內容、樣式隔離)

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

  const doc = iframe.contentDocument || iframe.contentWindow.document;
  // 複製樣式表
  [...document.styleSheets].forEach(sheet => {
    try {
      if (sheet.cssRules) {
        const style = doc.createElement('style');
        style.textContent = [...sheet.cssRules].map(r => r.cssText).join('\n');
        doc.head.appendChild(style);
      }
    } catch (e) { /* 跨域樣式表無法讀取 */ }
  });
  // 複製內容
  doc.body.appendChild(el.cloneNode(true));
  doc.close();

  iframe.onload = () => {
    iframe.contentWindow.focus();
    iframe.contentWindow.print();
    // 打印對話框關閉後清理
    setTimeout(() => document.body.removeChild(iframe), 1000);
  };
}

方案三:新窗口打印(舊瀏覽器兼容)

function printInNewWindow(html, title = '打印') {
  const win = window.open('', '_blank', 'width=800,height=600');
  win.document.write(`${title}
    ${html}`);
  win.document.close();
  win.focus();
  win.print();
  win.onafterprint = () => win.close(); // 部分瀏覽器支援
}

方案四:專用庫

  • print-js:支援 PDF、圖片、HTML、JSON 打印,API 簡單。
  • react-to-print / vue-print-nb:組件級打印,保留樣式、支援 TypeScript。

React 組件封裝

import { useRef } from 'react';
import { useReactToPrint } from 'react-to-print';

function PrintableReport({ children }) {
  const ref = useRef(null);
  const handlePrint = useReactToPrint({
    contentRef: ref,
    documentTitle: '報表打印',
    onAfterPrint: () => console.log('打印完成'),
    removeAfterPrint: true
  });
  return (
    
{children}
); }

Print CSS 最佳實踐清單

  • 使用 @page 設置頁邊距:@page { margin: 2cm; }。
  • 避免絕對定位、固定高度、Flex/Grid 複雜佈局(打印渲染引擎支援有限)。
  • 字體使用系統字體棧,避免 Web Font 載入失敗導致空白。
  • 圖片設置 max-width: 100% 防止溢出分頁。
  • 表格添加 thead { display: table-header-group; } 實現跨頁表頭重複。
copyright © 萬盛學電腦網 all rights reserved