Recursive AI

Add a table of contents to a PDF in C#

OnePDF is a free, open-source PDF library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

Generate a new PDF with a clickable contents page. OnePDF takes the entry text and page numbers from your headings. This works while generating the PDF, not on an existing PDF.

Terminal
dotnet add package RecursiveAI.OnePdf.Layout

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using OnePdf.Layout;
 
LayoutDocument.Compose(doc =>
{
    doc.Page(p => p.Content()
        .TableOfContents());
    doc.Page(p => p.Content()
        .Heading(1).Text("Arrival"));
}).Save("guide.pdf");
Console.WriteLine("Wrote guide.pdf");

Unzip the example, then dotnet run.

The download runs the full program below. If you run just the snippet above, it prints:

Text
Wrote guide.pdf

Open guide.pdf and click “Arrival” on the first page to jump to its heading on page 2.

The full program

The download builds a three-page guide. The contents page uses Roman numbering; the guide starts at page label 1. The program reopens the file and prints each link’s target label.

C#
using OnePdf;
using OnePdf.Layout;
 
LayoutDocument.Compose(doc =>
{
    doc.Title("Field guide").Language("en-US");
    doc.Page(page =>
    {
        page.NumberStyle(NumberingStyle.LowerRoman);
        page.Content().Column(col =>
        {
            col.Spacing(8);
            col.Item().Text("Contents").Bold();
            col.Item().TableOfContents(toc => toc.Levels(1, 2));
        });
    });
    doc.Page(page =>
    {
        page.StartNumber(1);
        page.Content().Column(col =>
        {
            col.Item().Heading(1).Text("Arrival").Bold();
            col.Item().Text("Pick up a trail map at the gate.");
            col.Item().PageBreak();
            col.Item().Heading(1).Text("Trail").Bold();
            col.Item().Heading(2).Text("River crossing");
            col.Item().Text("Follow the signs to the footbridge.");
        });
    });
}).Save("guide.pdf");
 
using var pdf = PdfDocument.Open("guide.pdf");
var links = pdf.Pages[0].Links;
Console.WriteLine($"guide.pdf: {pdf.PageCount} pages, {links.Count} contents links");
foreach (var link in links)
{
    if (link.Destination is not { PageIndex: >= 0 } target)
        throw new InvalidDataException("A contents link has no page target.");
    Console.WriteLine($"Targets page label {pdf.Pages[target.PageIndex].Label}");
}
Text
guide.pdf: 3 pages, 3 contents links
Targets page label 1
Targets page label 2
Targets page label 2

If a heading is missing from the contents page, check that it’s a Heading in the flowing page body and that its level is included by Levels.

Variations

List only top-level headings and turn off the dots. Replace the TableOfContents call in the full program:

C#
col.Item().TableOfContents(toc =>
{
    toc.Levels(1, 1);
    toc.Leader(null);
});
Text
guide.pdf: 3 pages, 2 contents links
Targets page label 1
Targets page label 2

The short answer

To add a clickable table of contents to a PDF you’re generating in C#, place TableOfContents() where the entries should appear and mark the document’s section titles with Heading(level). Then call LayoutDocument.Save. The layout docs say the table “lists the document’s headings, with page numbers, leaders and links.” You don’t need to write an HTML list or count the pages yourself.

Put the contents element on its own page, or include it in the body of a page alongside a “Contents” title. Give that title ordinary text styling if you don’t want it listed. Heading(1) marks a main section and Heading(2) marks a subsection. This uses heading levels, not how large or bold the text looks. By default, levels 1 through 3 appear in the table. For a non-heading item you want to list, the layout package offers TocEntry(title, level); to keep a heading in the document but out of the list, use the inToc argument of Heading.

Call Save on the layout directly. The pagination docs explain that the layout starts with an empty table and recomputes the entries as the table takes up space and pushes content forward. Each entry links to a named destination at its heading. The number in the table is the page’s label, not the zero-based index of its physical page. In the full example the first chapter is on the second physical page, but its entry displays 1.

Can you add a table of contents to an existing PDF?

Not automatically with this layout method. TableOfContents() takes its entries from elements you supply while composing a new document. It doesn’t scan existing pages for text that looks like a heading or turn an existing HTML list into a table of contents. If you still have the source sections, generate the PDF again from those sections and add the contents page during layout.

A contents page is also different from PDF bookmarks. The contents page is part of the document and can be printed. Bookmarks appear in a viewer’s navigation panel. OnePDF Layout provides a separate Bookmark element for that outline; the TableOfContents call here creates the links on the page.

All onepdf recipes