Search code examples
pythonpython-3.xheaderfooterpython-docx

Header and footer creation in versions before 0.8.8


Is there a workaround for adding headers and footers in a Microsoft Word (docx) file?

These are not implemented in versions of python-docx prior to 0.8.8.

More specifically, I would like to add:

  1. Page number to footers
  2. Some random text to headers

The ideal code will look as follows:

from docx import Document

document = Document()

# Add header and footer on all pages

document.save("demo.docx")

Solution

  • How about something like this (Thanks to Eliot K)

    from docx import Document
    import win32com.client as win32
    import os.path
    import tempfile
    
    tempdir = tempfile.gettempdir()
    msword = win32.gencache.EnsureDispatch('Word.Application')
    tempfile = os.path.join(tempdir, "temp.doc")
    
    document = Document()
    
    document.save(tempfile)
    
    doc = msword.Documents.Open(tempfile)
    
    doc.Sections(1).Footers(1).Range.Text = r'Text to be included'
    doc.Sections(1).Footers(1).PageNumbers.Add()
    doc.SaveAs(tempfile, FileFormat = 0)
    
    document = Document(tempfile)
    

    Not the most elegant approach perhaps, but should do what you need it to. Maybe sequester the ugly save/load code in a function somewhere in a dusty corner of your code ;-)

    Again, does require a windows machine with microsoft office installed.

    Good luck!