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.itextpdf;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class ChapterDemo {
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("ChapterDemo.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.13.3</version>
</dependency>