Replace Text with Image in Word in Java

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

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.TextSelection;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextRange;

public class ReplaceTextWithImage {

    public static void main(String[] args) {

        //Load a sample Word file
        Document document = new Document();
        document.loadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx");

        //Find the string 'E-iceblue' in the document
        TextSelection[] selections = document.findAllString("E-iceblue", true, true);

        //Replace the string with an image
        int index = 0;
        TextRange range = null;
        for (Object obj : selections) {

            TextSelection textSelection = (TextSelection)obj;
            DocPicture pic = new DocPicture(document);
            pic.loadImage("C:\\Users\\Administrator\\Desktop\\e-iceblue-logo.png");
            range = textSelection.getAsOneRange();
            index = range.getOwnerParagraph().getChildObjects().indexOf(range);
            range.getOwnerParagraph().getChildObjects().insert(index,pic);
            range.getOwnerParagraph().getChildObjects().remove(range);
        }

        //Save the document
        document.saveToFile("output/ReplaceTextWithImage.docx", FileFormat.Docx_2013);
    }
}

Replace Text with Image in Word in Java