PDF Generation in Java with iText

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

What is iText and why is it needed?

iText is a powerful library for Java, designed for creating and processing PDF documents. It allows you to programmatically generate PDF files, add text, images, tables, forms, and annotations. The library is widely used in enterprise applications for automating reports, invoices, contracts, and other documents. The main advantage of iText is full control over the content and structure of the PDF.

Installing iText

To add iText to a Maven project, add the dependency in pom.xml:

<dependency>    <groupId>com.itextpdf</groupId>    <artifactId>itext7-core</artifactId>    <version>7.2.5</version>    <type>pom</type></dependency>

For Gradle:

implementation 'com.itextpdf:itext7-core:7.2.5'

Main features of iText

  • Creating PDF from scratch: adding paragraphs, tables, images.
  • Working with forms: filling and extracting data from AcroForms.
  • Encryption and protection: setting passwords, restricting printing or copying.
  • Converting HTML to PDF: using the html2pdf module.
  • Merging and splitting pages: working with multiple documents.

Java code example

Let's create a simple PDF with text and a table:

import com.itextpdf.kernel.pdf.PdfDocument;import com.itextpdf.kernel.pdf.PdfWriter;import com.itextpdf.layout.Document;import com.itextpdf.layout.element.Paragraph;import com.itextpdf.layout.element.Table;

public class PdfGenerator { public static void main(String[] args) throws Exception { String dest = "example.pdf"; PdfWriter writer = new PdfWriter(dest); PdfDocument pdf = new PdfDocument(writer); Document document = new Document(pdf);

// Adding a title document.add(new Paragraph("Hello, world!"));

// Creating a 3x2 table Table table = new Table(3); table.addCell("Name"); table.addCell("Age"); table.addCell("City"); table.addCell("Anna"); table.addCell("25"); table.addCell("Moscow"); table.addCell("Ivan"); table.addCell("30"); table.addCell("St. Petersburg");

document.add(table); document.close(); System.out.println("PDF created: " + dest); }}

When to use iText

The library is ideal for:

  • Generating reports and invoices in web applications (Spring Boot, Java EE).
  • Automating document workflows: contracts, acts, invoices.
  • Creating interactive PDF forms for user filling.
  • Converting HTML templates to PDF for printing or distribution.

iText is the de facto standard for working with PDF in Java. Alternatives: Apache PDFBox (more low-level) and Aspose.PDF (commercial).

Recommendations