If you are looking to add images to pdf in java you have a couple of options:
- Insert an image as an annotations
- Insert an image into the page content stream
This article explores the pros and cons of each method and how to perform them in Java.
Image Annotations
Using annotations to insert images allows for interactivity, which lets users click, move, or delete them. This may or may not be desirable based on your use case. Annotations also provide separation of concerns, which is ideal for markup, comments, or highlights. One of the main caveats with annotations is that they may be ignored by some printers or PDF viewers, resulting in different rendering experiences on different systems.
Direct Image Insertion in the Content Stream
Inserting an image directly into the page content stream allows for greater control and reliability over the output. All PDF viewers will render them consistently. This makes them the perfect choice if you have printing or archival requirements. With this approach there is no interactivity which is the exact opposite of image annotations and your use-case will often dictate if this is appropriate.
How to insert images into PDF files using Java
Thankfully, our PDF toolkit JPedal makes both of these approaches easy.
Annotations
WritableAnnotation[] annotations = new WritableAnnotation[1];
annotations[0] = new ImageAnnotation(page, x0, y0, x1, y1, bufferedImage);
AnnotationWriter.writeAnnotations(new File("input.pdf"), new File("outputFile.pdf"), annotations);
View the Javadocs.Direct Insertion
PdfManipulator pdf = new PdfManipulator();
pdf.loadDocument(new File("inputFile.pdf"));
pdf.addImage(page, bufferedImage, new float[] {x0, y0, x1, y1});
pdf.apply();
pdf.writeDocument(new File("outputFile.pdf"));
pdf.closeDocument();
View the Javadocs.Note you will need a library to read BufferedImages, we recommend JDeli which supports a wide range of formats, including HEIC and WEBP.
You can learn more about manipulating PDFs on our support site.
This guide showed you how you can add images to PDF in Java using a few lines of code. We have over 2 decades of experience working with PDF files, read our other articles to learn more about the PDF format.