Python-docx, making a word file and need to detect whether on new page or not -


i using python-docx module make lots , lots of documents generated on demand data. there several parts when insert figures conventional document.add_picture command so:

document.add_picture(img_after_crop, width=inches(width))  

the problem i'm having many of pictures charts finish section after chart want move new page, images of different sizes have filled page. if put page break after image nice figure new page of next section , other times (if image fills page) flow has moved on next page , page break leave empty page. i'm looking way prevent this. if there way current page number, can see how fix problem. moving using "sections" fix (for example sections automatically start new page not advance page if we're on blank page)? detecting page advancement in document being worked on ideal, i'm open solution...

solution

the correct answer in short form below, took me trial , error figure out right way use record here minimum code snippet on how use page_break_before make heading or paragraph jump next page:

from docx import document document = document() document.add_heading('document title', 0) para = document.add_heading("this heading goes @ top of new page", level=1) para.paragraph_format.page_break_before=true document.add_paragraph('just text goes here. normal paragraph') document.save('doctest.docx') 

this python generate test word document title on first page heading jumps next page , following paragraph goes beneath it. key trick paragraph_format access , lets use alignment settings, keep_together settings, , on paragraph_format options. needed cobble couple examples figure out set value figured i'd post posterity.

try setting paragraph formatting of paragraph after image .page_break_before = true. word rendering engine intelligent enough not add page break if paragraph happens occur first on new page.


Comments