python-docx is a popular library for programmatically working with Microsoft Word files in the .docx format using Python. One of the common requirements when working with Word documents is the need to add headers and footers. This article will guide you through the process of doing just that.

Installing python-docx

Before we start, ensure you have the python-docx library installed. If not, you can install it using pip:

pip install python-docx

Understanding Headers and Footers

In Word documents, there are typically three types of headers and footers:

  1. Primary: Appears on all pages except designated first pages.
  2. First Page: Appears only on the first page.
  3. Even Pages: Appears only on even-numbered pages.

python-docx gives us tools to access and modify all these types.

Adding Headers and Footers

Now, let's look at how to add headers and footers to a document.

from docx import Document

# Create a new document
doc = Document()

# Add some content to the document
for i in range(10):
    doc.add_paragraph(f"This is paragraph {i + 1}")

# Access the primary header
header = doc.sections[0].header

# Add a primary header text
header.paragraphs[0].text = "Primary Header: This is a header text"

# Access the primary footer
footer = doc.sections[0].footer

# Add a primary footer text
footer.paragraphs[0].text = "Primary Footer: This is a footer text"

# Save the document
doc.save("document_with_header_footer.docx")

Adding Different Headers for First Page and Even Pages

To designate different headers or footers for the first page or even-numbered pages, you need to modify the section's start_new_page property.

Here's how you can do that:

from docx import Document

# Create a new document
doc = Document()

# Add some content
for i in range(10):
    doc.add_paragraph(f"This is paragraph {i + 1}")

# Access the default section
section = doc.sections[0]

# Enable different first page header/footer
section.start_new_page = True

# Add content to the first page header
first_page_header = section.header.is_first_page_header
first_page_header.paragraphs[0].text = "First Page Header"

# Add content to even page header
even_page_header = section.header.is_even_page_header
even_page_header.paragraphs[0].text = "Even Page Header"

# Save the document
doc.save("document_with_different_headers.docx")

python-docx provides a straightforward approach to adding headers and footers to your Word documents. While this article introduces the basics, the library offers more advanced features like adding images to headers/footers, styling the text, and much more. As always, consulting the official documentation can provide more detailed insights into these capabilities.