python-openxml / python-docx

Create and modify Word documents with Python
MIT License
4.38k stars 1.08k forks source link

Inserting a new page before last page in the word document using python #1402

Closed latheefS closed 1 month ago

latheefS commented 1 month ago

Hi,

I am adding a page with a heading (but not a header) before the last page of the existing Word document. And for this, I used the code below.

**doc = Document('<myfilepath>/Report.docx')  --ignore the filepath

current_section = doc.sections[-1]
print(current_section.start_type)
new_section = doc.add_section(start_type=WD_SECTION.NEW_PAGE)

#Intro_heading = new_section.add_heading('Introduction', level=1)
Intro_heading = new_section.add_paragraph("Introduction")**

I've developed code to enter the content before the last page of the input Word document I provide. Now to add the content before the last page I've added the above code and it is failing with the below issues.

Error for adding heading:

**Intro_heading = new_section.add_heading('Introduction', level=1)
                ^^^^^^^^^^^^^^^^^^^^^^^

AttributeError: 'Section' object has no attribute 'add_heading'**

Error for adding paragraph:

**Intro_heading = new_section.add_paragraph("Introduction")
                ^^^^^^^^^^^^^^^^^^^^^^^^^

AttributeError: 'Section' object has no attribute 'add_paragraph'**

Note that i don't want to start off with paragraph instead i want to start off with heading in the new insert page.

Can someone please help me with this issue?

scanny commented 1 month ago

Have a look at this method on Paragraph: https://python-docx.readthedocs.io/en/latest/api/text.html#docx.text.paragraph.Paragraph.insert_paragraph_before

As you've discovered, a section is not a block-item container so doesn't have .add_paragraph() etc.

.add_heading() is just a convenience method. You can accomplish the same by adding a paragraph and changing its style: https://python-docx.readthedocs.io/en/latest/_modules/docx/document.html#Document.add_heading