Introduction

Add images to word document using apache poi will show you how to insert or add images into a Word document using Apache POI API. We will create here a Java application to add images to word document using apache poi library. Using apache poi library is very easy for any kind of doing activities in word document.

I am going to show you example using both maven and gradle build tools. This example is also run on Apache POI version 3.15. Here I am using Apache POI version 4.1.1.

Prerequisites

The following configurations are required in order to run the application

Eclipse 4.12, JDK 1.8 or 12, maven 3.6.1, gradle 5.6, Apache POI 3.15 or 4.1.1

Creating Project

You need to create a maven or gradle project in eclipse with below information:

Group Id - com.roytuts
Artifact Id - apache-poi-word

Updating Build File

Once the project is created and eclipse finishes build then you need to modify the pom.xml file as shown below.

Here we will add apache poi API as a dependency for working with microsoft word document or even you can work with open source word document.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.roytuts</groupId>
	<artifactId>apache-poi-word</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
	<name>apache-poi-word</name>
	<url>http://maven.apache.org</url>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>1.8 or 12</java.version>
		<poi.version>3.15 or 4.1.1</poi.version>
	</properties>
	<dependencies>
		<!-- apache poi for xlsx, docx etc reading/writing -->
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>${poi.version}</version>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.1</version>
                                <configuration>
					<source>${java.version}</source>
					<target>${java.version}</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

If you want to use gradle based project then use below build script (build.gradle) to setup the project. Here also we have used the same apache poi version as you have seen in the above maven based pom.xml file.

apply plugin: 'java-library'

sourceCompatibility = 1.8 or 12
targetCompatibility = 1.8 or 12

repositories {
    jcenter()
}

dependencies {
	compile("org.apache.poi:poi-ooxml:3.15 or 4.1.1")
}

Inserting Image using Java

We know how to insert image or an object, i.e., a file into the word document manually from an option given in the word document but here we will see how to add images to word document using apache poi using Java program.

Related Posts:

Therefore create below class to insert or add images into word file.

The below class basically adds or inserts two images into the word file.

We create first document object and paragraph object. Then we read the image details and insert the images into the word document.

package com.roytuts.apache.poi.word;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.BreakType;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
public class WordDocument {
	public static void addImagesToWordDocument(File imageFile1, File imageFile2)
			throws IOException, InvalidFormatException {
		XWPFDocument doc = new XWPFDocument();
		XWPFParagraph p = doc.createParagraph();
		XWPFRun r = p.createRun();
		BufferedImage bimg1 = ImageIO.read(imageFile1);
		int width1 = bimg1.getWidth();
		int height1 = bimg1.getHeight();
		BufferedImage bimg2 = ImageIO.read(imageFile2);
		int width2 = bimg2.getWidth();
		int height2 = bimg2.getHeight();
		String imgFile1 = imageFile1.getName();
		String imgFile2 = imageFile2.getName();
		int imgFormat1 = getImageFormat(imgFile1);
		int imgFormat2 = getImageFormat(imgFile2);
		String p1 = "Sample Paragraph Post. This is a sample Paragraph post. Sample Paragraph text is being cut and pasted again and again. This is a sample Paragraph post. peru-duellmans-poison-dart-frog.";
		String p2 = "Sample Paragraph Post. This is a sample Paragraph post. Sample Paragraph text is being cut and pasted again and again. This is a sample Paragraph post. peru-duellmans-poison-dart-frog.";
		r.setText(p1);
		r.addBreak();
		r.addPicture(new FileInputStream(imageFile1), imgFormat1, imgFile1, Units.toEMU(width1), Units.toEMU(height1));
		// page break
		// r.addBreak(BreakType.PAGE);
		// line break
		r.addBreak();
		r.setText(p2);
		r.addBreak();
		r.addPicture(new FileInputStream(imageFile2), imgFormat2, imgFile2, Units.toEMU(width2), Units.toEMU(height2));
		FileOutputStream out = new FileOutputStream("word_images.docx");
		doc.write(out);
		out.close();
		doc.close();
	}
	private static int getImageFormat(String imgFileName) {
		int format;
		if (imgFileName.endsWith(".emf"))
			format = XWPFDocument.PICTURE_TYPE_EMF;
		else if (imgFileName.endsWith(".wmf"))
			format = XWPFDocument.PICTURE_TYPE_WMF;
		else if (imgFileName.endsWith(".pict"))
			format = XWPFDocument.PICTURE_TYPE_PICT;
		else if (imgFileName.endsWith(".jpeg") || imgFileName.endsWith(".jpg"))
			format = XWPFDocument.PICTURE_TYPE_JPEG;
		else if (imgFileName.endsWith(".png"))
			format = XWPFDocument.PICTURE_TYPE_PNG;
		else if (imgFileName.endsWith(".dib"))
			format = XWPFDocument.PICTURE_TYPE_DIB;
		else if (imgFileName.endsWith(".gif"))
			format = XWPFDocument.PICTURE_TYPE_GIF;
		else if (imgFileName.endsWith(".tiff"))
			format = XWPFDocument.PICTURE_TYPE_TIFF;
		else if (imgFileName.endsWith(".eps"))
			format = XWPFDocument.PICTURE_TYPE_EPS;
		else if (imgFileName.endsWith(".bmp"))
			format = XWPFDocument.PICTURE_TYPE_BMP;
		else if (imgFileName.endsWith(".wpg"))
			format = XWPFDocument.PICTURE_TYPE_WPG;
		else {
			return 0;
		}
		return format;
	}
}

Here in the above source code we have added some sample text to the paragraph before we have added image to the word document.

We have also added line break between the image and next paragraph. If you want to insert page break then you can uncomment the line of code for page break and comment the line of code for line break.

Creating Main Class

Now create the main class which will test our application.

The below class inserts or adds two images into word document from a particular location.

package com.roytuts.apache.poi.main;
import java.io.File;
import java.io.IOException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import com.roytuts.apache.poi.word.WordDocument;
public class WordDocumentApp {
	public static void main(String[] args) throws InvalidFormatException, IOException {
		File image1 = new File("C:\\Users\\soumi\\Desktop\\application.jpg");
		File image2 = new File("C:\\Users\\soumi\\Desktop\\release.jpg");
		WordDocument.addImagesToWordDocument(image1, image2);
	}
}

Testing the Application

Run the above class to see the output in word_images.docx file. The file is created under root directory of the project.

Now open the created word document you should see the expected output similar to below image.

add images to word document using apache poi

Thanks for reading.

Tags:

6 thoughts on “Add images to Word document using Apache POI

  1. Hi, this is nice document for developers.
    I research this topic and I found on the net compatible API for Java and Android caled JWord for Microsoft Word or compatible API for Java and Android caled JOffice for Microsoft Office.
    There are a number of use cases on the site and the API itself is well documented.
    API is available and for .NET which is great!
    API developed by Independentsoft company.

  2. Hi Thanks for the code..when i try to open the word document it says “We’re sorrt, we can’t open…”
    Thanks,
    Gopi Krishna

  3. Hi
    Thanks for the details example. while i was trying i am getting class not found error. could you please tell me what are the jar files and version

Leave a Reply

Your email address will not be published. Required fields are marked *