Back to Blog
Python

Python-Docx: Headers, Footers, and Margins

python python docx headers footers and margins: Learn to control headers, footers, and margins in .docx files using python-docx, including different first page and sec...

python-docxWord documentsdocument generationheaders and footerspage margins
Python code editing a Word document with headers, footers, and margin settings

When generating Word documents programmatically, controlling the page layout is as important as the content itself. The query python python docx headers footers and margins points to a common need: using Python to set up headers, footers, and page margins in .docx files. The python-docx library provides a straightforward API for these tasks, 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 these 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:

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.

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.

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:

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:

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.

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. You can also unlink the first-page header from the primary header if needed, though it is often simpler to set the text directly.

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.

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 gutter and header_distance and footer_distance, which control the space between the edge and the header/footer. These are also 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.

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 a page break or content, then add 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. Also, headers and footers are stored per section; if you delete a section, its header and footer are removed. When generating documents programmatically, keep the section structure in mind—adding a section unexpectedly can change the header/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.

python python docx headers footers and margins: Practical Us | RYUSLOG DEV