Add images to Word document using Apache POI

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. I will create here a Java based application to add images to word document using apache poi library. Using apache poi library is very easy to add images into word document.

I am going to show you example using both maven and gradle build tools. This example was tested on Apache POI version 3.15, 4.1.1, 4.1.2.

Prerequisites

Java at least 8, maven 3.6.3, gradle 6.5.1, Apache POI 3.15 or 4.1.1 or 4.1.2

Project Setup

You need to create a maven or gradle project in your favorite IDE or tool. The name of the project is apache-poi-add-images-word-docx.

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

If you are creating gradle based project then you can use below build.gradle script:

plugins {
    id 'java-library'
}

sourceCompatibility = 12
targetCompatibility = 12

repositories {
    jcenter()
}

dependencies {
    implementation 'org.apache.poi:poi-ooxml:4.1.2'
    
    //required only for jdk 9 or above
    implementation('com.fasterxml.jackson.core:jackson-databind:2.11.2')
}

If you are creating maven based project then you can use below pom.xml file:

<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-add-images-word-docx</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>at least 1.8</java.version>
		<poi.version>3.15 or 4.1.1 or 4.1.2</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>
		
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.11.2</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>

Inserting Image using Java

You already 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.

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.

You need to create first document object and paragraph object. Then You have to read the image details and insert the images into the word document.

package com.roytuts.apache.poi.add.images.word.docx;

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.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

public class WordDocxImageAdder {

	public static void main(String[] args) throws InvalidFormatException, IOException {
		File image1 = new File("image-1.png");
		File image2 = new File("image-2.png");
		
		addImagesToWordDocument(image1, image2);
	}

	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 I have added some sample text to the paragraph before I have added image to the word document.

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

I have created main method, for testing the application, which inserts or adds two images into word document from a particular location. The images are kept into the project’s root directory.

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

Source Code

Download

Thanks for reading.

6 Thoughts to “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. leeya

    hi..thanks for the code,,,but do have a code to insert image in the existing file

  3. leeya

    hi, thanks for the code,,,,but,,do you have a sample code for replace text in word document?

  4. Gopi Krishna

    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

  5. Manova

    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

    1. Did you check the pom.xml or build.gradle file?

Leave a Comment