Home Tutorials Training Consulting Books Company Contact us






Get more...

Java and PDF with iText. This article demonstrates how to create PDF files with Java and the iText library. In this tutorial iText version 8.x is used

1. Overview

iText is a Java library originally created by Bruno Lowagie that allows you to create PDF, read PDF and manipulate them. The following tutorial will show how to create PDF files with iText.

This tutorial uses iText 8, which is the latest major version of the library. iText 8 features a modern, fluent API design and is actively maintained.

This tutorial assumes that you have basic Java and Maven knowledge.

1.1. iText versions and licensing

iText has gone through several major versions:

  • iText 5.x - Older version with LGPL/MPL licensing (now legacy)

  • iText 7.x - Complete rewrite with new API and AGPL 3.0 licensing

  • iText 8.x - Current version with enhanced features and AGPL 3.0 licensing

Important: iText is dual-licensed under AGPL 3.0 (open source) or a commercial license. The AGPL license requires you to open source your application if you distribute it. If you cannot comply with AGPL, you need a commercial license.

Alternatives: If AGPL is not suitable for your project, consider:

  • OpenPDF - A fork of iText 5 with LGPL/MPL licensing

  • Apache PDFBox - Apache licensed PDF library

1.2. iText 8 structure

In iText 8, PDF creation follows this structure:

  • PdfWriter - Handles the low-level PDF writing to a file or stream

  • PdfDocument - Represents the PDF document structure

  • Document - High-level document for adding content (paragraphs, tables, images, etc.)

  • Paragraph - Text blocks with formatting

  • Table - Tables with cells and styling

  • Image - Images and graphics

2. Create a PDF

Create a new Maven project named com.vogella.itext.write with the package "com.vogella.itext.write". Change the pom.xml to the following.

This tutorial uses Java 21, but the code examples work with Java 17 or later.
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.vogella.itext.write</groupId>
    <artifactId>com.vogella.itext.write</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>21</maven.compiler.source>
        <maven.compiler.target>21</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.13.0</version>
                <configuration>
                    <source>${maven.compiler.source}</source>
                    <target>${maven.compiler.target}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>

        <!-- iText 8 core library -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-core</artifactId>
            <version>8.0.5</version>
            <type>pom</type>
        </dependency>

    </dependencies>
</project>

Create the following class FirstPdf.java. This example demonstrates the basic structure of creating a PDF with iText 8. Note the use of try-with-resources to ensure proper resource cleanup.

package com.vogella.itext.write;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.time.LocalDate;

import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.AreaBreak;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.List;
import com.itextpdf.layout.element.ListItem;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.properties.TextAlignment;
import com.itextpdf.layout.properties.UnitValue;

public class FirstPdf {
    private static final String FILE = "FirstPdf.pdf";

    public static void main(String[] args) {
        try {
            createPdf(FILE);
            System.out.println("PDF created successfully: " + FILE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void createPdf(String dest) throws FileNotFoundException, IOException {
        // Initialize PDF writer with try-with-resources
        try (PdfWriter writer = new PdfWriter(dest);
             PdfDocument pdf = new PdfDocument(writer);
             Document document = new Document(pdf)) {

            // Add metadata
            pdf.getDocumentInfo().setTitle("My First PDF");
            pdf.getDocumentInfo().setAuthor("Lars Vogel");
            pdf.getDocumentInfo().setSubject("Using iText 8");
            pdf.getDocumentInfo().setKeywords("Java, PDF, iText");
            pdf.getDocumentInfo().setCreator("vogella.com");

            // Add title page
            addTitlePage(document);

            // Start a new page
            document.add(new AreaBreak());

            // Add content
            addContent(document);
        }
    }

    private static void addTitlePage(Document document) {
        // Add title
        Paragraph title = new Paragraph("Title of the Document")
                .setFontSize(24)
                .setBold()
                .setTextAlignment(TextAlignment.CENTER);
        document.add(title);

        // Add empty line
        document.add(new Paragraph("\n"));

        // Add generation info
        Paragraph info = new Paragraph(
                "Report generated by: " + System.getProperty("user.name") +
                ", " + LocalDate.now())
                .setFontSize(12)
                .setBold();
        document.add(info);

        // Add description
        for (int i = 0; i < 3; i++) {
            document.add(new Paragraph("\n"));
        }

        Paragraph description = new Paragraph(
                "This document describes something which is important")
                .setFontSize(12)
                .setBold();
        document.add(description);

        // Add disclaimer
        for (int i = 0; i < 8; i++) {
            document.add(new Paragraph("\n"));
        }

        Paragraph disclaimer = new Paragraph(
                "This document is a preliminary version and not subject " +
                "to your license agreement or any other agreement with vogella.com ;-)")
                .setFontSize(12)
                .setFontColor(ColorConstants.RED);
        document.add(disclaimer);
    }

    private static void addContent(Document document) {
        // Add first chapter
        Paragraph chapter1 = new Paragraph("First Chapter")
                .setFontSize(18)
                .setBold();
        document.add(chapter1);

        // Add subcategory 1
        Paragraph subCat1 = new Paragraph("Subcategory 1")
                .setFontSize(16)
                .setBold();
        document.add(subCat1);
        document.add(new Paragraph("Hello"));

        // Add subcategory 2
        Paragraph subCat2 = new Paragraph("Subcategory 2")
                .setFontSize(16)
                .setBold();
        document.add(subCat2);
        document.add(new Paragraph("Paragraph 1"));
        document.add(new Paragraph("Paragraph 2"));
        document.add(new Paragraph("Paragraph 3"));

        // Add a list
        List list = new List()
                .setSymbolIndent(12)
                .setListSymbol("\u2022")
                .setFontSize(12);
        list.add(new ListItem("First point"));
        list.add(new ListItem("Second point"));
        list.add(new ListItem("Third point"));
        document.add(list);

        // Add some space
        for (int i = 0; i < 5; i++) {
            document.add(new Paragraph("\n"));
        }

        // Add a table
        createTable(document);

        // Add second chapter
        document.add(new Paragraph("\n"));
        Paragraph chapter2 = new Paragraph("Second Chapter")
                .setFontSize(18)
                .setBold();
        document.add(chapter2);

        Paragraph subCat3 = new Paragraph("Subcategory")
                .setFontSize(16)
                .setBold();
        document.add(subCat3);
        document.add(new Paragraph("This is an important message"));
    }

    private static void createTable(Document document) {
        // Create table with 3 columns
        Table table = new Table(UnitValue.createPercentArray(new float[]{1, 1, 1}))
                .useAllAvailableWidth();

        // Add header cells
        table.addHeaderCell(new Cell().add(new Paragraph("Table Header 1")
                .setTextAlignment(TextAlignment.CENTER)
                .setBold()));
        table.addHeaderCell(new Cell().add(new Paragraph("Table Header 2")
                .setTextAlignment(TextAlignment.CENTER)
                .setBold()));
        table.addHeaderCell(new Cell().add(new Paragraph("Table Header 3")
                .setTextAlignment(TextAlignment.CENTER)
                .setBold()));

        // Add data cells
        table.addCell("1.0");
        table.addCell("1.1");
        table.addCell("1.2");
        table.addCell("2.1");
        table.addCell("2.2");
        table.addCell("2.3");

        document.add(table);
    }
}

The resulting PDF should look similar to the previous version but uses the modern iText 8 API.

pdfwrite10

3. Formatting your output

Paragraphs allow setting the alignment and indentation. For this example, add the following class to your project. Create the following class PositionPdf.java.

package com.vogella.itext.position;

import java.io.FileNotFoundException;
import java.io.IOException;

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.properties.TextAlignment;

public class PositionPdf {
    private static final String FILE = "PositionPdf.pdf";

    public static void main(String[] args) {
        try {
            createPdf(FILE);
            System.out.println("PDF created successfully: " + FILE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void createPdf(String dest) throws FileNotFoundException, IOException {
        // Initialize PDF writer with try-with-resources
        try (PdfWriter writer = new PdfWriter(dest);
             PdfDocument pdf = new PdfDocument(writer);
             Document document = new Document(pdf)) {

            // Right aligned text
            Paragraph paragraph = new Paragraph("This is right aligned text")
                    .setTextAlignment(TextAlignment.RIGHT);
            document.add(paragraph);

            // Centered text
            paragraph = new Paragraph("This is centered text")
                    .setTextAlignment(TextAlignment.CENTER);
            document.add(paragraph);

            // Left aligned text (default)
            paragraph = new Paragraph("This is left aligned text")
                    .setTextAlignment(TextAlignment.LEFT);
            document.add(paragraph);

            // Left aligned with indentation
            paragraph = new Paragraph("This is left aligned text with indentation")
                    .setTextAlignment(TextAlignment.LEFT)
                    .setMarginLeft(50);
            document.add(paragraph);
        }
    }
}

4. Read an existing PDF

iText allows you to read existing PDFs and include pages from them in your own PDF. The following example reads page 2 of the previous example and creates a new document with this page.

Create the following class ReadAndUsePdf.java.

package com.vogella.itext.read;

import java.io.FileNotFoundException;
import java.io.IOException;

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;
import com.itextpdf.layout.Document;

public class ReadAndUsePdf {
    private static final String INPUTFILE = "FirstPdf.pdf";
    private static final String OUTPUTFILE = "ReadPdf.pdf";

    public static void main(String[] args) {
        try {
            createPdf(OUTPUTFILE);
            System.out.println("PDF created successfully: " + OUTPUTFILE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void createPdf(String dest) throws FileNotFoundException, IOException {
        // Read the source PDF
        try (PdfReader reader = new PdfReader(INPUTFILE);
             PdfDocument srcDoc = new PdfDocument(reader);
             PdfWriter writer = new PdfWriter(dest);
             PdfDocument pdfDoc = new PdfDocument(writer);
             Document document = new Document(pdfDoc)) {

            int numberOfPages = srcDoc.getNumberOfPages();

            // Go through all pages and only include page 2
            for (int i = 1; i <= numberOfPages; i++) {
                if (i == 2) {
                    // Get page 2 from source document
                    PdfPage origPage = srcDoc.getPage(i);

                    // Create a form XObject from the page
                    PdfFormXObject pageCopy = origPage.copyAsFormXObject(pdfDoc);

                    // Add a new page to destination document
                    PdfPage page = pdfDoc.addNewPage();

                    // Create canvas and add the copied page
                    PdfCanvas canvas = new PdfCanvas(page);
                    canvas.addXObjectAt(pageCopy, 0, 0);
                }
            }
        }
    }
}

This example demonstrates how to:

  • Read an existing PDF using PdfReader

  • Copy a specific page from one PDF to another

  • Use PdfFormXObject to handle page copying

  • Properly manage resources with try-with-resources

5. Links and Literature