Recursive AI

HTML to PDF with a table of contents in C#

OneRender is a free, open-source HTML and CSS rendering library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

A CSS target-counter() rule fills in each contents entry’s page number.

Terminal
dotnet add package RecursiveAI.OneRender.Pdf

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

C#
using OneRender.Pdf;
File.WriteAllBytes("toc.pdf", HtmlPdf.ToPdf("""
<style>.toc a::after{content:leader('.')
  target-counter(attr(href url),page)}
h2{break-before:page}</style>
<h1>Contents</h1>
<nav class="toc"><a href="#s">Survey</a></nav>
<h2 id="s">Survey</h2>
"""));

Writes toc.pdf. Page 1 lists “Survey” with dots and the number 2; the link jumps to page 2.

Unzip the example, then dotnet run.

The full program

The HTML is inside the program. The first page links to “Survey” on page 2 and “Findings” on page 3.

C#
using OneRender.Pdf;
 
string html = """
    <!doctype html>
    <html lang="en">
    <head>
      <title>Field report</title>
      <style>
        @page { size: A4; margin: 20mm }
        section { break-before: page }
        .toc a::after {
          content: leader('.') target-counter(attr(href url), page);
        }
      </style>
    </head>
    <body>
      <h1>Contents</h1>
      <ul class="toc">
        <li><a href="#survey">Survey</a></li>
        <li><a href="#findings">Findings</a></li>
      </ul>
      <section>
        <h2 id="survey">Survey</h2>
        <p>We recorded water levels at three sites.</p>
      </section>
      <section>
        <h2 id="findings">Findings</h2>
        <p>Water levels fell at two sites.</p>
      </section>
    </body>
    </html>
    """;
 
using var file = File.Create("report.pdf");
var result = HtmlPdf.ToPdf(html, file);
Console.WriteLine($"report.pdf: {result.PageCount} pages");
Text
report.pdf: 3 pages

If a link doesn’t jump to its heading, check that the part after # exactly matches the heading’s id.

Variations

Keep the links and page numbers, but omit the dots. Replace the .toc a::after rule in the full program:

CSS
.toc a::after {
  content: " (page " target-counter(attr(href url), page) ")";
}

The first entry now reads “Survey (page 2).”

The short answer

For a clickable table of contents when converting HTML to PDF in C#, give each target heading an id and write an HTML link such as <a href="#survey">Survey</a> in the contents list. Set the link’s ::after content to leader('.') target-counter(attr(href url), page) and pass the HTML to HtmlPdf.ToPdf. The dots fill the space before the page number. The number comes from the destination’s page in the rendered document, so you don’t have to type it into the HTML.

How do I display a table of contents in a PDF?

Put the list where you want it to appear on paper. Here, the “Contents” heading and list come before the report, and break-before: page starts each section on a fresh page. For a longer report, keep the .toc selector so regular links elsewhere don’t pick up page numbers. The text inside each link is the label shown in the PDF; it can be shorter than the heading as long as the href still matches its id.

The OneRender PDF docs distinguish the link from its number: “target-counter() and target-text() make no link by themselves.” It’s the <a href="#survey"> that becomes a link to the named PDF destination. The contents page is visible in print. OneRender 1.4.0 does not write PDF sidebar bookmarks (also called outlines). Write the contents links yourself; OneRender does not discover headings to build the list.

How do I add page numbers to an HTML table of contents?

target-counter(attr(href url), page) asks for the page counter at the link’s destination. Plain counter(page) would give the page the contents entry sits on. In the full program both entries sit on page 1, but they display 2 and 3. leader('.') fills the remaining line space with a dot pattern; it isn’t part of the page-number calculation. The variation above prints a parenthesized page number instead.

The page number depends on print layout, not heading order. If you add a cover page before the contents or change the print margins, regenerate the whole PDF instead of editing the numbers by hand. The Paged media section of the OneRender architecture guide explain that layout can make up to three further passes to resolve generated numbers. If they don’t settle, OneRender keeps the last values and records a diagnostic. In a long report, keep the HtmlPdfResult from the stream overload, as the full program does, so you can inspect its Diagnostics if the layout needs investigation.

All onerender recipes