Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

docx-python word doc page break

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')
like image 880
Robert Bailey Avatar asked Feb 07 '18 01:02

Robert Bailey


People also ask

How do you add a line break in docx python?

Looking into this some more, if you press Shift + Enter in Word it adds a manual line break (not a paragraph) via appending Chr(11) . In Open XML, this translates to a Break.

How do I insert a page break in docx?

Put your cursor where you want one page to end and the next to begin. Go to Insert > Page Break.

Does python-docx work with Doc?

Win32com → work with MS Word .doc files Despite the ease of use, the python-docx module cannot take in the aging . doc extension, and believe it or not, . doc file is still the go-to word processor for lots of stakeholders (despite the . docx being around for over a decade).


1 Answers

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)
like image 153
scanny Avatar answered Oct 07 '22 20:10

scanny