Skip to content
Related Articles

Related Articles

Inserting Images in a PDF using Java
  • Difficulty Level : Medium
  • Last Updated : 08 Dec, 2020

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:

  1. Get the current working directory of the running java program to create the PDF file in the same location
  2. Create a PdfWriter object (from itextpdf library) which writes the PDF file to the given path
  3. Create an empty PdfDocument object
  4. Create Image object from the image on disk
  5. Add Image to the Document

Implementation:



Java




import java.io.*;
  
// importing itext library packages
import 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:

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :