瀏覽器打印功能常需「只打印表格/報表/證書,不打印導航/廣告」。本文對比四種方案:CSS @media print 隱藏、iframe 隔離打印、新窗口打印、專用打印庫,並提供 React/Vue 組件級打印封裝。
@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 子樹」(需靠隱藏其他所有)。
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(); // 部分瀏覽器支援
}
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}
);
}
@page 設置頁邊距:@page { margin: 2cm; }。max-width: 100% 防止溢出分頁。thead { display: table-header-group; } 實現跨頁表頭重複。