The following example demonstrates how to add an image into a PDF document using the iText library. An image is created using the com.itextpdf.text.Image
class. To create an instance of image, we can use the Image.getInstance()
method. In the example below, we create an image from an image file name a URL that points to an image resource.
package org.kodejava.itextpdf;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileOutputStream;
import java.io.IOException;
public class ImageDemo {
public static void main(String[] args) {
Document doc = new Document();
try {
PdfWriter.getInstance(doc, new FileOutputStream("ImageDemo.pdf"));
doc.open();
// Creating image by file name
String filename = "kodejava-itextpdf/src/main/resources/java.png";
Image image = Image.getInstance(filename);
doc.add(image);
// The following line to prevent the "Server returned
// HTTP response code: 403" error.
System.setProperty("http.agent", "Chrome");
// Creating image from a URL
String url = "https://kodejava.org/wp-content/uploads/2017/01/kodejava.png";
image = Image.getInstance(url);
doc.add(image);
} catch (DocumentException | IOException e) {
e.printStackTrace();
} finally {
doc.close();
}
}
}
Maven Dependencies
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.3</version>
</dependency>
Latest posts by Wayan (see all)
- How do I use the LongToDoubleFunction functional interface in Java? - March 15, 2025
- How do I use the LongSupplier functional interface in Java? - March 14, 2025
- How do I use the LongPredicate functional interface in Java? - March 14, 2025
How can we get image from Android gallery and convert it to PDF using Kotlin?