0

Recently, version 0.8.8 of python-docx added direct support for headers and footers.

Now one can simply add a header or footer as follows:

from docx import Document
document = Document()

header = document.sections[0].header
header.add_paragraph('This is an example Header') 

footer = document.sections[0].footer
footer.add_paragraph('This is an example Footer')

Prior to this release, one could add headers and footers flexibly using a template approach.

With templates it is very straightforward to include things such as page numbers. However, this does not seem to be the case with the implementation of headers and footers in the new versions.

Is there an easy way to add page numbers in versions 0.8.8 and later?

1 Answers1

0

I believe you'll find that an "auto" page-number of the sort used in a header or footer is a type of field. Fields have not yet been implemented in python-docx, so you'd be on your own for that, having to add the required XML from a point as close as you can get, which I expect would be the <w:r> element for a run.

The way I would approach it would be to add a page-number in a header using Word, and then inspect the resulting XML using opc-diag. That would establish specifically what XML needs to go where.

From there you can get a run element using r = run._r and then use lxml calls to insert the XML you need.

scanny
  • 26,423
  • 5
  • 54
  • 80
  • Any plans to implement this in the (near) future? –  Apr 12 '19 at 17:09
  • New features are primarily added to `python-docx` via sponsorship. That's how headers and footers got there recently. So the question becomes "does anyone want this feature enough to pay for adding it?". This happens more than you might think, usually a project that has `python-docx` as a dependency and just needs another feature or two. No one has signed up for this particular one just yet. The typical approach for no-budget users is to extend the package by writing XML directly in focused areas, as I outlined above. It takes some analysis work, but can usually be done in a dozen lines or so. – scanny Apr 13 '19 at 21:04
  • Interesting. But what is the process for sponsoring features? There does not appear to be any information about this on the python-docx website. –  Apr 20 '19 at 13:08
  • @PearlySpencer if you think you might want to sponsor a feature, just reach out on the email on the GitHub repo author profile: https://github.com/scanny – scanny Apr 22 '19 at 20:21