- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to add multiple images in a PDF document using Java
Problem Description
How to add multiple images in a PDF document using Java.
Solution
Following is the program to add multiple images in a PDF document using Java.
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
public class AddingMultipleImages {
public static void main(String args[]) throws Exception {
String file = "C:/EXAMPLES/itextExamples/addingMultipleImagesToPDF.pdf";
String[] IMAGES = {
"C:/EXAMPLES/itextExamples/logo.jpg",
"C:/EXAMPLES/itextExamples/javafxLogo.jpg",
"C:/EXAMPLES/itextExamples/tpPoster.jpg" };
//Creating the images
Image image = new Image(ImageDataFactory.create(IMAGES[0]));
//Creating the PdfDocument class
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(file));
//Creating a Document
Document doc = new Document(pdfDoc, new PageSize(image.getImageWidth(),
image.getImageHeight()));
for (int i = 0; i < IMAGES.length; i++) {
image = new Image(ImageDataFactory.create(IMAGES[i]));
pdfDoc.addNewPage(new PageSize(image.getImageWidth(),
image.getImageHeight()));
image.setFixedPosition(i + 1, 0, 0);
doc.add(image);
}
//Closing the document
doc.close();
System.out.println("Images added successfully..");
}
}
Input
Output
java_itext
Advertisements