10

I am trying to add a page break to the middle of a document using the docx-python library.

It would appear that when adding a pagebreak, the page break is added to the end of the document. Is there a method to add a page break to a specific location?

This is my current code.

from docx import Document
from docx.shared import Inches

demo='gm.docx'
document = Document(docx=demo)

for paragraph in document.paragraphs:
    if 'PUB' in paragraph.text:
        document.add_page_break()

document.save('gm.docx')
buhtz
  • 10,774
  • 18
  • 76
  • 149
Robert Bailey
  • 115
  • 1
  • 3
  • 10
  • I assume there is something wrong with your for loop. `document.add_page_break()` works for me and add the break at the appropriate location. – buhtz Dec 05 '22 at 10:29

1 Answers1

17

Breaks of their various forms appear at the Run level:
http://python-docx.readthedocs.io/en/latest/api/text.html#run-objects

So something like this should do the trick:

from docx.enum.text import WD_BREAK

for paragraph in document.paragraphs:
    if 'PUB' in paragraph.text:
        run = paragraph.add_run()
        run.add_break(WD_BREAK.PAGE)
scanny
  • 26,423
  • 5
  • 54
  • 80