Java Examples - Insert Image in PDF


Advertisements

Problem Description

How to insert image in a PDF using Java.

Solution

Following is an example program to insert image in a PDF using Java.

import java.io.File;  

import org.apache.pdfbox.pdmodel.PDDocument; 
import org.apache.pdfbox.pdmodel.PDPage; 
import org.apache.pdfbox.pdmodel.PDPageContentStream; 
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;  

public class InsertingImageInPdf { 
   public static void main(String args[]) throws Exception {  
      
      //Loading an existing document 
      File file = new File("C:/pdfBox/InsertImage_IP.pdf"); 
      PDDocument doc = PDDocument.load(file); 

      //Retrieving the page 
      PDPage page = doc.getPage(0); 

      //Creating PDImageXObject object 
      PDImageXObject pdImage = PDImageXObject.createFromFile("C:/pdfBox/logo.png", doc); 

      //creating the PDPageContentStream object 
      PDPageContentStream contents = new PDPageContentStream(doc, page); 

      //Drawing the image in the PDF document 
      contents.drawImage(pdImage, 70, 250);     
      System.out.println("Image inserted"); 

      //Closing the PDPageContentStream object 
      contents.close();       

      //Saving the document 
      doc.save("C:/pdfBox/InsertImage_OP.pdf"); 
      
      //Closing the document  
      doc.close(); 
   }  
} 

Input

Insert Image Input

Output

Insert Image Output
java_apache_pdf_box
Advertisements