Inserting Images in a PDF using Java
Last Updated :
08 Dec, 2020
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:
- Get the current working directory of the running java program to create the PDF file in the same location
- Create a PdfWriter object (from itextpdf library) which writes the PDF file to the given path
- Create an empty PdfDocument object
- Create Image object from the image on disk
- Add Image to the Document
Implementation:
Java
import java.io.*;
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" );
String pdfPath = currDir + "/InsertImage.pdf" ;
PdfWriter writer = new PdfWriter(pdfPath);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
ImageData imageData = ImageDataFactory.create(
currDir + "/image.jpg" );
Image img = new Image(imageData);
doc.add(img);
doc.close();
System.out.println(
"Image added successfully and PDF file created!" );
}
}
|
After execution of the program:
Share your thoughts in the comments
Please Login to comment...