Adding and Setting Headers and Footers in Word Documents Using Python
Headers and footers are commonly used elements in Word documents, displaying consistent information at the top or bottom of each page, such as document titles, company names, and page numbers. When processing large volumes of documents or adding headers and footers in batches, manual operations can be inefficient. Python can automate these tasks, improving document processing efficiency.
This article demonstrates how to add and set headers and footers in Word documents using Python and the Spire.Doc library, including common operations such as adding text, images, page numbers, and setting different headers and footers for odd and even pages.
Environment Setup
First, install the Spire.Doc library:
pip install spire.doc
After installation, the relevant functionality can be imported and used in Python code.
Basic Concepts
Before writing code, it is important to understand several basic concepts:
- Section: A Word document consists of one or more sections, each with its own header and footer settings
- Header: The area located at the top of the page
- Footer: The area located at the bottom of the page
- Paragraph: Content in headers and footers is organized and displayed through paragraphs
Adding Basic Headers and Footers
The following example demonstrates how to add headers and footers containing text and images to a Word document:
from spire.doc import *
from spire.doc.common import *
# Create a document object and load the file
document = Document()
document.LoadFromFile("Sample.docx")
# Get the first section
section = document.Sections[0]
# Get header and footer objects
header = section.HeadersFooters.Header
footer = section.HeadersFooters.Footer
# Add a paragraph to the header
headerParagraph = header.AddParagraph()
# Add an image to the header
headerPicture = headerParagraph.AppendPicture("Header.png")
# Set image size and position
headerPicture.Width = 40
headerPicture.Height = 40
headerPicture.TextWrappingStyle = TextWrappingStyle.InFrontOfText
headerPicture.HorizontalAlignment = ShapeHorizontalAlignment.Left
headerPicture.VerticalAlignment = ShapeVerticalAlignment.Outside
# Add text to the header
text = headerParagraph.AppendText("Internal Company Document")
text.CharacterFormat.FontName = "Arial"
text.CharacterFormat.FontSize = 10
text.CharacterFormat.Italic = True
# Set header paragraph right alignment
headerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Right
# Add bottom border line
headerParagraph.Format.Borders.Bottom.BorderType = BorderStyle.Single
headerParagraph.Format.Borders.Bottom.Space = 0.05
# Add a paragraph to the footer
footerParagraph = footer.AddParagraph()
# Add page number field
footerParagraph.AppendField("page number", FieldType.FieldPage)
footerParagraph.AppendText(" / ")
footerParagraph.AppendField("number of pages", FieldType.FieldNumPages)
# Set footer paragraph center alignment
footerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center
# Save the document
document.SaveToFile("HeaderAndFooter.docx", FileFormat.Docx)
document.Close()
Below is the generated document's header and footer:
This code first loads an existing Word document, then retrieves the first section of the document. The header and footer objects are accessed through the HeadersFooters property, paragraphs are added using the AddParagraph() method, and images and text content are added via the AppendPicture() and AppendText() methods.
Setting Different Headers and Footers for Odd and Even Pages
In formal documents, it is often necessary to set different headers and footers for odd and even pages. For example, odd pages may display chapter titles while even pages display the document name. The following code demonstrates how to implement this functionality:
from spire.doc import *
from spire.doc.common import *
# Load the document
doc = Document()
doc.LoadFromFile("MultiplePages.docx")
# Get the first section
section = doc.Sections[0]
# Enable different headers and footers for odd and even pages
section.PageSetup.DifferentOddAndEvenPagesHeaderFooter = True
# Add odd page header
oddHeaderPara = section.HeadersFooters.OddHeader.AddParagraph()
oddHeaderText = oddHeaderPara.AppendText("Odd Page Header - Chapter Title")
oddHeaderPara.Format.HorizontalAlignment = HorizontalAlignment.Center
oddHeaderText.CharacterFormat.FontName = "Arial"
oddHeaderText.CharacterFormat.FontSize = 10
# Add even page header
evenHeaderPara = section.HeadersFooters.EvenHeader.AddParagraph()
evenHeaderText = evenHeaderPara.AppendText("Even Page Header - Document Name")
evenHeaderPara.Format.HorizontalAlignment = HorizontalAlignment.Center
evenHeaderText.CharacterFormat.FontName = "Arial"
evenHeaderText.CharacterFormat.FontSize = 10
# Add odd page footer
oddFooterPara = section.HeadersFooters.OddFooter.AddParagraph()
oddFooterText = oddFooterPara.AppendText("Odd Page Footer")
oddFooterPara.Format.HorizontalAlignment = HorizontalAlignment.Center
# Add even page footer
evenFooterPara = section.HeadersFooters.EvenFooter.AddParagraph()
evenFooterText = evenFooterPara.AppendText("Even Page Footer")
evenFooterPara.Format.HorizontalAlignment = HorizontalAlignment.Center
# Save the document
doc.SaveToFile("OddAndEvenHeaderFooter.docx", FileFormat.Docx)
doc.Close()
The generated document's header and footer are shown below:
The key step is to set the DifferentOddAndEvenPagesHeaderFooter property to True, then access and set the headers and footers for odd and even pages separately through the OddHeader, EvenHeader, OddFooter, and EvenFooter properties.
Setting Different First Page Header and Footer
Some documents require special headers and footers for the first page, or no headers and footers on the first page. This can be achieved as follows:
from spire.doc import *
from spire.doc.common import *
# Load the document
doc = Document()
doc.LoadFromFile("Sample.docx")
# Get the first section
section = doc.Sections[0]
# Enable different first page header and footer
section.PageSetup.DifferentFirstPageHeaderFooter = True
# Set first page header (can be left empty to hide header on first page)
firstHeaderPara = section.HeadersFooters.FirstPageHeader.AddParagraph()
firstHeaderText = firstHeaderPara.AppendText("First Page Specific Header")
firstHeaderPara.Format.HorizontalAlignment = HorizontalAlignment.Center
# Set regular header (for pages other than the first page)
headerPara = section.HeadersFooters.Header.AddParagraph()
headerText = headerPara.AppendText("Regular Header")
headerPara.Format.HorizontalAlignment = HorizontalAlignment.Right
# Save the document
doc.SaveToFile("FirstPageHeader.docx", FileFormat.Docx)
doc.Close()
The generated document's header and footer are shown below:
By setting the DifferentFirstPageHeaderFooter property to True, the first page's header and footer can be set using the FirstPageHeader and FirstPageFooter properties.
Adjusting Header and Footer Height
The height of headers and footers can be adjusted through the HeaderDistance and FooterDistance properties:
from spire.doc import *
from spire.doc.common import *
# Load the document
doc = Document()
doc.LoadFromFile("Sample.docx")
# Get the first section
section = doc.Sections[0]
# Set the distance from the header to the top of the page (unit: points)
section.PageSetup.HeaderDistance = 50
# Set the distance from the footer to the bottom of the page (unit: points)
section.PageSetup.FooterDistance = 50
# Add header content
header = section.HeadersFooters.Header
headerPara = header.AddParagraph()
headerPara.AppendText("Header with Adjusted Height")
# Save the document
doc.SaveToFile("AdjustedHeight.docx", FileFormat.Docx)
doc.Close()
Below is a preview of the generated Word document:
Practical Tips
Adding Page Number Formats
Page numbers are the most common element in footers and can be added in various formats:
footerParagraph = footer.AddParagraph()
# Add "Page X" format
footerParagraph.AppendText("Page ")
footerParagraph.AppendField("page number", FieldType.FieldPage)
# Add "Page X of Y" format
footerParagraph.AppendText("Page ")
footerParagraph.AppendField("page number", FieldType.FieldPage)
footerParagraph.AppendText(" of ")
footerParagraph.AppendField("number of pages", FieldType.FieldNumPages)
Adding Separator Lines
Adding separator lines to headers or footers can enhance visual effects:
# Add separator line at the bottom of the header
headerParagraph.Format.Borders.Bottom.BorderType = BorderStyle.Single
headerParagraph.Format.Borders.Bottom.Color = Color.get_Gray()
headerParagraph.Format.Borders.Bottom.LineWidth = 0.5
# Add separator line at the top of the footer
footerParagraph.Format.Borders.Top.BorderType = BorderStyle.Single
footerParagraph.Format.Borders.Top.Color = Color.get_Gray()
footerParagraph.Format.Borders.Top.LineWidth = 0.5
Setting Image Size and Position
When adding images to headers and footers, the image position can be precisely controlled:
picture = headerParagraph.AppendPicture("Logo.png")
# Set image size
headerPicture.Width = 40
headerPicture.Height = 40
# Set text wrapping style
picture.TextWrappingStyle = TextWrappingStyle.Behind
# Set horizontal position
picture.HorizontalOrigin = HorizontalOrigin.Page
picture.HorizontalAlignment = ShapeHorizontalAlignment.Left
# Set vertical position
picture.VerticalOrigin = VerticalOrigin.Page
picture.VerticalAlignment = ShapeVerticalAlignment.Top
Summary
This article has introduced various methods for adding and setting headers and footers in Word documents using Python, including adding text and images, setting different headers and footers for odd and even pages, special handling for the first page, adjusting height, and other common operations. These techniques enable efficient batch processing of documents and automated header and footer configuration.
In practical applications, these methods can be combined according to specific requirements. For example, professional headers and footers containing company logos, document titles, and page numbers can be created for formal reports, or different header and footer styles for odd and even pages can be set up for book typesetting. Mastering these techniques can significantly improve the efficiency and standardization of document processing.





Top comments (0)