Skip to content
Related Articles

Related Articles

Adding Image in Existing PDF File using Java

Improve Article
Save Article
  • Last Updated : 08 Dec, 2020
Improve Article
Save Article

 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


  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


// Adding Image in Existing PDF using Java
// Importing openCV libraries
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import PDImageXObject;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
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
        // Closing the Document

Output: Text inserted in the same input image.

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!