A 300-page PDF with no bookmarks is frustrating. A scanned 300-page PDF with no bookmarks is a different problem: it may not contain a usable text layer at all.

Running OCR is only the first step. To turn a printed table of contents into useful PDF navigation, an application must also recover line order, identify entries, infer hierarchy, map printed page numbers to physical PDF pages, and write a valid outline structure back into the file.

We built this pipeline for PDF Bookmarks. This post walks through the engineering decisions behind its browser-based TOC generator, including the parts that turned out to be harder than simply calling an OCR model.

The goal is not to claim that heuristics can understand every PDF. It is to show how a practical, inspectable pipeline can handle a useful range of real documents without sending the PDF to a server or requiring a cloud OCR API.

PDF Bookmarks table of contents generator interface

1. The pipeline: try structure before OCR

The high-level flow looks like this:

Local PDF file | v PDF.js: inspect text layer and existing outline | +--> Existing outline is usable? ----------> Reuse it | +--> Text-based table of contents? --------> Parse entries | +--> Text headings available? -------------> Font + numbering heuristics | +--> Looks like a scan and no result? -----> Local OCR | v TOC lines + coordinates | v Hierarchy + page offset | v Bookmark tree | v PDF outline dictionaries | v Downloaded PDF 

The application is built with React and Vite. The document pipeline uses:

  • PDF.js to inspect PDF text and render pages to canvas.
  • PaddleOCR models exported to ONNX for local text detection and recognition.
  • ONNX Runtime Web to execute the models in the browser.
  • pdf-lib to edit the PDF and serialize the result.

A useful design rule emerged early: use the cheapest source of structure first. If a PDF already has a good outline, do not OCR it. If it has a real text layer and a printed TOC, parse that before rendering images. OCR is the fallback for image-only documents, not the default path for every file.

Our current auto-generation flow tries the existing outline first, then a text-layer TOC, then font-based heading heuristics. If those passes produce no entries and a sample suggests the PDF is scanned, it switches to OCR-based TOC extraction.

2. Distinguishing a scanned PDF from a text PDF

PDF.js can expose a page's text content through getTextContent(). For a normal text PDF, this gives us strings and their transformation data, including coordinates and font information.

For a scan, the page may be visually full of text while the extracted text layer is almost empty.

We use a deliberately simple signal: inspect up to five sample pages and calculate the average number of extracted characters per page. If the average is below 20 characters, we treat the document as likely scanned.

This is a routing heuristic, not a universal classifier. A sparse slide deck or a cover-heavy document can also have very little text. The important point is that this check is cheap and helps us avoid initializing an OCR runtime unnecessarily.

3. OCR must return geometry, not just text

A plain OCR result such as:

Chapter 1 Introduction 1 1.1 Background 3 1.2 Related Work 8 Chapter 2 Methodology 15 

is useful, but it has already lost information. The original page also contained indentation, alignment, columns, and vertical spacing. Those signals help determine which entries are chapters and which are subsections.

Our OCR path therefore keeps each recognized item together with its bounding box and confidence score.

The PDF.js page is rendered to a canvas at a scale of 2.0, then passed to the local OCR pipeline. The result contains text plus box coordinates. We group detections into visual lines by comparing their vertical centers, using a tolerance derived from the median detected text-box height. Items on the same line are sorted by their X coordinate and joined. The first item's X coordinate is retained as the line's indentation signal.

That last detail matters: OCR coordinates are also layout data. They are not just decorations for drawing boxes around recognized words.

Running ONNX models in the browser

The OCR runtime currently tries a PP-OCRv6 ONNX model first and keeps PP-OCRv5 as a fallback. ONNX Runtime Web selects WebGPU when the browser exposes a usable adapter; WebAssembly is the fallback path.

There is one subtle failure mode worth mentioning: a GPU inference session can sometimes be created successfully while returning incorrect numerical results. A successful session initialization does not prove that recognition works.

To catch this, we run a small self-test after creating the detection and recognition sessions. The test renders a known string, 识别测试123, onto a canvas, runs detection and recognition, and checks whether enough expected characters appear in the decoded output. If the provider fails the check, we release that session and try the next provider/model combination. WASM remains the fallback.

When SharedArrayBuffer is available, the WASM path can use multiple threads, capped by the device's reported hardware concurrency and an application limit. Without it, the runtime still works in single-threaded mode.

This adds initialization work, but it is much better than silently returning a page of OCR garbage.

References: PaddleOCR PP-OCRv6 · ONNX Runtime WebGPU guide

4. Finding the table of contents and recovering entries

A scanned book may have a cover, title page, copyright page, preface, and several blank pages before its contents. The TOC is not guaranteed to be on page 2.

For the scanned path, we search the first 16 PDF pages. A candidate page is accepted when it contains a short, standalone TOC heading such as Contents or 目录 and enough TOC-like lines. OCR can confuse Chinese characters—for example, 目 may be recognized as 日 or 曰, and 录 may appear as 錄—so the heading check includes a small amount of fuzzy matching.

The current thresholds are intentionally different:

  • With a TOC heading, at least three title-and-page entries are required.
  • Without a heading, at least eight TOC-like entries are required.

The heading may occupy a page by itself, with entries starting on the next page, so that case is checked too.

Once a start page is found, the parser collects entries across up to 12 pages. A typical entry is a title followed by dot leaders or whitespace and a page number. OCR is imperfect, so the parser also handles a few common failure cases:

  • It cleans stray punctuation and small OCR fragments around titles.
  • It can keep clearly structured chapter headings even when OCR loses their page number.
  • Missing page numbers can be filled from a nearby known entry.
  • A page-number sequence that suddenly moves backwards is treated as a likely OCR error and clamped to the previous maximum.

These repairs are heuristics. They reduce common errors, but they cannot reconstruct information that is absent or badly corrupted in the scan.

5. Reconstructing the hierarchy

A flat list of titles is not a useful table of contents. We need to infer a tree:

Chapter 1 Introduction 1.1 Background 1.2 Related Work 1.2.1 Earlier Systems Chapter 2 Methodology 2.1 Data Collection 

For scanned TOCs, we first use the X coordinates of OCR lines. We sort the indentation positions and split them into clusters when the gap is larger than a tolerance derived from the line height. Two to five meaningful clusters are treated as plausible hierarchy levels. Very small clusters are usually noise—perhaps a handwritten note or a skewed detection box—so they can be discarded, and isolated entries are assigned to the nearest remaining cluster.

For text-layer TOCs, the same idea uses extracted text positions and a tolerance derived from the median font size.

If indentation is not reliable, we fall back to heading patterns. These include common forms such as:

  • Chinese: 第X章, 第X节, 第X部分
  • English: Chapter 2, Section 2
  • Numbered headings: 1., 1.2, 1.2.3
  • Lettered headings: A., a.
  • Parenthesized numbering: (一), (2)

We also compare entries with the same numbering shape. If most 1.2-style entries are at one level but one OCR box drifts horizontally, the majority level can correct that outlier. A final adjustment handles documents where parts and chapters share the same visual level.

After assigning levels, a stack builds the nested tree. When the next entry is at the same or a higher level, we pop until we find the correct parent, then append the new node.

This is intentionally a hybrid approach: geometry handles layout, patterns provide a fallback, and the tree remains editable by the user.

6. The page-offset problem

This is one of the most important details in a real book.

The printed page number in a table of contents is not necessarily the physical page index in the PDF. A book may have a cover, title page, copyright page, preface, and contents pages before printed page 1.

We use:

PDF physical page = printed page number + offset offset = physical page - printed page number 

For a text-based TOC, we take a few early entries and search for their titles in the pages after the TOC. If an entry printed as page 1 is found on physical PDF page 14, the estimated offset is 13.

For the OCR path, matching a title alone can be misleading: a chapter title may appear on a divider page before the actual chapter starts. So we prefer a second signal.

After the TOC, we inspect up to six pages and look only at the top and bottom 12% of each page. OCR boxes in those regions are checked for common printed page-number forms such as 12, Page 12, 第 12 页, or - 12 -. Each valid observation votes for an offset:

const offset = physicalPageNumber - printedPageNumber; votes[offset] = (votes[offset] || 0) + 1; 

The most common offset wins, within a conservative range. If there are no usable printed-number votes, we fall back to matching one of the first few TOC titles against body pages. If neither signal works, the current fallback is zero.

This is still a best-effort estimate. Roman-numeral front matter, unnumbered pages, unusual page-number placement, and OCR errors can defeat it. That is why we expose the generated tree for inspection instead of pretending page mapping is infallible.

7. Writing real PDF bookmarks

A PDF's clickable navigation tree is not the same thing as a printed contents page. In the PDF format, it is represented by the document's outline structure.

The high-level pdf-lib API is useful for loading, editing, and saving documents, but it does not provide a high-level bookmark-tree builder. We use its lower-level document context to create the outline dictionaries directly.

At a high level, the outline root points to the first and last top-level items. Each item stores:

  • Title: the bookmark label.
  • Parent: its parent outline node.
  • Dest: a destination pointing to the target page.
  • Prev and Next: links between sibling items.
  • First and Last: links to child items.
  • Count: the number of descendants represented by the node.

The destination references the actual PDF page object, rather than storing a page number as plain text. Bookmark titles are encoded as Unicode PDF strings so Chinese and other non-ASCII chapter names survive serialization.

We attach the outline root to the catalog's /Outlines entry and set /PageMode /UseOutlines to request that compatible readers open with the bookmark panel visible. Reader behavior varies: Chrome's built-in PDF viewer may not automatically open that panel, even though the outline is present and can be opened manually.

The final file is serialized with pdf-lib and downloaded in the browser. The separate “Insert TOC page” feature can also turn the bookmark tree into a visible, printable page with clickable links.

Reference: pdf-lib PDFDocument API

8. Keep the result editable

Automation should save time, not remove control.

The generated outline opens in a tree editor where users can rename entries, correct page numbers, delete false positives, reorder items, and drag entries into or out of parent nodes. A stack-based tree is convenient for generation, but a human-friendly editing model is just as important for correcting imperfect scans.

There is also a manual import path. Users can paste TOC text and set an explicit page offset. The parser recognizes numbering, chapter labels, and indentation, then previews the resulting hierarchy before import. This is useful when a publisher provides a clean TOC as text or when OCR is not reliable enough.

9. Privacy and trade-offs

The PDF parsing, rendering, OCR inference, bookmark generation, and PDF writing in this workflow run in the browser. The PDF does not need to be uploaded to our application server for these operations. The OCR model files are downloaded when first needed and may then be reused from the browser cache.

The site does send basic feature-usage analytics, such as which tool was opened and whether an operation succeeded. Those events do not contain the PDF bytes or extracted document text.

There are trade-offs:

  • The first OCR run needs to download model assets.
  • WebGPU availability varies by browser, operating system, and device; WASM is the fallback.
  • Large PDFs can put pressure on browser memory.
  • Low-resolution, skewed, multi-column, or heavily damaged scans are harder to parse.
  • Printed page numbers may be missing, Roman-numeral, or placed somewhere our header/footer heuristic does not inspect.
  • Handwriting is not the target use case; printed text is a better fit.

The OCR path currently searches a bounded range near the beginning of the document for the contents page. A book whose TOC starts much later may need manual import or a future configurable search range.

10. What we learned

Three lessons shaped this implementation:

  1. OCR is not document understanding. Text without coordinates loses the layout clues needed to reconstruct hierarchy.
  2. Page numbers are semantic data. A correct title attached to the wrong physical page is still a broken bookmark.
  3. Deterministic paths should come first. Existing outlines, text layers, and font metadata are cheaper and often more reliable than OCR. Use OCR when the document actually needs it.

If you want to try the workflow, the PDF table of contents generator can create editable bookmarks from text-based PDFs and scanned contents pages. It runs in the browser, requires no API key, and does not require an account.

Further reading