Adding pictures to .docx files with Apache POI with XWPFDocument

7.1k Views Asked by At

I've been trying to add .jpg pictures to .docx files with Apache POI. XWPFDocument.addPictureData doesn't seem to work.

XWPFDocument docx = new XWPFDocument();
FileOutputStream fos = new FileOutputStream(...);
InputStream pic = new FileInputStream(...);
docx.addPictureData(pic,Document.PICTURE_TYPE_JPEG);
docx.write(fos);

This creates a new, seemingly blank, .docx file.

1

There are 1 best solutions below

0
On

I'm probably late for this one but this issue https://issues.apache.org/bugzilla/show_bug.cgi?id=49765 describes your problem.

As of poi-3.7 you can also use XWPFRun.addPicture(InputStream, int, String, int, int) to add a picture, like so:

docx.createParagraph().createRun().addPicture(pic, Document.PICTURE_TYPE_JPEG, "my pic", Units.toEMU(200), Units.toEMU(200));

I'll update the answer if I figure out what's actually wrong with the addPicture method.