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

如何在laravel dompdf中添加两种不同的动态页脚?

解决方案

要实现不同页面组的差异化页脚和页码重置,只需修改Blade视图中的PHP脚本部分,通过判断当前页码来切换页脚文本并重新计算页码。

步骤1:修改Blade视图的页脚脚本

替换原有的<script type="text/php">代码为以下内容:

<!-- 移除原静态footer,改用脚本动态生成 -->
<script type="text/php">
    if (isset($pdf)) {
        // 获取与控制器设置一致的字体
        $font = $pdf->getFont('sans-serif');
        $currentPage = $pdf->getPage();
        
        // 定义页脚文本(若需动态传递,可参考步骤2从控制器获取)
        $footerText1 = 'footer_text_1';
        $footerText2 = 'footer_text_2';
        
        // 确定当前页的页脚文本和显示页码
        if ($currentPage <= 3) {
            $displayPage = $currentPage;
            $activeFooterText = $footerText1;
        } else {
            // 第4页及以后页码从1重新计数
            $displayPage = $currentPage - 3;
            $activeFooterText = $footerText2;
        }
        
        // 输出页脚文本(坐标可根据页面布局调整)
        $pdf->page_text(50, 810, $activeFooterText, $font, 10, array(0, 0, 0));
        // 输出页码(坐标可按需调整)
        $pdf->page_text(295, 810, "页码 {$displayPage}", $font, 10, array(0, 0, 0));
    }
</script>

步骤2:控制器动态传递页脚文本(可选)

如果需要从控制器动态传入页脚文本,修改视图参数:

$pdf = PDF::loadView($viewPath, [
    'pdf' => true,
    'key1' => 'value1',
    'key2' => 'value2',
    // 添加页脚文本变量
    'footerText1' => '自定义第1-3页页脚文本',
    'footerText2' => '自定义第4页及以后页脚文本'
])->setOptions(['defaultFont' => 'sans-serif', 'enable_php' => true])
->setPaper('a4', 'landscape')
->save($path . '/' . $fileName . '.pdf');

return $pdf->download($fileName . '.pdf');

此时需将Blade脚本中的页脚文本定义改为:

$footerText1 = '{{ $footerText1 }}';
$footerText2 = '{{ $footerText2 }}';

关键说明

  • $pdf->getPage():获取当前页面的原始页码
  • 页码重置逻辑:第4页及以后通过$currentPage - 3实现从1开始计数
  • page_text()方法的前两个参数为文本的X、Y坐标,需根据A4横向页面布局调整(默认A4横向宽度约841px,高度约595px)
  • 必须确保控制器中已开启enable_php选项,否则PHP脚本无法执行

内容的提问来源于stack exchange,提问作者Sumer Singh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 16:05:24