Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

CSS @media print 實現網頁動態頁首頁尾換頁:Table + JavaScript 精準控制列印版面

編輯:Windows XP 系統介紹

網頁列印時需在每頁固定位置顯示頁首(Logo、標題)、頁尾(頁碼、機密等級)並強制換頁,瀏覽器預設列印無法精準控制。利用 CSS @media print 偽類配合 Table 佈局與 JavaScript 動態插入,可在 IE5+、現代瀏覽器實現精準分頁。

核心架構

<div id="header" style="display:none">頁首內容</div>
<div id="footer" style="display:none">頁尾內容</div>
<table id="tbl" width="6.5in" border="0">
  <tr><td>資料列 1</td></tr>
  <tr><td>資料列 2</td></tr>
  ...
</table>

CSS 列印專用樣式

@media print {
  #header, #footer { display: block; page-break-after: always; }
  #header { position: fixed; top: 0.25in; width: 6.5in; }
  #footer { position: fixed; bottom: 0.25in; width: 6.5in; }
  tr { page-break-inside: avoid; }
}

JavaScript 動態分頁邏輯(onload 執行)

  1. 計算可用列印高度:11in - (頁首高+頁尾高) - (上下邊界×2) = 8.5in。
  2. 遍歷 Table 所有 <tr>,累加 offsetTop + offsetHeight。
  3. 超過可用高度 → 在前一列 <tr> 加 style="page-break-after:always",並插入頁尾/頁首佔位列。
  4. 最後一列後加入最終頁尾。

關鍵參數假設(A4/Letter 通用)

  • 紙張:Letter 8.5×11 in / A4 210×297 mm。
  • 邊界:上下 0.25 in、左右 1 in → 可用寬 6.5 in。
  • 頁首/頁尾高:各 1 in → 可用高 8.5 in。
  • 解析度:screen.deviceYDPI(通常 96 DPI)換算像素。

現代替代方案:Puppeteer/Playwright headless Chrome 產生 PDF、@page CSS 標準(現代瀏覽器支援度提升中)、WeasyPrint/PrinceXML 伺服器端渲染,精準度與維護性優於客戶端 JS 方案。

Copyright © Windows教程網 All Rights Reserved