Replace Image with New Image in Word Using Java

This article will share how to replace an existing image in a Word document with a new image programmatically by using Free Spire.Doc for Java.

Method 1: Download the Free Spire.Doc for Java and unzip it. Then add the Spire.Doc.jar file to your Java application as dependency.

Method 2: Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.


Sample Code

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

//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;

/*//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;

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



Sharing Java Code