Search code examples
pythonms-wordpython-docx

Add page number using python-docx


I am trying to add a page number in the footer of a word doc using python-docx. So far, I haven't been able to find how to do so. This question address how to find a page number (or how you cannot). This one talks about creating a template and adding page numbers there. Is there a way to add page numbers on a document I created using doc = Document()?


Solution

  • An automatic page-number in a footer is implemented as a field. Fields do not yet have API support in python-docx, so you cannot do what you want with a document created from the default template (document = Document()), at least not by making an API call.

    The two possible approaches are to create a template document that already has a page-number in the footer and start from there:

    document = Document("my-template.docx")
    

    Or to create a workaround function that adds in the XML using low-level lxml calls on an XML element object obtained from a python-docx object, like paragraph._p.

    The links provided by Syafiqur__ in his answer can help you with this latter approach.