Replace Image with New Image in Word Using Java

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>
import com.spire.doc.Document;
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();
doc.loadFromFile("jellyfish.docx");

//Get the first section
Section section = doc.getSections().get(0);
Paragraph para = section.getParagraphs().get(1);

//Replace the first image in this section with new image
Object obj = para.getChildObjects().get(0);
if(obj instanceof DocPicture){
DocPicture pic = (DocPicture)obj;
pic.loadImage("C:\\Users\\Administrator\\Desktop\\img1.jpg");
}

/*//Replace all images
for(int i =0;i < section.getParagraphs().getCount();i++){
Object obj = section.getParagraphs().get(i).getChildObjects();
if(obj instanceof DocPicture){
DocPicture pic = (DocPicture)obj;
pic.loadImage("tp.png");
}
}*/

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

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store