I think this question is pretty self explanatory. From what I've read of the python-docx documentation, it seems that the header and footer must be exactly the same on every page, which of course makes adding page numbers difficult. Is this possible?
2 Answers
Adding headers and footers is a feature not yet implemented.
However...
If it is an existing document you want to add headers and footers to you can call a VBA-macro. I recently posted a way to do that (https://stackoverflow.com/a/44767400/7386332)
If it is a new document then you can indeed go on and create a template document first and then open it up and continue editing as described by scanny.

- 18,287
- 5
- 40
- 46
-
There ought to be a way to do this entirely within `python-docx` API, as it refers to this use case in its docs but doesn't demonstrate how. https://python-docx.readthedocs.io/en/latest/dev/analysis/features/header.html?highlight=page%20number – Marc Maxmeister Mar 14 '19 at 20:47
-
Well, now there is. Haven’t looken into it though. – Anton vBR Mar 15 '19 at 05:15
-
besides python-docx documentation itself, can you find any place on SO or elsewhere that demonstrates how to insert page numbers into a header or footer, without using VBA macro or other Win32 specific libraries? – Marc Maxmeister Mar 15 '19 at 15:11
-
if not, I'll ask it as a new question, as this has not been provided. Or I'll bounty this one – Marc Maxmeister Mar 15 '19 at 15:11
-
1I need this to work on a linux server, without windows binaries present, and pure python, not VBA – Marc Maxmeister Mar 15 '19 at 15:12
-
Better open a new q – Anton vBR Mar 15 '19 at 19:24
A Word document produced by python-docx
will preserve any headers and footers present in the "template" document. So the way to get those is to create a "starting" document that has the headers and footers you're after.
A header or footer can contain a page number field, which is automatically updated with the current page number at display and/or print time. This is added using the Insert > Field > Page Number menu option in Word. Different Word versions do this slightly differently, but this should get you close enough to find it on your version. Otherwise a search on "Insert page number Word 2013" with your version will find you many resources.

- 26,423
- 5
- 54
- 80