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

如何使用Python的borb库为多页文档添加页眉页脚及页码标识

使用borb为多页PDF添加页眉页脚及页码

在borb中,要给多页文档统一添加页眉页脚(包含当前页码与总页码),核心是通过PageLayout结合Footer、PageNumber组件实现,以下是完整可运行示例:

from borb.pdf import Document, Page, PDF, SingleColumnLayout, Paragraph, Footer, PageNumber, Alignment
from decimal import Decimal

# 初始化PDF文档
doc = Document()

# 循环创建5个页面
for page_idx in range(5):
    page = Page()
    doc.add_page(page)
    
    # 为页面设置单列布局
    layout = SingleColumnLayout(page)
    
    # 添加页面主体内容
    layout.add(Paragraph(f"这是第 {page_idx + 1} 页的示例内容", font_size=12))
    
    # 配置页脚
    footer = Footer()
    # 添加页码组件:自动显示当前页码/总页码,右对齐,底部边距20
    footer.add(
        PageNumber(suffix=" / "),
        horizontal_alignment=Alignment.RIGHT,
        vertical_alignment=Alignment.BOTTOM,
        margin_bottom=Decimal(20)
    )
    # 将页脚绑定到当前页面布局
    layout.set_footer(footer)
    
    # 【可选】添加页眉示例
    # from borb.pdf import Header
    # header = Header()
    # header.add(Paragraph("文档通用页眉", font_size=10, horizontal_alignment=Alignment.CENTER))
    # layout.set_header(header)

# 保存生成的PDF文件
with open("多页带页眉页脚文档.pdf", "wb") as out_file:
    PDF.dumps(out_file, doc)

核心要点:

  • 为每个页面的SingleColumnLayout单独设置Footer/Header,即可实现多页统一应用页眉页脚
  • PageNumber组件会自动识别文档总页数,通过suffix参数可拼接出「当前页码/总页码」的格式
  • 可通过horizontal_alignment、margin_*等参数调整页眉页脚的位置、边距,也可在Header/Footer中添加Image、多行Paragraph等组件实现复杂样式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 04:35:16