Replacing a run text by a paragraph

I have document with text inserted in a text box
source.docx (14.8 KB)

. I want to read the text of the 2nd run and put it in a new paragraph.
Here is my code:


import sys
import os
import aspose.words as aw

def process_document(doc_path):
    # Load the document
    doc = aw.Document(doc_path)

    # Get the second run in the document
    second_run = doc.get_child(aw.NodeType.RUN, 1, True).as_run()
    
    if second_run:
        # Create a new paragraph
        new_paragraph = aw.Paragraph(doc)
        # Insert the new paragraph after the last paragraph
        doc.last_section.body.append_child(new_paragraph)
        
        # Apply "Heading 1" style to the new paragraph
        new_paragraph.paragraph_format.style_name = "Heading 1"

        # Insert the text of the second run into the new paragraph
        new_run = second_run.clone(True)
        new_paragraph.append_child(new_run)


        # Save the modified document
        output_path = os.path.splitext(doc_path)[0] + "_modified.docx"
        doc.save(output_path)
        print("Document saved successfully as:", output_path)
    else:
        print("No second run found in the document.")

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python script.py <input_docx>")
        sys.exit(1)
    
    input_docx = sys.argv[1]
    process_document(input_docx)

The issue is that the inserted paragraph is outside the text box (see result)
source_modified.docx (14.6 KB)

Any help is appreciated.

@ansar2024 Do you need to put the newly created paragraph into the shape? If so you can use the following code:

doc = aw.Document("C:\\Temp\\source.docx")

# Get the second run in the document
second_run = doc.get_child(aw.NodeType.RUN, 1, True).as_run()

# Create a new paragraph
new_paragraph = aw.Paragraph(doc)
# Apply "Heading 1" style to the new paragraph
new_paragraph.paragraph_format.style_name = "Heading 1"
new_run = second_run.clone(True)
new_paragraph.append_child(new_run)

# Get shape
shape = doc.get_child(aw.NodeType.SHAPE, 0, True).as_shape()
# Put the newly created paragraph into the shape.
shape.append_child(new_paragraph)

doc.save("C:\Temp\out.docx")

out.docx (10.5 KB)

1 Like

That is exactly what I was trying to achieve. Thanks a lot for your support.

1 Like