Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
latheefS opened this issue Jun 3, 2024 · 1 comment
Closed

Comments

@latheefS
Copy link

latheefS commented Jun 3, 2024

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
Copy link
Contributor

scanny commented Jun 3, 2024

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

@scanny scanny closed this as completed Jun 3, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants