To insert an image in a PDF using Java can be done by using a library called iText. iText is a Java library originally created by Bruno Lowagie which allows creating PDF, read PDF, and manipulate them.
Libraries required :
- iText
- slf4j (Logging Library)
Download the iText jar files directly from here & download the slf4j jar file directly from here. To use the libraries add the jar files to the classpath of the system
Approach:
- Get the current working directory of the running java program to create the PDF file in the same location
- Create a PdfWriter object (from itextpdf library) which writes the PDF file to the given path
- Create an empty PdfDocument object
- Create Image object from the image on disk
- Add Image to the Document
Implementation:
Java
import java.io.*; // importing itext library packagesimport com.itextpdf.io.image.*;import com.itextpdf.kernel.pdf.*;import com.itextpdf.layout.Document;import com.itextpdf.layout.element.Image; public class InsertImagePDF { public static void main(String[] args) throws IOException { String currDir = System.getProperty("user.dir"); // Getting path of current working directory // to create the pdf file in the same directory of // the running java program String pdfPath = currDir + "/InsertImage.pdf"; // Creating path for the new pdf file PdfWriter writer = new PdfWriter(pdfPath); // Creating PdfWriter object to write pdf file to // the path PdfDocument pdfDoc = new PdfDocument(writer); // Creating a PdfDocument object Document doc = new Document(pdfDoc); // Creating a Document object ImageData imageData = ImageDataFactory.create( currDir + "/image.jpg"); // Creating imagedata from image on disk(from given // path) using ImageData object Image img = new Image(imageData); // Creating Image object from the imagedata doc.add(img); // Adding Image to the empty document doc.close(); // Closing the document System.out.println( "Image added successfully and PDF file created!"); }} |
After execution of the program:

