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

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.