Tech and Media Labs
This site uses cookies to improve the user experience.




Java IText: Chapter + Section

Jakob Jenkov
Last update: 2014-05-24

You can add chapters and sections to a PDF document using IText. Chapters are represented by the class com.itextpdf.text.Chapter. Sections are represented by the class com.itextpdf.text.Section.

Here is a simple code example:

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

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

public class ChapterSectionExample {

  public static void main(String[] args) {

    Document document = new Document();

    try {
      PdfWriter.getInstance(document,
            new FileOutputStream("ChapterSection.pdf"));

      document.open();

      Paragraph paragraph = new Paragraph();
      paragraph.add(new Phrase("This is a chapter."));

      
          Chapter chapter = new Chapter(paragraph, 1);

          Section section1 = chapter.addSection("This is section 1", 2);
          Section section2 = chapter.addSection("This is section 2", 2);

          document.add(chapter);
      

      document.close();

    } catch (DocumentException e) {
      e.printStackTrace();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }

  }
}

Here is what the generated document looks like:

An IText Chapter and Section example
An IText Chapter and Section example

Jakob Jenkov




Copyright  Jenkov Aps
Close TOC