Overview

In the previous article, we introduced how to use Apache POI Word API to create tables. In this article, we will explain how to use POI Word to insert images into a document.

Add Picture

import org.apache.poi.common.usermodel.PictureType;
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;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CreateDocPic {

  public static void main(String[] args) throws IOException, InvalidFormatException {
    try (XWPFDocument doc = new XWPFDocument()) {
      try (FileOutputStream out = new FileOutputStream("D:\\tmp\\dogeDoc.docx")) {
        XWPFParagraph p = doc.createParagraph();
        XWPFRun run = p.createRun();
        try (FileInputStream in = new FileInputStream("D:\\tmp\\doge.jpg")) {
          run.addPicture(in, PictureType.JPEG, "doge", (int) (Units.EMU_PER_CENTIMETER * 5.54), (int) (Units.EMU_PER_CENTIMETER * 6.99));
          doc.write(out);
        }
      }
    }
  }
}

The method for inserting an image is addPicture(InputStream pictureData, PictureType pictureType, String filename, int width, int height). It's worth mentioning that the width and height units used here are not pixels, but EMUs. Fortunately, the org.apache.poi.util.Units class provides some useful methods for converting different length units.

I would like to insert an image with a displayed width of 5.54cm * 6.99cm. The Units.EMU_PER_CENTIMETER in the Units class represents how many EMUs are in one centimeter. Therefore, the length needs to be multiplied by Units.EMU_PER_CENTIMETER.

Here is a screenshot of the generated document:

Feedback

Notice:Feedback requires logging into the system first.