Replace Image with New Image in Word in Java

This article demonstrates how to replace an existing image in a Word document with a new image using Spire.Doc for Java.

Below is the screenshot of the original Word document before replacing image:

Replace Image with New Image in Word in Java

import com.spire.doc.Document;
import com.spire.doc.DocumentObject;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.DocPicture;

public class ReplaceImages {
    public static void main(String[] args){
        //Load the Word document
        Document doc = new Document();

        //Get the first section
        Section section = doc.getSections().get(0);

        //Loop through the paragraphs in the section
        for (Paragraph para:(Iterable) section.getParagraphs()
             ) {
            //Loop through the child object in the paragraph
            for (DocumentObject obj:(Iterable) para.getChildObjects()
                 ) {
                //Replace image with new image
                if(obj instanceof DocPicture){
                    DocPicture pic = (DocPicture)obj;

        //Save the resultant document
        doc.saveToFile("ReplaceWithImage.docx", FileFormat.Docx_2013);


Replace Image with New Image in Word in Java