Search code examples
pythonms-wordheaderpython-docx

Create a document with python-docx where the header only appears on the first page


I am using python-docx to create a word document from scratch and I have managed to add an image header to the document. However the header image is repeated over all the pages and I do not fully understand how sections and header.is_linked_to_previous works to be able to figure out how to only have the header on the first page.

document = Document()
header = document.sections[0].header
htable = header.add_table(1, 1, Inches(6))
htab_cells = htable.rows[0].cells
ht0 = htab_cells[0].add_paragraph()
kh = ht0.add_run()
kh.add_picture('BothHeaderLogos.png', width=Inches(5.6))
current_section = document.sections[-1]
new_section = document.add_section(WD_SECTION.ODD_PAGE)
document.add_heading("Sequence Summary", level=1)
header.is_linked_to_previous = False

Solution

  • I think what you're looking for is document.sections[0].first_page_header. A header defined there appears only on the first page of the section.

    The .is_linked_to_previous property would only be required if you already have more than one section. Creating a second section just to add that would be unnecessary.

    Headers and footers are documented here:
    https://python-docx.readthedocs.io/en/latest/user/hdrftr.html

    And the API details for these calls are here:
    https://python-docx.readthedocs.io/en/latest/api/section.html