Creating Table of Contents using events

Tags: page eventstable of contentsPdfOutlineiText 5link annotation

Example written in answer to the question How can I add titles of chapters in ColumnText?

Files: 
/**
 * Example written by Bruno Lowagie in answer to:
 * http://stackoverflow.com/questions/29092738/itext-chapter-title-and-columntext
 */
package sandbox.events;
 
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfAction;
import com.itextpdf.text.pdf.PdfDestination;
import com.itextpdf.text.pdf.PdfOutline;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import sandbox.WrapToTest;
 
@WrapToTest
public class CreateTOCinColumn {
 
    public static final String DEST = "results/events/columns_with_toc.pdf";
    public static final Rectangle[] COLUMNS = {
        new Rectangle(36, 36, 192, 806),
        new Rectangle(204, 36, 348, 806),
        new Rectangle(360, 36, 504, 806)
    };
 
    public class TOCEntry {
        protected PdfAction action;
        protected String title;
    }
 
    public class TOCCreation extends PdfPageEventHelper {
 
        protected PdfOutline root;
        protected List<TOCEntry> toc = new ArrayList<TOCEntry>();
 
        public TOCCreation() {
        }
 
        public void setRoot(PdfOutline root) {
            this.root = root;
        }
 
        public List<TOCEntry> getToc() {
            return toc;
        }
 
        @Override
        public void onGenericTag(PdfWriter writer, Document document, Rectangle rect, String text) {
            PdfDestination dest = new PdfDestination(PdfDestination.XYZ, rect.getLeft(), rect.getTop(), 0);
            new PdfOutline(root, dest, text);
            TOCEntry entry = new TOCEntry();
            entry.action = PdfAction.gotoLocalPage(writer.getPageNumber(), dest, writer);
            entry.title = text;
            toc.add(entry);
        }
    }
 
    public static void main(String[] args) throws IOException, DocumentException {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new CreateTOCinColumn().createPdf(DEST);
    }
    public void createPdf(String dest) throws IOException, DocumentException {
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
        TOCCreation event = new TOCCreation();
        writer.setPageEvent(event);
        document.open();
        event.setRoot(writer.getRootOutline());
        ColumnText ct = new ColumnText(writer.getDirectContent());
        int start;
        int end;
        for (int i = 0; i <= 20; ) {
            start = (i * 10) + 1;
            i++;
            end = i * 10;
            String title = String.format("Numbers from %s to %s", start, end);
            Chunk c = new Chunk(title);
            c.setGenericTag(title);
            ct.addElement(c);
            ct.addElement(createTable(start, end));
        }
        int column = 0;
        do {
            if (column == 3) {
                document.newPage();
                column = 0;
            }
            ct.setSimpleColumn(COLUMNS[column++]);
        } while (ColumnText.hasMoreText(ct.go()));
        document.newPage();
        for (TOCEntry entry : event.getToc()) {
            Chunk c = new Chunk(entry.title);
            c.setAction(entry.action);
            document.add(new Paragraph(c));
        }
        document.close();
    }
 
    public PdfPTable createTable(int start, int end) throws IOException {
        PdfPTable table = new PdfPTable(2);
        for (int i = start; i <= end; i++) {
            table.addCell(String.valueOf(i));
            table.addCell("Test");
        }
        return table;
    }
}
/*
 * This example is written by Bruno Lowagie in answer to:
 * http://stackoverflow.com/questions/39037594
 */
package sandbox.events;
 
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Font.FontFamily;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.draw.DottedLineSeparator;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.List;
import sandbox.WrapToTest;
 
/**
 *
 * @author Bruno Lowagie (iText Software)
 */
@WrapToTest
public class CreateTOC {
 
    public static final String DEST = "results/events/create_toc.pdf";
    public final Font titleFont = new Font(FontFamily.HELVETICA, 16);
 
    public class TOCEvent extends PdfPageEventHelper {
 
        protected List<SimpleEntry<String, Integer>> toc = new ArrayList<>();
 
        @Override
        public void onGenericTag(PdfWriter writer, Document document, Rectangle rect, String text) {
            toc.add(new SimpleEntry(text, writer.getPageNumber()));
        }
 
        public List getTOC() {
            return toc;
        }
    }
 
 
    public static void main(String[] args) throws IOException, DocumentException {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new CreateTOC().createPdf(DEST);
    }
 
    public void createPdf(String dest) throws IOException, DocumentException {
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
        TOCEvent event = new TOCEvent();
        writer.setPageEvent(event);
        document.open();
        for (int i = 0; i < 10; i++) {
            String title = "This is title " + i;
            Chunk c = new Chunk(title, titleFont);
            c.setGenericTag(title);
            document.add(new Paragraph(c));
            for (int j = 0; j < 50; j++) {
                document.add(new Paragraph("Line " + j + " of title " + i));
            }
        }
        document.newPage();
        document.add(new Paragraph("Table of Contents", titleFont));
        Chunk dottedLine = new Chunk(new DottedLineSeparator());
        List<SimpleEntry<String, Integer>> entries = event.getTOC();
        Paragraph p;
        for (SimpleEntry<String, Integer> entry : entries) {
            p = new Paragraph(entry.getKey());
            p.add(dottedLine);
            p.add(String.valueOf(entry.getValue()));
            document.add(p);
        }
        document.close();
    }
}
/*
 * This example is written by Bruno Lowagie in answer to:
 * http://stackoverflow.com/questions/39037594
 */
package sandbox.events;
 
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Font.FontFamily;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfAction;
import com.itextpdf.text.pdf.PdfDestination;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.draw.DottedLineSeparator;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.List;
import sandbox.WrapToTest;
 
/**
 *
 * @author Bruno Lowagie (iText Software)
 */
@WrapToTest
public class CreateTOC2 {
 
    public static final String DEST = "results/events/create_toc2.pdf";
    public final Font titleFont = new Font(FontFamily.HELVETICA, 16);
 
    public class TOCEvent extends PdfPageEventHelper {
 
    	protected int counter = 0;
        protected List<SimpleEntry<String, SimpleEntry<String, Integer>>> toc = new ArrayList<>();
 
        @Override
        public void onGenericTag(PdfWriter writer, Document document, Rectangle rect, String text) {
        	String name = "dest" + (counter++);
        	int page = writer.getPageNumber();
            toc.add(new SimpleEntry<String, SimpleEntry<String, Integer>>(text, new SimpleEntry<String, Integer>(name, page)));
            writer.addNamedDestination(name, page, new PdfDestination(PdfDestination.FITH, rect.getTop()));
        }
 
        public List<SimpleEntry<String, SimpleEntry<String, Integer>>> getTOC() {
            return toc;
        }
    }
 
 
    public static void main(String[] args) throws IOException, DocumentException {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new CreateTOC2().createPdf(DEST);
    }
 
    public void createPdf(String dest) throws IOException, DocumentException {
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
        TOCEvent event = new TOCEvent();
        writer.setPageEvent(event);
        document.open();
        for (int i = 0; i < 10; i++) {
            String title = "This is title " + i;
            Chunk c = new Chunk(title, titleFont);
            c.setGenericTag(title);
            document.add(new Paragraph(c));
            for (int j = 0; j < 50; j++) {
                document.add(new Paragraph("Line " + j + " of title " + i));
            }
        }
        document.newPage();
        document.add(new Paragraph("Table of Contents", titleFont));
        Chunk dottedLine = new Chunk(new DottedLineSeparator());
        List<SimpleEntry<String, SimpleEntry<String, Integer>>> entries = event.getTOC();
        Paragraph p;
        for (SimpleEntry<String, SimpleEntry<String, Integer>> entry : entries) {
        	Chunk chunk = new Chunk(entry.getKey());
            SimpleEntry<String, Integer> value = entry.getValue();
        	chunk.setAction(PdfAction.gotoLocalPage(value.getKey(), false));
            p = new Paragraph(chunk);
            p.add(dottedLine);
            chunk = new Chunk(String.valueOf(value.getValue()));
        	chunk.setAction(PdfAction.gotoLocalPage(value.getKey(), false));
            p.add(chunk);
            document.add(p);
        }
        document.close();
    }
}
File nameRaw URLUpdated
CreateTOCinColumn.javaCreateTOCinColumn.java2015-10-25 3:23 am
CreateTOC.javaCreateTOC.java2016-08-19 6:13 pm
CreateTOC2.javaCreateTOC2.java2016-08-23 3:26 pm
Results: 
File nameRaw URLUpdated
cmp_columns_with_toc.pdfcmp_columns_with_toc.pdf2015-10-25 3:24 am
cmp_create_toc.pdfcmp_create_toc.pdf2016-08-19 6:15 pm
cmp_create_toc2.pdfcmp_create_toc2.pdf2016-08-23 3:27 pm