Unable to remove image from document

I have a document with 2 images (see attached document. the 2nd image is at the end of the 2nd page)
recipe1.docx (3.3 MB)

. I want to replace the last image (shape=1). I use the following python code:

import sys
import os
import aspose.words as aw
import aspose.pydrawing as drawing

doc = aw.Document("recipe1.docx")
builder = aw.DocumentBuilder(doc)
shape = doc.get_child(aw.NodeType.SHAPE, 1, True)  # Getting the first shape in the document
builder.move_to(shape)
shape.remove()  
builder.insert_image("new-img.jpg")
doc.save("AsposeOut.docx")

The issue is that I cannot replace or remove the 2nd image but I can replace/remove the 1st one when I set :shape = doc.get_child(aw.NodeType.SHAPE, 0, True)

Thank you for any help

@ansar2024 Actually there are more that one shape in your document. There is a group shape at the beginning of the document that contains multiple shapes:

Also, it is not required to insert new and remove old shape to replace the image in the shape. You can simply set new image to existing shape. Please see the following code that sets new image to the last shape in the document:

import aspose.words as aw

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

# Get all shapes.
shapes = doc.get_child_nodes(aw.NodeType.SHAPE, True)

# Get the last SHAPE
last_shape = shapes[shapes.count-1].as_shape()

# Check whether the shape has Image
if last_shape.has_image :
    # Chnage the Image
    last_shape.image_data.set_image("C:\\Temp\\test.png")

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

The code you provided works fine. I appreciate your invaluable support. Thank you!

1 Like