You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:实现带可变页码与合同号的CSS打印页脚

打印页脚实现方案(含合同号与X of Y页码)

核心思路

用CSS打印媒体查询结合计数器,搭配表格布局的页脚组实现每页底部动态页码,同时通过PHP注入固定合同号。

完整代码实现

1. CSS 配置

/* 初始化页码计数器 */
@page {
    counter-increment: page;
    counter-reset: page 0; /* 从0开始,递增后显示1 */
    margin-bottom: 2cm; /* 给页脚预留空间 */
}

/* 初始化总页数计数器 */
body {
    counter-reset: pages;
}

/* 每页内容容器,触发总页数计数 */
.page-content {
    page-break-after: always;
    break-after: page;
    counter-increment: pages;
}

/* 避免最后一页生成空页 */
.page-content:last-child {
    page-break-after: avoid;
    break-after: avoid;
}

/* 打印页脚样式 */
@media print {
    .print-footer {
        display: table-footer-group;
        width: 100%;
        text-align: center;
        padding: 10px 0;
        border-top: 1px solid #ccc;
    }
    .screen-only {
        display: none;
    }
}

/* 屏幕上隐藏打印页脚 */
@media screen {
    .print-footer {
        display: none;
    }
}

2. HTML/PHP 结构

<!-- 全局表格容器,承载页脚组 -->
<table style="width: 100%; border-collapse: collapse;">
    <tfoot>
        <tr>
            <td class="print-footer">
                Contract # <?php echo $line["contract_num"]; ?> Page <span class="page-number"></span> of <span class="total-pages"></span>
            </td>
        </tr>
    </tfoot>
    <tbody>
        <!-- 第一页内容 -->
        <tr>
            <td class="page-content">
                <!-- 第一页HTML内容 -->
            </td>
        </tr>
        <!-- 第二页内容 -->
        <tr>
            <td class="page-content">
                <!-- 第二页HTML内容 -->
            </td>
        </tr>
        <!-- 更多页面依此类推 -->
    </tbody>
</table>

<!-- JS补充总页数(CSS无法直接获取总页数) -->
<script>
window.addEventListener('beforeprint', function() {
    const totalPages = document.querySelectorAll('.page-content').length;
    document.querySelectorAll('.total-pages').forEach(el => el.textContent = totalPages);
    // 同步CSS生成的页码
    document.querySelectorAll('.page-number').forEach(el => {
        el.textContent = window.getComputedStyle(el, ':after').content.replace(/"/g, '');
    });
});
</script>

方案说明

  • CSS计数器:@page自动递增每页页码,.page-content统计总页数,解决服务器端PHP无法感知浏览器分页的问题。
  • 表格布局:table-footer-group是CSS打印布局标准方式,确保页脚固定在每页底部,不会叠加重复。
  • JS辅助:通过beforeprint事件计算总页数并填充,弥补CSS无法获取总页数的缺陷。
  • 合同号注入:直接通过PHP输出$line["contract_num"],确保所有页脚显示相同合同号。

解决之前尝试的问题

  • 固定定位页脚重复:用table-footer-group替代position: fixed,避免页脚叠加。
  • PHP变量递增失效:改用客户端CSS计数器实现页码递增,规避服务器端渲染的局限。
  • CSS计数器未生效:补充@page计数器初始化与总页数统计逻辑,完善配置。

内容的提问来源于stack exchange,提问作者Heidi Denney

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 13:25:18