/*
 * modified from blowagie's 'iText Tutorial'
 *      Example: java  com.lowagie.examples.objects.bookmarks.ChapterSection
 */

import java.awt.Color;
import java.io.FileOutputStream;

import com.lowagie.text.*;
import com.lowagie.text.pdf.PdfWriter;

public class OrphanSectionTitle {

	/**
	 *            no arguments needed
	 */
    public static void main(String[] args) {
        
        // step 1: creation of a document-object
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        try {
            // step 2: we create a writer that listens to the document
            PdfWriter writer=PdfWriter.getInstance(document, new FileOutputStream("ChapterSection.pdf"));
            // step 3: we open the document
            writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
            document.open();
            // step 4: we add content to the document
            // we define some fonts
            Font chapterFont = FontFactory.getFont(FontFactory.HELVETICA, 24, Font.NORMAL, new Color(255, 0, 0));
            Font sectionFont = FontFactory.getFont(FontFactory.HELVETICA, 20, Font.NORMAL, new Color(0, 0, 255));
            // we create some paragraphs
            Paragraph blahblah = new Paragraph("blah blah blah blah blah blah blaah blah blah blah blah blah blah" +
                                               " blah blah blah blah blah blah blah blah blah blah blah blah blah" +
                                               " blah blah blah blah blah blah blah blah blah blah blah blah blah" +
                                               " blah blah blah blah blah blah blah blah blah blah blah blah blah" +
                                               " blah blah blah blah blah blah blah blah blah blah blah blah");

            Paragraph cTitle = new Paragraph("This is chapter 1" , chapterFont);
            Chapter chapter = new Chapter(cTitle, 1);
            // add 6 sections
            for (int j = 1; j < 7; j++) {
                Paragraph sTitle = new Paragraph("This is section " + j, sectionFont);
                 if ( j==6) // produce a widow line
                     sTitle = new Paragraph("This is section " + j+
                                            " foobar foobar foobar foobar foobar foobar foobar " + 
                                            " foobar foobar foobar foobar foobar foobar"
                                            , sectionFont);
                sTitle.setKeepTogether(true); //

                Section section = chapter.addSection(sTitle, 1);
                section.add(blahblah);
            }
            document.add(chapter);
        }
        catch(Exception de) {
            de.printStackTrace();
        }
        // step 5: we close the document
	document.close();
    }
}