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.

Prerequisites

The following configurations are required in order to run the application

Eclipse Kepler
JDK 1.8
Have maven 3 installed and configured
Apache POI dependency in pom.xml

You basically need to create a maven project in eclipse.

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.jeejava</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</java.version>
		<poi.version>3.15</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>
				<configuration>
					<source>${java.version}</source>
					<target>${java.version}</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

If you want to use gradle build script to create your project then use below build script 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'

repositories {
    jcenter()
}

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

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.

You may like to read also:

how to create a word document using apache poi

create table in word document using apache poi

create header and footer in word document using apache poi

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.jeejava.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.

Now create the main class which will test our application:

package com.jeejava.apache.poi.main;

import java.io.File;
import java.io.IOException;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;

import com.jeejava.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);
	}

}

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:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit | Email Me

Leave a Reply

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