How to add an image to a PDF using PdfBox

written by Răzvan Puiu


In this article we'll see how to add an image to a PDF using the PdfBox library.


First, you have to add the PdfBox Maven dependency:

<dependency>
 <groupId>org.apache.pdfbox</groupId>
 <artifactId>pdfbox</artifactId>
 <version>2.0.20</version> <!-- For the latest version go HERE: -->
</dependency>

The following code snippet will insert an encoded image in the "hello-getPdfApi.pdf" file.

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import javax.xml.bind.DatatypeConverter;

...
PDDocument doc = new PDDocument();
PDPage page = new PDPage(pageFormat);
doc.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(doc, page);
PDImageXObject image = PDImageXObject.createFromByteArray(doc, DatatypeConverter.parseBase64Binary(encodedStr), "img-filename");
contentStream.drawImage(image, x, y, imgWidth, imgHeight);
doc.save("hello-getPdfApi.pdf");
doc.close();

In PdfBox, the PDDocument class is used to represent a PDF. Once you have created the document, you can add pages that are represented by the PDPage class. Just take care about the size of the image/images you want to add. You might need to keep track of the size in order to add new pages to the document.

PDImageXObject represents the image that will be added to the PDF. An "XObject" is simply an external object, in our case the image that is converted to a byte array.

The createFromByteArray method will determine the file format from the bytes of the image file. The supported file types are JPG, JPEG, TIF, TIFF, GIF, BMP and PNG.

Quote from the documentation: "Starting with 2.0.18, this call will create an image directly from a PNG file without decoding it (when possible), which is faster. However the result size depends on the compression skill of the software that created the PNG file. If file size or bandwidth are important to you or to your clients, then create your PNG files with a tool that has implemented the Zopfli algorithm, or use the two-step process mentioned above."


After you have successfully created your image, it's time to draw it in the Content Stream. The PDPageContentStream provides the ability to write content to a page, and the drawImage() method will write an image with a specific width and height at the X Y coordinates.

Just make sure you don't call it from within a text bloc or you'll see the IllegalStateException :)

After you finish writing, you can save the document to a file or to a byte array if that's your use case, but just make sure you also close it.