How to add image in PDF document using java iText library

In this tutorial you will learn how to add the images in PDF document using iText PDF library.

Please note we are using the iText version 5 for this example.

You can create the Image object by using below statement.

// Create an image of lord ganesh.
Image image = Image.getInstance("lord_ganesh.jpg");

You can pass the file path or any URL path to method getInstance () of Image object.

Below is the example of code show adding the image in PDF document using iText.

package com.java.connect.itext;
 
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
 
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Image;
import com.lowagie.text.pdf.PdfWriter;
 
public class PDFImageExample {
    public static void main(String[] args) throws DocumentException, MalformedURLException, IOException {
        // Create new PDF document
        Document document = new Document();
        // Create an output stream of PDF file.
        OutputStream out = new FileOutputStream("PDF_Image_Example.pdf");
        // Get a PdfWriter instance to write in PDF document.
        PdfWriter.getInstance(document, out);
        // Open the PDF document
        document.open();
        // Create an image of lord ganesh.
        Image image = Image.getInstance("lord_ganesh.jpg");
        // Add paragraph to PDF document.
        document.add(image);
        // Close the PDf document after use.
        document.close();
    }
}

The generated PDF document looks like below screen. You can see the image has been added in the PDF document.

iText-add-image-in-PDF-document-using-java-iText-library_files