在批量处理 Word 文档时,页眉页脚的添加往往比正文排版更繁琐。手动操作不仅重复劳动多,还容易在"首页不同"或"奇偶页不同"等场景下出错。使用 Python 调用文档处理库,可以将这部分工作自动化。下面结合常见示例,从基础操作到差异化设置,逐步说明如何用代码控制 Word 的页眉与页脚。
环境准备
本文示例使用 Spire.Doc for Python,可以通过 pip 安装:
bash
pip install Spire.Doc
安装完成后,在脚本中导入必要的模块。
在页眉页脚中添加文本、图片与页码
页眉通常用于放置文档标题、公司名称或 Logo,页脚则多用于显示页码。该库通过 Section.HeadersFooters.Header 和 Section.HeadersFooters.Footer 分别获取页眉和页脚对象,再向其中添加段落与内容。
下面的代码将操作封装成函数,便于对多个节复用。它同时演示了图片、文本、边框和页码域的组合使用:
python
from spire.doc import *
from spire.doc.common import *
def InsertHeaderAndFooter(section):
header = section.HeadersFooters.Header
footer = section.HeadersFooters.Footer
# 页眉:图片 + 文本
headerParagraph = header.AddParagraph()
headerPicture = headerParagraph.AppendPicture("Header.png")
text = headerParagraph.AppendText("添加页眉")
text.CharacterFormat.FontName = "宋体"
text.CharacterFormat.FontSize = 10
text.CharacterFormat.Italic = True
headerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Right
headerParagraph.Format.Borders.Bottom.BorderType = BorderStyle.Single
headerParagraph.Format.Borders.Bottom.Space = 0.05
# 图片采用衬于文字下方,并以页面为参照定位到左上角
headerPicture.TextWrappingStyle = TextWrappingStyle.Behind
headerPicture.HorizontalOrigin = HorizontalOrigin.Page
headerPicture.HorizontalAlignment = ShapeHorizontalAlignment.Left
headerPicture.VerticalOrigin = VerticalOrigin.Page
headerPicture.VerticalAlignment = ShapeVerticalAlignment.Top
# 页脚:图片 + 页码域
footerParagraph = footer.AddParagraph()
footerPicture = footerParagraph.AppendPicture("Footer.png")
footerPicture.TextWrappingStyle = TextWrappingStyle.Behind
footerPicture.HorizontalOrigin = HorizontalOrigin.Page
footerPicture.HorizontalAlignment = ShapeHorizontalAlignment.Left
footerPicture.VerticalOrigin = VerticalOrigin.Page
footerPicture.VerticalAlignment = ShapeVerticalAlignment.Bottom
footerParagraph.AppendText("第 ")
footerParagraph.AppendField("页码", FieldType.FieldPage)
footerParagraph.AppendText("页 共 ")
footerParagraph.AppendField("页数", FieldType.FieldNumPages)
footerParagraph.AppendText("页")
footerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center
footerParagraph.Format.Borders.Top.BorderType = BorderStyle.Single
footerParagraph.Format.Borders.Top.Space = 0.05
document = Document()
document.LoadFromFile("示例文档.docx")
section = document.Sections.get_Item(0)
InsertHeaderAndFooter(section)
document.SaveToFile("添加页眉页脚.docx", FileFormat.Docx)
document.Close()
这里有两点需要注意。第一,页码必须使用域字段 (FieldType.FieldPage 与 FieldType.FieldNumPages),而不能手动填写固定数字,否则文档页数一旦变化,页码就会全部错位。第二,页眉页脚中的图片通过 HorizontalOrigin.Page 和 VerticalOrigin.Page 以页面为参照定位,配合 TextWrappingStyle.Behind 衬于文字下方,可以避免挤压正文区域。
在页眉中插入表格
有些场景需要在页眉放置结构化的信息,例如出版号、日期、文档编号等。该库支持直接在页眉中添加表格:
python
def InsertTableToHeader(section):
header = section.HeadersFooters.Header
tableHeader = header.AddTable(True)
tableHeader.ResetCells(2, 2)
data = [["出版号", "日期"], ["SC12546", "2019年7月24日"]]
for i in range(len(data)):
dataRow = tableHeader.Rows.get_Item(i)
dataRow.Height = 20
dataRow.HeightType = TableRowHeightType.Exactly
dataRow.RowFormat.BackColor = Color.Empty()
for c in range(len(data[i])):
dataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle
dataRow.Cells[c].CellFormat.HorizontalAlignment = HorizontalAlignment.Center
range = dataRow.Cells[c].AddParagraph().AppendText(data[i][c])
range.CharacterFormat.FontName = "宋体"
表格创建后,行高、单元格对齐方式、背景色都可以逐项设置。需要留意的是,页眉表格会占用页眉区域高度,如果行数较多,应同步调整 section.PageSetup.HeaderDistance,避免正文被向下推挤。
处理首页与奇偶页的差异化需求
很多正式报告要求封面不显示页眉页脚,或者双面打印时奇偶页的页码位置相反。可以通过 PageSetup 上的两个布尔属性来开启这类模式。
首页不同
将 DifferentFirstPageHeaderFooter 设为 True 后,第一节的第一页会使用独立的 FirstPageHeader 和 FirstPageFooter 容器,其余页面仍然使用常规的 Header 与 Footer:
python
section.PageSetup.DifferentFirstPageHeaderFooter = True
# 首页页眉页脚
p1 = section.HeadersFooters.FirstPageHeader.AddParagraph()
p1.Format.HorizontalAlignment = HorizontalAlignment.Left
r1 = p1.AppendText("首页页眉")
r1.CharacterFormat.FontName = "宋体"
r1.CharacterFormat.FontSize = 12
p2 = section.HeadersFooters.FirstPageFooter.AddParagraph()
p2.Format.HorizontalAlignment = HorizontalAlignment.Left
r2 = p2.AppendText("首页页脚")
r2.CharacterFormat.FontName = "宋体"
r2.CharacterFormat.FontSize = 12
# 非首页页眉页脚
p3 = section.HeadersFooters.Header.AddParagraph()
p3.Format.HorizontalAlignment = HorizontalAlignment.Right
r3 = p3.AppendText("非首页页眉")
r3.CharacterFormat.FontName = "微软雅黑"
r3.CharacterFormat.FontSize = 14
p4 = section.HeadersFooters.Footer.AddParagraph()
p4.Format.HorizontalAlignment = HorizontalAlignment.Right
r4 = p4.AppendText("非首页页脚")
r4.CharacterFormat.FontName = "微软雅黑"
r4.CharacterFormat.FontSize = 14
这里有一个细节:开启"首页不同"后,FirstPageHeader 与 FirstPageFooter 是独立对象。只要不向其中添加任何内容,封面就不会显示页眉页脚,无需额外执行"清除"操作。
奇偶页不同
双面打印装订时,页码通常要求靠外侧对齐。开启 DifferentOddAndEvenPagesHeaderFooter 后,原先设置在 Header / Footer 上的内容只对奇数页生效,偶数页需要单独操作 EvenHeader 与 EvenFooter:
python
section.PageSetup.DifferentOddAndEvenPagesHeaderFooter = True
# 奇数页页眉页脚
P3 = section.HeadersFooters.OddHeader.AddParagraph()
OH = P3.AppendText("奇数页页眉")
P3.Format.HorizontalAlignment = HorizontalAlignment.Center
OH.CharacterFormat.FontName = "微软雅黑"
OH.CharacterFormat.FontSize = 10
P2 = section.HeadersFooters.OddFooter.AddParagraph()
OF = P2.AppendText("奇数页页脚")
P2.Format.HorizontalAlignment = HorizontalAlignment.Center
OF.CharacterFormat.FontName = "微软雅黑"
OF.CharacterFormat.FontSize = 10
# 偶数页页眉页脚
P4 = section.HeadersFooters.EvenHeader.AddParagraph()
EH = P4.AppendText("偶数页页眉")
P4.Format.HorizontalAlignment = HorizontalAlignment.Center
EH.CharacterFormat.FontName = "微软雅黑"
EH.CharacterFormat.FontSize = 10
P1 = section.HeadersFooters.EvenFooter.AddParagraph()
EF = P1.AppendText("偶数页页脚")
EF.CharacterFormat.FontName = "微软雅黑"
EF.CharacterFormat.FontSize = 10
P1.Format.HorizontalAlignment = HorizontalAlignment.Center
两个开关可以叠加使用。如果同时开启了首页不同与奇偶页不同,需要确保 FirstPageHeader、OddHeader、EvenHeader 三个容器都有明确的处理逻辑,避免某类页面出现空白页眉或残留内容。另外,HeadersFooters 是按节 独立管理的,多节文档需要遍历 document.Sections 逐节设置,不能只处理第一节。
调整页眉页脚与正文的距离
页眉页脚区域的高度由 HeaderDistance 和 FooterDistance 控制,单位为磅(pt)。默认值通常为 36 pt,适合单行小字。如果页眉中放入了较高的 Logo 或表格,或者页脚内容较多,正文可能会被向下推挤。此时可以适当调小这两个值,让页眉页脚更贴近页面边缘:
python
section.PageSetup.HeaderDistance = 30
section.PageSetup.FooterDistance = 30
调整时需要注意:HeaderDistance 过小可能导致页眉内容被裁切,建议结合页边距(Margins)一起考虑。正文的上边距至少应大于页眉距离加上页眉实际高度。
小结
本文围绕 Word 页眉页脚的自动化处理,介绍了几个常见场景:在页眉页脚中添加文本、图片和页码,在页眉中插入表格,以及通过 PageSetup 开关处理首页不同和奇偶页不同。实现上的两个关键点是:页码使用域字段而非固定数字,页眉页脚按节独立管理、多节文档需逐节设置。实际使用时,根据文档是否有封面、是否双面打印来选择对应的容器和开关即可。
如果文档结构复杂、节与节之间页眉页脚存在继承关系,建议先在 Word 中理清各节的设置状态再编写脚本,避免代码与文档实际状态不一致。不同文档处理库在页眉页脚对象模型上的设计也有差异,迁移代码时需要留意容器名称和定位方式的对应关系。