How do I create Chapter in iText?

This brief example show you how to create chapter in the PDF document using iText. To create chapter we use the com.itextpdf.text.Chapter class. We can pass the chapter title and the chapter number as the parameter for the Chapter constructor.

To create a section for the chapter we can use the com.itextpdf.text.Section class. To add a section we call the Chapter.addSection() method of the Chapter object. Let’s look at the example below:

package org.kodejava.example.itextpdf;

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

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

public class PDFChapterDemo {
    public static void main(String[] args) {
        // Creates a new document
        Document document = new Document();
        try {
            // Prepare PDF writer and open the document.
            PdfWriter.getInstance(document,
                    new FileOutputStream("PDFChapterDemo.pdf"));
            document.open();

            // Creates a new Chapter object
            Chapter chapter = new Chapter("Chapter One", 1);

            // Add sections to the chapter
            Section section = chapter.addSection("This is Section 1", 2);
            Paragraph paragraph = new Paragraph("This is the paragraph of the Section 1");
            section.add(paragraph);

            chapter.addSection("This is Section 2", 2);

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

Maven Dependencies

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