iText PDF Java API Introduction
I am starting with a tutorial series for iText PDF API and how to use it with Java applications.
iText PDF API is one of the popular most API for working with PDF documents in Java.
In this article, I will help you to get started with iText with a simple Java program and in the coming tutorials you can learn about generating complex PDF documents.
Download iText or Setup via Maven
You can either download the iText jars from its website or you use it via the Maven central repository using the following dependency.
<dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.8</version> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-pdfa</artifactId> <version>5.5.8</version> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-xtra</artifactId> <version>5.5.8</version> </dependency> <dependency> <groupId>com.itextpdf.tool</groupId> <artifactId>xmlworker</artifactId> <version>5.5.8</version> </dependency>
Example iText PDF Java Program
Following is a hello world Java example program that creates a new PDF file.
- In this program our first step is to instantiate the
Document
class from itext core. - Then use the
PdfWriter
util class to create a fresh PDF file. - Followed by writing text into the newly created PDF document as paragraph.
I have added itextpdf-5.5.9.jar
as project dependency.
package com.javapapers.java.itext;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
public class HelloWorldIText {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter.getInstance(document, new FileOutputStream(
"MyFirstDynamic.pdf"));
document.open();
document.add(new Paragraph(
"iText Core is the library that allows you to create, process and edit PDF documents"));
document.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}