Search code examples
pythonpython-docx

How to delete all Headers and Footers in a word document using Python code


I want to delete all headers and footers in a word document which contains multiple pages and sections using a Python function. I tried using docx-python:

from docx import Document
document = Document('new.docx')

for section in document.sections:
    header = section.header
    header.is_linked_to_previous = True
  
document.save('mydoc.docx')

header.is_linked_to_previous = True is removing all headers and footers in a document, but if "Different First Page" option is enabled in Word in a Header or Footer, then this is not working. I want to remove all occurrences.

enter image description here


Solution

  • You can simply just set different first page to False via python-docx.

    from docx import Document
    
    document = Document(doc)
    
    for section in document.sections:
        section.different_first_page_header_footer = False
        section.header.is_linked_to_previous = True
      
    document.save(edited_doc)