Monday, November 18, 2024
Google search engine
HomeLanguagesJavaInserting Images in a PDF using Java

Inserting Images in a PDF using Java

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:

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments