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 set Paragraph indentation in iText?

To set paragraph indentation in the iText Paragraph object we can use the setFirstLineIndent(), setIndentationLeft() and setIndentationRight(). These methods accept a float value as a parameter.

The setFirstLineIndent() method set the first line indentation of a paragraph, while the setIndentationLeft() and setIndentationRight() methods set the left and the right indent of the paragraph. Let see an example below:

package org.kodejava.itextpdf;

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

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

public class ParagraphIndentationDemo {
    private static final String CONTENT = """
            Lorem ipsum dolor sit amet, consectetur adipisicing elit, \
            sed do eiusmod tempor incididunt ut labore et dolore magna \
            aliqua. Ut enim ad minim veniam, quis nostrud exercitation \
            ullamco laboris nisi ut aliquip ex ea commodo consequat. \
            Duis aute irure dolor in  reprehenderit in voluptate velit \
            esse cillum dolore eu fugiat nulla pariatur. Excepteur sint \
            occaecat cupidatat non proident, sunt in culpa qui officia \
            deserunt mollit anim id est laborum.
            """;

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

            Paragraph paragraph = new Paragraph();
            paragraph.add(new Chunk(ParagraphIndentationDemo.CONTENT));

            // Set paragraph's first line indent
            paragraph.setFirstLineIndent(75);

            // Set paragraph's left side indent
            paragraph.setIndentationLeft(50);

            // Set paragraph's right side indent
            paragraph.setIndentationRight(25);
            document.add(paragraph);
        } catch (DocumentException | FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
    }
}

Maven Dependencies

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

Maven Central

How do I set Paragraph alignment in iText?

To set the alignment of a paragraph object we can use the Paragraph.setAlignment() method. We can pass constants such as Paragraph.ALIGN_LEFT, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_RIGHTto the setAlignment() method.

package org.kodejava.itextpdf;

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

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

public class ParagraphAlignment {
    private static final String CONTENT = """
            Lorem ipsum dolor sit amet, consectetur adipisicing elit, \
            sed do eiusmod tempor incididunt ut labore et dolore magna \
            aliqua. Ut enim ad minim veniam, quis nostrud exercitation \
            ullamco laboris nisi ut aliquip ex ea commodo consequat. \
            Duis aute irure dolor in  reprehenderit in voluptate velit \
            esse cillum dolore eu fugiat nulla pariatur. Excepteur sint \
            occaecat cupidatat non proident, sunt in culpa qui officia \
            deserunt mollit anim id est laborum.
            """;

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

            // Creates a check for the paragraphs contents
            Chunk chunk = new Chunk(ParagraphAlignment.CONTENT);

            // Creates paragraphs and set the alignment of the paragraph.
            // We use the Paragraph.ALIGN_LEFT, Paragraph.ALIGN_CENTER
            // and Paragraph.ALIGN_RIGHT
            Paragraph para1 = new Paragraph(chunk);
            para1.setAlignment(Paragraph.ALIGN_LEFT);
            para1.setSpacingAfter(50);
            document.add(para1);

            Paragraph para2 = new Paragraph(chunk);
            para2.setAlignment(Paragraph.ALIGN_CENTER);
            para2.setSpacingAfter(50);
            document.add(para2);

            Paragraph para3 = new Paragraph(chunk);
            para3.setAlignment(Paragraph.ALIGN_RIGHT);
            document.add(para3);

            document.close();
        } catch (DocumentException | FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

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

Maven Central

How do I set Paragraph line space in iText?

To set the line spacing of a paragraph in iText can be done by passing the line space / leading argument in the Paragraph constructor. In the example below we set the line space to 32. We can also set the space between paragraph by calling the setSpacingBefore() and setSpacingAfter() methods of this object.

package org.kodejava.itextpdf;

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

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

public class ParagraphLineSpaceDemo {
    public static void main(String[] args) {
        Document doc = new Document();

        try {
            FileOutputStream fos = new FileOutputStream("ParagraphLineSpace.pdf");
            PdfWriter.getInstance(doc, fos);
            doc.open();

            String content = "The quick brown fox jumps over the lazy dog";

            // Setting paragraph line spacing to 32
            Paragraph para1 = new Paragraph(32);

            // Setting the space before and after the paragraph
            para1.setSpacingBefore(50);
            para1.setSpacingAfter(50);
            for (int i = 0; i < 10; i++) {
                para1.add(new Chunk(content));
            }
            doc.add(para1);

            Paragraph para2 = new Paragraph();
            for (int i = 0; i < 10; i++) {
                para2.add(new Chunk(content));
            }
            doc.add(para2);

            doc.close();
        } catch (DocumentException | FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

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

Maven Central