Chapter Example
iText is a free and open source library for creating and manipulating
PDF documents in Java. The following example shows creating a PDF document with
chapter, sections and subsections.
package com.bethecoder.tutorials.itext.tests;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Section;
import com.itextpdf.text.pdf.PdfWriter;
public class ChapterExample {
/**
* @param args
* @throws DocumentException
* @throws FileNotFoundException
*/
public static void main ( String [] args ) throws FileNotFoundException, DocumentException {
Document document = new Document ( PageSize.A4 ) ;
PdfWriter.getInstance ( document, new FileOutputStream ( "test21.pdf" )) ;
//Open the document before adding any content
document.open () ;
Paragraph paragraph = new Paragraph ( "BE THE CODER" ) ;
document.add ( paragraph ) ;
Chapter chapter1 = new Chapter ( "Chapte 1" , 1 ) ; //Creates a new page
Section section11 = chapter1.addSection ( "Section 11" ) ;
section11.add ( new Paragraph ( "Some text in Section 11" )) ;
Section section12 = chapter1.addSection ( "Section 12" ) ;
Section section13 = chapter1.addSection ( "Section 13" ) ;
Section section111 = section11.addSection ( "Section 111" ) ;
Section section121 = section12.addSection ( "Section 121" ) ;
Section section131 = section13.addSection ( "Section 131" ) ;
section131.addSection ( "Section 1311" ) ;
section131.addSection ( "Section 1312" ) .add ( new Paragraph ( "Some text in Section 1312" )) ;
document.add ( chapter1 ) ;
//Close the document
document.close () ;
}
}
It gives the following output,