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 – 5.0.0.

Prerequisites

Java at least 8, Maven 3.6.3, Gradle 6.5.1 – 6.7.1, Apache POI 3.15 – 5.0.0

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:3.1.2 to 5.0.0'
    
    //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:

<?xml version="1.0" encoding="UTF-8"?>

<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>
		<maven.compiler.source>12</maven.compiler.source>
		<maven.compiler.target>12</maven.compiler.target>
	</properties>

	<dependencies>
		<!-- apache poi for xlsx, docx etc reading/writing -->
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>3.1.2 to 5.0.0</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.1</version>
			</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 you 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

That’s all about how to add images to word docx using apache poi and Java libraries.

Source Code

Download

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

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

Leave a Reply

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