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

如何在Flutter生成的PDF文件页脚中添加页码

为Flutter PDF生成功能添加页脚页码

实现方案

你当前使用的pdf库中,MultiPage组件的footer回调提供的pw.Context对象包含了当前页码和总页数的信息,直接利用这两个属性即可实现页码功能。

修改步骤

  1. 更新MultiPage的footer调用,将上下文对象传递给buildFooter方法
  2. 修改buildFooter方法,加入页码布局

修改后的代码片段

1. 调整generate方法中的MultiPage配置

pdf.addPage(MultiPage(
  maxPages: 20,
  pageFormat: PdfPageFormat.a4,
  build: (context) => [
    pw.SizedBox(height: 25),
    buildTablaDiario(listaDiarioActual),
  ],
  header: (context) => buildHeader(image,fecha,patrulla,responsable,vigilante1,vigilante2,turno,hora),
  // 传递上下文对象到footer方法
  footer: (context) => buildFooter(context, firma_resp),
));

2. 更新buildFooter方法,添加页码

static Widget buildFooter(pw.Context context, firmafooter) => pw.Column(
  crossAxisAlignment: pw.CrossAxisAlignment.center,
  children: [
    // 页码区域,居中显示
    pw.Row(
      mainAxisAlignment: pw.MainAxisAlignment.center,
      children: [
        pw.Text(
          'Página ${context.pageNumber} de ${context.totalPages}',
          style: pw.TextStyle(fontSize: 10),
        ),
      ],
    ),
    pw.SizedBox(height: 10),
    // 原有页脚内容
    pw.Row(
      crossAxisAlignment: pw.CrossAxisAlignment.center,
      children: [
        pw.Column(
          children: [
            pw.Text("FIRMA",
                style:
                pw.TextStyle(fontSize: 11,fontWeight: FontWeight.bold)),
            pw.Container(
                height: 100,
                width: 300,
                decoration: pw.BoxDecoration(
                  border: pw.Border.all(width: 1, color: PdfColors.black),
                ),
                child: pw.Image(firmafooter,height: 95,width: 95,fit: pw.BoxFit.fill)
            )
          ],
        ),
        pw.SizedBox(width: 50),
        pw.Container(
          height: 100,
          child: pw.Text("REVISADO CLIENTE",style: pw.TextStyle(fontSize: 10))
        )
      ],
    ),
  ],
);

核心说明

  • context.pageNumber:当前页的页码(从1开始计数)
  • context.totalPages:PDF的总页数,由MultiPage自动计算生成
  • 可根据需求调整页码的对齐方式、字体大小、颜色等样式,匹配文档整体风格

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 08:08:10