Vibin Gangadharan
Vibin Gangadharan

Reputation: 13

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

Upvotes: 1

Views: 3224

Answers (1)

Cyrus Dobbs
Cyrus Dobbs

Reputation: 48

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)

Upvotes: 1

Related Questions