Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python-Docx: Headers, Footers, and Margins

Learn to control headers, footers, and margins in .docx files with python-docx, including section-specific layouts and different first-page settings.

~4 min readPython
#python-docx#Word documents#document generation#headers and footers
Python code editing a Word document with headers, footers, and margin settings

When generating Word documents programmatically, controlling page layout is as important as the content itself. The python-docx library provides a straightforward API for setting headers, footers, and page margins in .docx files, but the details matter—especially when a document has multiple sections or needs a different first page. This article explains how to access and modify those properties reliably.

Why Headers, Footers, and Margins Matter in Generated Documents

Headers and footers carry repeated information like document titles, page numbers, and confidentiality notices. Margins define the printable area and affect readability and print layout. When you generate reports, invoices, or contracts, these elements must be correct from the start. Manually editing every generated file defeats the purpose of automation. python-docx lets you set them in code, so the output is consistent and production-ready.

Setting Up python-docx for Document Manipulation

python-docx is the de facto library for reading and writing .docx files in Python. Install it with pip:

bash
pip install python-docx

Then import the Document class. To work with an existing file, load it; to create a new one, instantiate Document() without arguments. Every document has at least one section, and sections control headers, footers, and margins.

python
from docx import Document doc = Document() # new document # or doc = Document('existing.docx') to modify

A section is accessible via doc.sections. The first section is doc.sections[0]. For a new document, that is the only section unless you add more.

Accessing and Editing Section Headers

Each section has a header attribute that returns a _Header object. The header contains paragraphs, just like the body. To add text, use the first paragraph or add a new one.

python
section = doc.sections[0] header = section.header header_paragraph = header.paragraphs[0] header_paragraph.text = "Quarterly Report"

You can also style the header paragraph, for example by setting alignment or font size. The header is linked to the previous section by default. If you have multiple sections and want a different header in the second section, you must unlink it first:

python
section2 = doc.add_section() section2.header.is_linked_to_previous = False section2.header.paragraphs[0].text = "Appendix"

Without unlinking, the second section inherits the header from the first. This is a common source of confusion when generating documents with distinct parts.

Working with Footers and Different First Page Settings

Footers work the same way as headers. Access section.footer and modify its paragraphs. For page numbers, you typically insert a field, but python-docx does not expose a high-level page number API. You can add a simple text footer:

python
footer = section.footer footer.paragraphs[0].text = "Confidential"

Many documents require a different header or footer on the first page. python-docx supports this with the different_first_page_header_footer property on the section. When set to True, the section has separate first-page header and footer objects.

python
section.different_first_page_header_footer = True first_page_header = section.first_page_header first_page_header.paragraphs[0].text = "Draft"

If you do not set the first-page header text, it remains empty. Use section.first_page_header and section.first_page_footer when a document needs a distinct opening page.

Adjusting Page Margins for Each Section

Margins are properties of the section. The left_margin, right_margin, top_margin, and bottom_margin attributes accept a Length object, typically in inches or centimeters. Use docx.shared.Inches or docx.shared.Cm.

python
from docx.shared import Inches section = doc.sections[0] section.left_margin = Inches(1) section.right_margin = Inches(1) section.top_margin = Inches(0.5) section.bottom_margin = Inches(0.5)

You can also set header_distance and footer_distance, which control the distance from the page edge to the header or footer. gutter adds extra space for binding. These also use Length objects.

If you add multiple sections, each section can have its own margins. This is useful when you want a wide margin for a cover page and narrower margins for the body.

Combining Headers, Footers, and Margins in a Realistic Example

Here is a complete example that creates a document with two sections. The first section has a header with the report title, a footer with a confidentiality notice, and 1-inch margins. The second section is unlinked, has a different header, and uses narrower margins.

python
from docx import Document from docx.shared import Inches doc = Document() # First section section1 = doc.sections[0] section1.left_margin = Inches(1) section1.right_margin = Inches(1) section1.top_margin = Inches(1) section1.bottom_margin = Inches(1) header1 = section1.header header1.paragraphs[0].text = "Annual Report" footer1 = section1.footer footer1.paragraphs[0].text = "Confidential" # Add content, then add the second section # ... (content goes here) section2 = doc.add_section() # Unlink header and footer from previous section2.header.is_linked_to_previous = False section2.footer.is_linked_to_previous = False section2.left_margin = Inches(0.75) section2.right_margin = Inches(0.75) section2.top_margin = Inches(0.5) section2.bottom_margin = Inches(0.5) section2.header.paragraphs[0].text = "Appendix" section2.footer.paragraphs[0].text = "Page" doc.save("report.docx")

This pattern covers the common need: different sections with independent layout settings. Note that when you add a new section, it inherits the previous section's headers, footers, and margins until you explicitly change them.

Compatibility and Maintainability Considerations

python-docx only works with .docx files, not the older .doc format. If your pipeline produces .doc, you need to convert first or use a different library. When generating documents programmatically, keep the section structure in mind—adding a section unexpectedly can change the header and footer of subsequent content.

For maintainability, consider building a helper function that configures a section with standard margins and header/footer text. This avoids repeating the same property assignments across many places in your code. If your document needs a complex layout, such as mirrored margins for book printing, python-docx supports section.mirror_margins and section.gutter, but these are rarely used in business documents.

Performance is rarely a bottleneck with python-docx because it operates on XML in memory and writes the file once. However, if you generate thousands of documents in a loop, reusing a template file with preconfigured sections can reduce overhead. Load the template, modify only the content, and save under a new name. This also ensures consistent layout without re-setting margins and headers every time.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.