Find & Replace Text & Images in Word Document using Aspose.Words for Java

I want to replace particular text and image in a word document which is having the format '.docx '.
How can I achieve this using Aspose.Words in Java?

@tusharvelingkar,

Please refer to the following article:

Also, you can move cursor to any target image, insert new content there and remove it by using following Aspose.Words for Java code:

Document doc = new Document("C:\\Temp\\word.docx");
DocumentBuilder builder = new DocumentBuilder(doc);

Shape target = null;
for (Shape shape : (Iterable<Shape>) doc.getChildNodes(NodeType.SHAPE, true)) {
    if (shape.hasImage()) {
        if (shape.getAlternativeText() == "match") {
            target = shape;
            break;
        }
    }
}

if (target != null) {
    builder.moveTo(target);
    builder.write("new content");
    target.remove();
}

doc.save("C:\\temp\\output.docx");

@awais.hafeez Thank you for your quick reply.
I go the text replacement part.
What I am looking for is replacing a specific image with another image in the document?
Do you have any code snippets for the same?

@tusharvelingkar,

Please try the following code:

Document doc = new Document("C:\\Temp\\word.docx");
DocumentBuilder builder = new DocumentBuilder(doc);

Shape target = null;
for (Shape shape : (Iterable<Shape>) doc.getChildNodes(NodeType.SHAPE, true)) {
    if (shape.hasImage()) {
        if (shape.getAlternativeText() == "match") {
            target = shape;
            break;
        }
    }
}

if (target != null) {
    builder.moveTo(target);
    builder.insertImage("image.png");
    target.remove();
}

doc.save("C:\\temp\\output.docx");

In case the problem still remains, then please ZIP and attach the following resources here for testing:

  • Your simplified source Word document you want to find and replace images in
  • Aspose.Words generated DOCX file showing the undesired behavior (if any)
  • Your expected DOCX file showing the desired output. You can create this document manually by using MS Word.

As soon as you get these pieces of information ready, we will start further investigation into your scenario and provide you code to achieve the same output by using Aspose.Words API.