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();

        //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);
            range = textSelection.getAsOneRange();
            index = range.getOwnerParagraph().getChildObjects().indexOf(range);

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

Replace Text with Image in Word in Java