Open In App

Adding Image in Existing PDF File using Java

Improve
Improve
Like Article
Like
Save
Share
Report

 These days, PDF is frequently used for report generation like to generate In order to make the java program interact with files be it of any type word, excel openCV Apache framework comes into play. External Files Required for Build this Code. The first requirement is to import the following libraries files

  1. Pdfbox-xxx.jar
  2. org.apache.commons.logging-xxx.jar

Algorithm:

  1. Linking PDF document and java program
    • Create PDDocument object
    • Create PDPage
    • Add page to document objects
    • Create FileInputStream object for image.
  2. Create PDJpeg object by passing PDDocument object and FIleInputStream as its constructor
  3. Invoke drawXObject() object and specify coordinates with width and height to draw the image onto PDF file.
  4. Close the stream, saving the document object, and close the document.

Implementation: Considering an input image sample to illustrate the working of a program where in order to illustrate the working PDF document before is as follows:

Processing with the usage of java program to insert text in the above PDF document

Java




// Adding Image in Existing PDF using Java
  
// Importing openCV libraries
import java.io.File;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.graphics.image PDImageXObject;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import java.io.IOException;
  
class GFG {
  
    // Main driver method
    public static void main(String[] args)
        throws IOException
    {
  
        // Loading an already existing pdf document
        File file = new File("D:\\javong\\pdf1.pdf");
        PDDocument doc = new PDDocument.load(file);
  
        // Retrieve the page
        PDPage page = doc.getPage(0);
  
        // Creating Object of PDImageXObject for selecting
        // Image and provide the path of file in argument
        PDImageXObject pdfimg
            = PDImageXImage.createFromFile(
                "D:\\Images\\chloro.jpg", doc);
  
        // Creating the PDPageContentStream Object
        // for Inserting Image
        PDPageContentStream image
            = new PDPageContentStream(doc, page);
  
        // set the Image inside the Page
        image.drawImage(pdfImage, 55, 370);
        System.out.println("Image Inserted");
  
        // Closing the page of PDF by closing
        // PDPageContentStream Object
        // && Saving the Document
        image.close();
        doc.save("D:\\javong\\pdf1.pdf");
  
        // Closing the Document
        doc.close();
    }
}


Output: Text inserted in the same input image.



Last Updated : 08 Dec, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads