Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Table Of Contents in iTextSharp

Tags:

c#

pdf

itext

I need to create a Table Of Contents with page numbers, but I don't know how. Next format:

heading1 ----------------page number  
  subHeading1---------------page number
  subHeading2---------------page number  
heading2-----------------page number  

I read a few articles and didn't understand. In particular, I mean this article, where "Named destinations" and "GoTo actions" I think it is useful for me, but I don't know how to use it in iTextSharp.

In my code, I have got a few "Chapter" and "Section", and I want to take it and create a TOC. I've understood that I need to use PdfPageEventHelper and OnChapter.

like image 635
Naomiss Avatar asked Aug 19 '16 11:08

Naomiss


People also ask

Is iText same as iTextSharp?

iText vs iTextSharp As you can tell from the historical overview, iTextSharp has always been kept in sync with iText, but before version 5, there was a difference in version numbers. Starting with version 7, the name iTextSharp is no longer used in favor of using the name iText.

What is chunk in iTextSharp?

A Chunk is the smallest significant piece of text that you can work with. It's ASP.NET equivalent is the <asp:Label>. As with the Label, you need to be careful how you use Chunks. The following snippet shows how to set the text of a Chunk, then write it to the PDF document 3 times: string path = Server.MapPath("PDFs");

What is the use of iTextSharp?

Itextsharp is an advanced tool library which is used for creating complex pdf repors. itext is used by different techonologies -- Android , . NET, Java and GAE developer use it to enhance their applications with PDF functionality.

Is iTextSharp compatible with .NET core?

The version which works with . NET core is iTextSharp. LGPLv2. Core which is free and what I use in the sample ASP.NET core project.


1 Answers

You've probably implemented this yourself by name, but I made a small example myself for the sake of completeness.

Please take a look at the CreateTOC example. It creates a PDF with some random text:

enter image description here

You can clearly see the titles and the content under the titles. After we have added all our content, we start a new page, and we add a table of contents:

enter image description here

The table of contents is composed by a series of key-value pairs, where the key is the title and the value is the page number. We create this list in a page event:

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;
    }
}

We use this page event like this:

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();
}

First we create an instance of the event and we declare it to the writer:

TOCEvent event = new TOCEvent();
writer.setPageEvent(event);

We mark the titles using setGenericTag():

String title = "This is title " + i;
Chunk c = new Chunk(title, titleFont);
c.setGenericTag(title);
document.add(new Paragraph(c));

Once we've finished adding the content, we get all the entries:

List<SimpleEntry<String, Integer>> entries = event.getTOC();

We loop over this list and compose a Paragraph for every entry:

for (SimpleEntry<String, Integer> entry : entries) {
    p = new Paragraph(entry.getKey());
    p.add(dottedLine);
    p.add(String.valueOf(entry.getValue()));
    document.add(p);
}

No one can argue that this was difficult. The event class takes less than 10 lines of code. Adding support for subheadings will add a handful of lines, but that shouldn't be difficult too. It's a matter of building a tree structure, and introducing some indentation where necessary.

like image 60
Bruno Lowagie Avatar answered Sep 28 '22 02:09

Bruno Lowagie