Apache PDFBox add Image to PDF Document
This tutorial demonstrates how to add an Image to a PDF document using Apache PDFBox.
Maven Dependencies
We use Apache Maven to manage our project dependencies. Make sure the following dependencies reside on the class-path.
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.8</version>
</dependency>
Apache PDFBox add Image to PDF Document
The image is located in the src/main/resources/logo.png
location of our project.
We can create an image using PDImageXObject.createFromFile(image, doc)
. Using the PDPageContentStream
we can call the drawImage()
method. We need to calculate the dimensions of the image/position and pass it in.
package com.memorynotfound.pdf.pdfbox;
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 java.io.File;
import java.io.IOException;
public class Image {
public static void main(String[] args) throws Exception{
try (final PDDocument doc = new PDDocument()){
PDPage page = new PDPage();
doc.addPage(page);
String image = Image.class.getResource("/logo.png").getFile();
PDImageXObject pdImage = PDImageXObject.createFromFile(image, doc);
PDPageContentStream contents = new PDPageContentStream(doc, page);
PDRectangle mediaBox = page.getMediaBox();
float startX = (mediaBox.getWidth() - pdImage.getWidth()) / 2;
float startY = (mediaBox.getHeight() - pdImage.getHeight()) / 2;
contents.drawImage(pdImage, startX, startY);
contents.close();
doc.save(new File("/tmp/image.pdf"));
} catch (IOException e){
System.err.println("Exception while trying to create pdf document - " + e);
}
}
}
Output
We have added an image to a PDF document. The previous program gives the following result.
References
- Apache PdfBox Official Website
- Apache PdfBox API Javadoc
- Apache PdfBox read PDF document
- Apache PdfBox create PDF document
- PDPageContentStream JavaDoc
- PDImageXObject JavaDoc
You could also:
instead of:
if you have a byteArray.