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

如何让Python-docx文档仅在首页显示页眉而非所有页面?

解决仅在首页显示页眉的问题

要实现仅首页显示页眉,你需要利用python-docx中不同首页页眉/页脚的特性,修改点如下:

  • 开启「首页独立页眉/页脚」的设置
  • 将页眉内容添加到「首页专属页眉」对象中,而非默认的全局页眉

修改后的完整代码:

section = doc.sections[0]
# 新增:开启首页独立页眉/页脚
section.different_first_page_header_footer = True

# 修改:使用first_page_header而非header,仅针对首页设置页眉
sec_header = section.first_page_header
header_tp = sec_header.add_paragraph()
header_run = header_tp.add_run()
header_run.add_picture(logo_path, width=Inches(1.24), height=Inches(0.30))
rml_header = "                       Project completion report"
header_run.add_text(rml_header)
header_run.bold = True        
header_run.add_text("\n_____________________________________________________________")
header_run.font.size = Pt(14)

关键说明:

  • different_first_page_header_footer = True:告诉文档首页的页眉/页脚与其他页面分离
  • section.first_page_header:专门对应首页的页眉对象,对它的修改只会影响首页
  • 原代码中的section.header对应非首页的页眉,现在不对它添加任何内容,所以其他页面不会显示页眉

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 08:17:41