Page number python-docx

Short answer is no, because the page breaks are inserted by the rendering engine, not determined by the .docx file itself.

However, certain clients place a <w:lastRenderedPageBreak> element in the saved XML to indicate where they broke the page last time it was rendered.

I don’t know which do this (although I expect Word itself does) and how reliable it is, but that’s the direction I would recommend if you wanted to work in Python. You could potentially use python-docx to get a reference to the lxml element you want (like w:document/w:body) and then use XPath commands or something to iterate through to a specific page, but just thinking it through a bit it’s going to be some detailed development there to get that working.

If you work in the native Windows MS Office API you might be able to get something better since it actually runs the Word application.

If you’re generating the documents in python-docx, those elements won’t be placed because it makes no attempt to render the document (nor is it ever likely to). We’re also not likely to add support for w:lastRenderedPageBreak anytime soon; I’m not even quite sure what that would look like.

If you search on ‘lastRenderedPageBreak’ and/or ‘python-docx page break’ you’ll see other questions/answers here that may give a little more.

Leave a Comment