How to Get Started with iText 8: A Beginner’s Guide to Library and API Usage

iText is a highly versatile and robust library used for creating and manipulating PDF files in Java. It is capable of generating high-quality documents with complex layouts and rich multimedia content.

The ease of embedding text, images, tables, and interactive forms in PDFs make it a go-to library for developers dealing with document-intensive applications. It is programmatically accessible, providing developers with complete control over the PDF creation and manipulation process.

Another significant feature of iText is its ability to handle advanced PDF features such as watermarks, encryption, and Digital Rights Management (DRM), which make it a great tool for more complex and advanced projects. It also provides a mechanism to create bookmarks, annotations, and comments, making it easier to navigate through voluminous PDFs.

iText is a powerful library that allows developers to generate and manipulate PDF files in Java. To get started with iText 8 in your Java project, follow these steps:

In your Maven pom.xml file, add the following dependency:

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-core</artifactId>
    <version>8.0.2</version>
    <type>pom</type>
</dependency>

Maven Central

Once you have added the iText dependency to your project, you can start using it to create PDFs. Here’s a simple example code that creates a PDF file and adds a paragraph to it:

package org.kodejava.itext;

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

import java.io.FileNotFoundException;

public class CreatePDFIntro {
    public static void main(String[] args) {
        try {
            PdfWriter writer = new PdfWriter("HelloWorld.pdf");
            PdfDocument pdf = new PdfDocument(writer);
            Document document = new Document(pdf);
            document.add(new Paragraph("Hello World!"));
            document.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}

This code will create a file named HelloWorld.pdf in the root folder of your project, containing a single paragraph with the text “Hello, World!”.

iText offers a multitude of features, from basic ones such as adding text and images to a PDF, to more complex ones like adding bookmarks, watermarks, and securing the PDF. The official iText 8 documentation is a comprehensive resource that covers these features in great detail; it also has several examples that show how to use the library.

In addition, iText provides strong international language support. This includes various fonts and writing systems, including every Western, Middle Eastern, and Asian language.

It’s worth noting that iText prioritizes performance and memory management, which is especially advantageous when dealing with large quantities of data or high-demand environments.

Given its wide range of features and powerful capabilities, iText is a time-tested choice for generating and manipulating PDFs in Java-centric software development. However, careful attention must be given to its licensing. The open-source version of iText is offered under AGPL, which can be restrictive for some projects. Therefore, for commercial use, a commercial license is recommended.

How do I create a PDF document using iText 8?

iText 8 is an open source library for creating and manipulating PDF files in Java. It’s a successor to iText 7, providing more advanced features and capabilities for transforming documents into PDF format.

iText 8 supports the creation and manipulation of PDF documents, and offers various functionalities to enhance your PDF generation requirements. With iText 8 you can generate documents from scratch, or manipulate existing documents, customize the content with font styling, add tables, lists and images, generate barcodes or even forms.

Here are the steps to create a simple PDF document using iText 8 in Java:

  1. Creating a new PdfWriter object, passing the output dest (file path) as an argument.
  2. Then create a PdfDocument with the writer object as argument.
  3. Create the root Document object.
  4. Instantiate a new Paragraph object with some text and add it to the document object.
  5. Finally, close the document object which effectively creates your PDF.

The code snippet:

package org.kodejava.itext;

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

public class CreatePDF {
    public static void main(String[] args) {
        try {
            String dest = "./First-PDF.pdf";
            PdfWriter writer = new PdfWriter(dest);

            // Creating PDF document
            PdfDocument pdfDoc = new PdfDocument(writer);

            // Document is the default root element
            Document document = new Document(pdfDoc);
            String text = "This is the first paragraph of the PDF document created using iText 8.";

            // Creating paragraph
            Paragraph paragraph = new Paragraph(text);

            // Adding paragraph to document 
            document.add(paragraph);

            // Closing the document 
            document.close();
            System.out.println("PDF Created Successfully");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Running this code will give you the First-PDF.pdf file as a result in our current working directory. We can replace the path to an absolute file path to where ever we want to write the output file.

iText version 8 is a powerful tool that, when used correctly, can help automate document generation tasks in your applications, saving a lot of manual effort and ensuring consistency and accuracy. However, it’s important to note that while iText 8 is open-source and free to use under the AGPL license, commercial implementations require purchasing a license.

Maven Dependencies

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-core</artifactId>
    <version>8.0.2</version>
    <type>pom</type>
</dependency>

Maven Central

How do I create an underlined or strike through chunk in iText?

You can use the Chunk‘s setUnderline(float thickness, float yPosition) method to add underline or strike through to a chunk. A negative value to the yPosition create an underline while a positive value will produce a strike through.

package org.kodejava.itextpdf;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class UnderlineStrikeThroughDemo {
    public static void main(String[] args) {
        Document doc = new Document();
        try {
            PdfWriter.getInstance(doc, new FileOutputStream("UnderStrike.pdf"));
            doc.open();

            // Creates a chunk with an underline with 0.1 thickness
            Chunk underline = new Chunk("The quick brown fox ");
            underline.setUnderline(0.1f, -1f);
            doc.add(underline);

            // Creates a strike through chunk with 1 thickness
            Chunk strike = new Chunk("jumps over the lazy dog.");
            strike.setUnderline(1f, 3f);
            doc.add(strike);
        } catch (DocumentException | FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            doc.close();
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13.3</version>
</dependency>

Maven Central

How do I define a font for text object in iText?

We can set font style for text object such as Chunk, Phrase, Paragraph, etc. using the com.itextpdf.text.Font class. We can define the font face, size, style and its color using this class.

package org.kodejava.itextpdf;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class FontDemo {
    public static void main(String[] args) {
        Document doc = new Document();
        try {
            PdfWriter.getInstance(doc, new FileOutputStream("FontDemo.pdf"));
            doc.open();

            // Creates some fonts
            Font largeBold = new Font(Font.FontFamily.COURIER, 32,
                    Font.BOLD);
            Font smallItalic = new Font(Font.FontFamily.HELVETICA, 10,
                    Font.ITALIC);
            Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12,
                    Font.ITALIC | Font.UNDERLINE, BaseColor.RED);

            // Creates chunk, phrase and paragraph with font
            // information.
            Chunk chunk = new Chunk("Hello World", largeBold);
            Phrase phrase =
                    new Phrase("The quick brown fox ", smallItalic);
            Paragraph paragraph =
                    new Paragraph("jumps over the lazy dog", redFont);

            doc.add(chunk);
            doc.add(phrase);
            doc.add(paragraph);
        } catch (DocumentException | FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            doc.close();
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13.3</version>
</dependency>

Maven Central

How do I create super / subscript in iText?

The following example you’ll see how to create a superscript and subscript text in the pdf document using iText. We can use the Chunk‘s class method called setTextRise(). A positive value will create a superscript text while a negative value will create a subscript text.

package org.kodejava.itextpdf;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class SuperSubscriptDemo {
    public static void main(String[] args) {
        Document doc = new Document();
        try {
            PdfWriter.getInstance(doc, new FileOutputStream("SuperSubscript.pdf"));
            doc.open();

            Font small = FontFactory.getFont(FontFactory.HELVETICA, 5, Font.ITALIC);

            // Add some chunks into the doc object.
            doc.add(new Chunk("The quick brown  "));

            Chunk superscript = new Chunk("fox ");
            superscript.setTextRise(5f);
            superscript.setFont(small);
            doc.add(superscript);

            doc.add(new Chunk("jumps over the lazy "));

            Chunk subscript = new Chunk("dog");
            subscript.setTextRise(-5f);
            subscript.setFont(small);
            doc.add(subscript);
        } catch (DocumentException | FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            doc.close();
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13.3</version>
</dependency>

Maven Central