I have been trying to add a sectional break into my word document using python-docx. I basically want to add a sectional break before every paragraph having style = “heading 1”. I have written the following code. The code goes as follows:
1)get the total number of paragraphs
2)find the index of the paragraph with style = “heading 1”
3)add a run to the paragraph which is before the paragraph having style = “heading 1”
4)add a sectional break to the run
z=len(doc.paragraphs) for i in range(0,z): if doc.paragraphs[i].style.name == "Heading 1": run_new=doc.paragraphs[i-1].add_run() run_new.add_break(docx.enum.text.WD_BREAK.SECTION_NEXT_PAGE)
But it gives me this error.
Traceback (most recent call last): File "D:/Pycharm Projects/pydocx/trial4.py", line 8, in <module> run_new.add_break(docx.enum.text.WD_BREAK.SECTION_NEXT_PAGE) File "D:Pycharm Projectspydocxenvlibsite-packagesdocxtextrun.py", line 42, in add_break }[break_type] KeyError: 2
How should I add the sectional break?
Advertisement
Answer
python-docx
currently has no API support for inserting a section break at an arbitrary location. You can only add a new section at the end of the document, typically in the course of generating a new document from the top down to the bottom.
>>> new_section = document.add_section(WD_SECTION.ODD_PAGE) >>> new_section.start_type ODD_PAGE (4)
There is more on adding a section on the documentation page here:
https://python-docx.readthedocs.io/en/latest/user/sections.html