Inferensys

Prompt

Table of Contents Hyperlink Extraction Prompt Template

A practical prompt playbook for extracting interactive Table of Contents hyperlink destinations from digital PDFs in production AI workflows.
Elegant overhead shot of a polished wooden communal table in a sun-drenched WeWork lounge, laptops and tablets displaying AI workflow dashboards, plants and pendant lights in background.
PROMPT PLAYBOOK

When to Use This Prompt

Identify the right conditions for deploying the Table of Contents hyperlink extraction prompt in a document processing pipeline.

This prompt is designed for document platform engineers who need to extract and validate interactive Table of Contents (TOC) links from digital PDFs. The primary job-to-be-done is not extracting the static text of a TOC page, but rather parsing the underlying link annotations—the clickable entries that point to internal pages or external URLs. Use this prompt when your pipeline must programmatically verify that every TOC entry resolves to a correct destination, build a navigation map for a document viewer, or detect broken references before a document is served to end users. The ideal user is an engineer who has already used a PDF parsing library like PyMuPDF or pdfplumber to extract raw link annotation data and now needs an LLM to normalize, validate, and structure that data into a consistent schema.

This prompt is not a substitute for a PDF parsing library. It does not read raw PDF bytes or perform OCR on scanned images. It assumes you have already extracted the raw link annotations and their associated display text. Do not use this prompt for static TOC text extraction from documents without interactive links, for generating a TOC from heading text, or for resolving cross-references in the body of a document. Those tasks require different prompt templates, such as the Table of Contents Parsing Prompt Template or the Cross-Reference Resolution Prompt Template. Additionally, this prompt is not designed for documents where the TOC is a scanned image; in that case, you need an OCR-aware processing pipeline before link extraction can occur.

Before integrating this prompt into a production system, confirm that your PDF parsing step reliably extracts both the link rectangle coordinates and the displayed text for each TOC entry. Common failure modes upstream include missing link annotations for entries that appear visually clickable, misaligned bounding boxes that capture adjacent text, and external URLs that are incorrectly parsed as internal page references. If your raw extraction data is noisy, add a pre-processing validation step to filter out entries with empty text or null destinations before sending data to the model. For high-stakes document workflows—such as legal filings or regulatory submissions—always include a human review step for entries flagged as broken or ambiguous by the model's output.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not. Understand the operational boundaries before embedding this extraction step in a document pipeline.

01

Good Fit: Interactive Digital PDFs

Use when: The source PDF contains an interactive table of contents with embedded hyperlinks (e.g., generated by Word, Adobe Acrobat, or LaTeX with hyperref). Why it works: The prompt extracts both the displayed text and the underlying link destination, enabling navigation tree construction and clickable TOC replication in a viewer.

02

Bad Fit: Scanned or Flat Image PDFs

Avoid when: The document is a scanned image or a flat PDF without internal link annotations. Why it fails: The model cannot extract hyperlinks that do not exist in the file structure. Guardrail: Route these documents to an OCR-aware TOC parsing prompt that reconstructs the outline from visual heading patterns and page numbers instead.

03

Required Inputs

Must provide: The raw PDF file with accessible link annotations, or a pre-extracted list of TOC entries with their associated link objects. Guardrail: If your PDF parsing library strips link destinations during text extraction, you must preserve the annotation layer separately. Do not pass only the visible text and expect the model to invent destinations.

04

Operational Risk: Broken Internal Links

What to watch: Links that point to missing pages, deleted sections, or external URLs misidentified as internal document references. Guardrail: Implement a post-extraction validation step that verifies each destination exists within the document's page range. Flag external URLs for review and separate them from internal navigation links in the output schema.

05

Operational Risk: Mismatched Link Text and Destination

What to watch: The displayed TOC text says 'Section 4.2' but the hyperlink points to 'Section 4.3' due to authoring errors or version drift. Guardrail: Add an eval check that compares the extracted link text against the destination section's actual title. Surface mismatches as warnings rather than silently trusting either field.

06

Pipeline Dependency: Upstream Link Extraction

What to watch: This prompt depends on a reliable upstream step that extracts link annotations from the PDF. If that step fails silently, the prompt receives incomplete data. Guardrail: Validate the input payload before calling the model. If the expected link count is zero or anomalously low, abort and route to a fallback TOC reconstruction prompt that works from visual layout alone.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A copy-ready prompt for extracting and validating TOC hyperlink destinations from a digital PDF.

This prompt template is designed to be pasted directly into your AI harness. It instructs the model to process a structured representation of a PDF's Table of Contents, extracting both the displayed text and the underlying hyperlink destination for each entry. The core job is to pair the human-readable label with its machine-actionable target, which is essential for building reliable navigation, validating document structure, and automating link integrity checks in a document platform.

code
You are an expert document structure analyst. Your task is to process a provided Table of Contents (TOC) data structure from a digital PDF and extract the hyperlink destinations.

**INPUT DATA:**
[TOC_DATA]

**INSTRUCTIONS:**
1.  Parse the [TOC_DATA], which is a JSON array of TOC entries. Each entry has a `title` (the displayed text) and an `action` (the hyperlink's internal destination or an external URL).
2.  For each entry, extract the `title` and the `destination` from the `action` object. The destination could be a page number, a named destination, an external URL, or null if no link is present.
3.  Classify each link as `internal` (points to a page or named destination within the document) or `external` (a URL to an outside resource).
4.  Flag any entry where the `title` text and the destination's target title are mismatched, or where the link is broken or missing.

**OUTPUT_SCHEMA:**
Return a valid JSON object with a single key `toc_links`. The value should be an array of objects, each with the following fields:
- `entry_title`: (string) The displayed text of the TOC entry.
- `link_type`: (string) One of `internal`, `external`, or `none`.
- `destination`: (string or null) The extracted destination value.
- `flags`: (array of strings) A list of issues like `broken_link`, `external_url`, or `title_mismatch`. Empty array if no issues.

**CONSTRAINTS:**
- Do not invent destinations. If the `action` is missing or malformed, set `destination` to `null` and `link_type` to `none`.
- If a link is an external URL, always set the `flags` array to include `external_url`.
- Ensure the output is strictly valid JSON.

To adapt this template, replace the [TOC_DATA] placeholder with the parsed TOC object from your PDF processing library. The prompt's strength lies in its explicit output schema and constraints, which make the output directly usable by downstream validation code. The classification and flagging instructions turn the model into a first-pass data quality filter, catching common issues like external URLs masquerading as internal references before they break your application's navigation logic. After generation, always validate the JSON structure against the defined schema and run a reconciliation script to ensure no entries from the input were dropped in the output.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Table of Contents hyperlink extraction prompt. Each placeholder must be populated before the prompt is sent to the model. Validation notes describe how to confirm the input is well-formed before execution.

PlaceholderPurposeExampleValidation Notes

[TOC_PAGE_RANGE]

Specifies which pages contain the interactive TOC to process

pages 2-4

Must be a valid page range string. Parse check: confirm range is within document page count. Null not allowed.

[DOCUMENT_TEXT]

Full extracted text of the document for context matching

Full plain text from PDF extraction

Must be non-empty string. Schema check: min length 1 character. Warn if text appears garbled or contains only non-printable characters.

[LINK_ANNOTATIONS]

Raw PDF link annotation data with destinations and display text

JSON array of link objects with rect, dest, and text fields

Must be valid JSON array. Parse check: each element requires dest and text fields. Null allowed only if PDF has no links.

[PAGE_LABEL_MAP]

Mapping from PDF page indices to document page numbers

{"0": "i", "1": "ii", "5": "1"}

Must be valid JSON object. Schema check: keys are string integers, values are strings. Required for roman numeral front matter handling.

[DESTINATION_TYPE_FILTER]

Which link destination types to include in output

["page", "named_dest", "external_url"]

Must be array of allowed values: page, named_dest, external_url, launch_action, unknown. Parse check: no invalid types present.

[OUTPUT_SCHEMA]

Expected JSON schema for each extracted TOC entry

{"display_text": string, "destination": string, "dest_type": string, "page_label": string, "confidence": number}

Must be valid JSON Schema object. Schema check: required fields include display_text, destination, dest_type. Confidence field must be number 0-1.

[MAX_ENTRIES]

Upper bound on TOC entries to extract

200

Must be positive integer. Parse check: value between 1 and 1000. Prevents runaway extraction on malformed documents with thousands of link annotations.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Table of Contents hyperlink extraction prompt into a reliable document processing pipeline.

This prompt is designed to be called once per document after a digital PDF has been parsed to extract its internal link annotations. The implementation harness must supply the model with a structured representation of the TOC page's interactive links—specifically, the displayed text and the raw destination target for each link. Do not pass raw PDF bytes or page images to this prompt; the upstream PDF parser (such as pdfplumber, PyMuPDF, or a cloud document AI service) is responsible for extracting the link annotations and normalizing them into the [TOC_LINK_LIST] input format. The model's job is to reason about mismatches, classify link types, and produce a clean, validated TOC structure—not to perform OCR or layout analysis.

Wire this prompt into your application as a post-extraction validation and normalization step. The typical call flow is: (1) parse the PDF to extract all link annotations on pages identified as the table of contents; (2) assemble each link as a JSON object with display_text and raw_destination fields; (3) pass the array as [TOC_LINK_LIST] to the prompt; (4) validate the model's JSON output against the expected schema before ingestion. Schema validation should check that every entry has a non-empty display_text, a destination_type from the allowed enum (internal_page, external_url, named_destination, broken), and a confidence score between 0 and 1. Reject or quarantine outputs that fail schema validation and retry with a more explicit [CONSTRAINTS] block rather than silently accepting malformed entries.

For production deployments, add a post-processing step that cross-references extracted internal page links against the PDF's actual page count. If a link claims to point to page 47 but the document has only 32 pages, flag it as broken with a resolution_note explaining the mismatch. External URLs should be checked with a HEAD request (where safe and permitted) to distinguish live links from dead references, but avoid blocking the pipeline on network calls—log URL reachability asynchronously and update the TOC metadata later. Log every extraction run with the document identifier, model version, prompt version, and validation pass/fail status so that regressions can be traced to prompt changes or PDF parser updates. For high-stakes document workflows, route entries with confidence below 0.85 or destination_type: broken to a human review queue rather than silently ingesting them into navigation systems.

Model choice matters here. This task requires instruction-following precision and structured output reliability more than creative reasoning. Use a model with strong JSON mode or structured output support (such as GPT-4o with response_format, Claude 3.5 Sonnet with tool-use-shaped output, or Gemini 1.5 Pro with controlled generation). Avoid models that struggle with long-context instruction adherence or that frequently drop fields from structured outputs. Set temperature to 0 or near-zero to minimize variation in link classification. If your PDF parser produces hundreds of TOC links, consider batching the link list into groups of 50–75 entries per call to stay within reliable context windows and reduce the risk of the model truncating or summarizing the output. Each batch should be processed independently and the results merged with a deduplication check on display_text to catch overlaps.

The primary failure mode in production is not the model misclassifying a link type—it is the upstream PDF parser failing to extract link annotations correctly. If the [TOC_LINK_LIST] contains garbled text or missing destinations, the model can flag issues but cannot recover the original data. Build a pre-validation step that checks for empty display_text fields, destinations that are raw byte offsets instead of human-readable targets, and link lists shorter than expected for the document's length. If pre-validation fails, log the document for parser review and do not call the prompt. The second most common failure is the model inventing destinations for broken links rather than marking them as broken. The [CONSTRAINTS] block in the prompt template explicitly forbids fabrication, but you should still add an eval that samples 5% of internal_page destinations and verifies the page number exists in the source PDF. If fabrication is detected, tighten the constraint language or switch to a model with stronger instruction adherence.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the structured JSON fields the model must return after extracting hyperlinks from a digital PDF's table of contents. Use this contract to validate the response before passing it to downstream navigation or chunking systems.

Field or ElementType or FormatRequiredValidation Rule

toc_entries

array of objects

Array must not be empty if TOC text was provided. Validate array length against input TOC text line count with a tolerance of ±20%.

toc_entries[].display_text

string

Must match the visible TOC entry text exactly, including punctuation and casing. Strip only leading/trailing whitespace. Null or empty string is a failure.

toc_entries[].link_destination

string or null

If a hyperlink exists, must be a valid internal PDF destination (e.g., 'page=12', 'nameddest=Section4.2', 'gotor=...'). If no link is found, value must be null. Reject external URLs (http/https) unless explicitly allowed by [ALLOW_EXTERNAL_URLS].

toc_entries[].destination_type

enum: page_number, named_destination, external_url, null

Must be one of the allowed enum values. Use null only when link_destination is null. If link_destination is present, destination_type must not be null.

toc_entries[].page_number

integer or null

If destination_type is page_number, extract the integer. Otherwise, set to null. Validate that page numbers are positive and within the document's known page range if [DOCUMENT_PAGE_COUNT] is provided.

toc_entries[].confidence

number (0.0 to 1.0)

Model's confidence in the extraction. Must be a float between 0.0 and 1.0. Entries with confidence below [CONFIDENCE_THRESHOLD] should be flagged for human review.

toc_entries[].flags

array of strings or null

List any warnings: broken_link, external_url, mismatched_text, ambiguous_destination, multiple_targets. If no flags, use an empty array. Do not use null.

processing_metadata

object

Must contain extraction_timestamp (ISO 8601 string) and entries_with_links_count (integer). entries_with_links_count must equal the count of toc_entries where link_destination is not null.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when extracting hyperlink targets from a digital PDF table of contents, and how to prevent silent failures in production.

01

External URLs Misidentified as Internal References

What to watch: The model treats an external web link (e.g., https://example.com) listed in the TOC as an internal document destination, producing a fabricated page number or section anchor. This happens when the prompt does not explicitly distinguish between internal PDF actions and external URIs. Guardrail: Add a dedicated output field link_type with enum values internal and external. Post-process external links separately and validate that internal links resolve to known page or named-destination references within the document.

02

Broken or Dead Internal Links

What to watch: The TOC entry displays correct text but the underlying PDF action points to a non-existent page, a deleted section, or a corrupted GoTo action. The model faithfully extracts the broken target without flagging it. Guardrail: Implement a post-extraction validation step that attempts to resolve each extracted internal link against the PDF's page tree and named destinations. Flag any link whose target page number exceeds the document page count or whose named destination is absent.

03

Mismatched Link Text vs. Destination Title

What to watch: The displayed TOC text says 'Introduction' but the link points to a section titled 'Overview' or a completely different heading. This occurs when the PDF author updated heading text without updating the TOC link destinations. Guardrail: After extraction, compare the extracted display_text against the actual heading text at the destination page. Add a text_destination_match boolean field and a confidence score. Route mismatches for human review or flag them in the output metadata.

04

Nested TOC Entries with Ambiguous Link Ownership

What to watch: A parent TOC entry and its child sub-entry share overlapping or identical link targets, or the model assigns the parent's link to the child and vice versa. This breaks navigation trees and section hierarchy mapping. Guardrail: Require the output schema to include a hierarchy_level integer and a parent_entry_index reference. Validate that each link target is unique to its TOC entry and that parent-child relationships form a consistent tree without cycles or orphans.

05

Silent Omission of Unlinked TOC Entries

What to watch: Some TOC entries are plain text without any hyperlink action. The model skips them entirely rather than extracting them with a null link target, causing downstream consumers to believe the TOC is complete when entries are missing. Guardrail: Explicitly instruct the prompt to extract every TOC entry regardless of link presence. Use a nullable link_target field with a link_present boolean. Validate output entry count against a known TOC length or flag unexpected omissions in eval.

06

Page Number vs. Named Destination Conflicts

What to watch: A TOC entry displays a page number but the underlying link uses a named destination that resolves to a different page. The model reports only one target type and discards the other, losing the discrepancy signal. Guardrail: Design the output schema to capture both displayed_page_number and resolved_destination_page as separate fields. Add a page_number_mismatch boolean flag. When the two values differ, surface the conflict for manual verification rather than silently choosing one.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the quality of extracted TOC hyperlinks before integrating the prompt into a production document pipeline. Each criterion targets a known failure mode in hyperlink extraction from digital PDFs.

CriterionPass StandardFailure SignalTest Method

Link Text to Destination Match

The displayed TOC text matches the title of the destination section for at least 95% of entries.

Link text is a generic label like 'Click here' while the destination is a specific section title; or the link text is truncated.

Parse the output JSON. For each entry, compare the [LINK_TEXT] field against the first 50 characters of the destination page's text. Flag mismatches.

Internal vs. External Link Classification

All extracted links are correctly classified as 'internal' (same document) or 'external' (URL). No internal page references are misclassified as external URLs.

An entry pointing to page 42 is classified as 'external' with a fabricated URL, or a web link is classified as 'internal'.

Validate the [LINK_TYPE] field. For 'internal' links, assert the [DESTINATION] field matches a page number or named destination pattern. For 'external' links, assert it matches a URL scheme.

Broken Link Detection

The output explicitly flags links where the destination target is missing, invalid, or points to a non-existent page.

A TOC entry is extracted with a [DESTINATION] value of 'null' or an empty string, but the [STATUS] field is not set to 'broken'.

Check the [STATUS] field for each entry. If [DESTINATION] is null or empty, assert [STATUS] equals 'broken'. If a page number exceeds the document's total page count, assert [STATUS] equals 'invalid_page'.

Hierarchy Preservation

The extracted JSON maintains the parent-child nesting structure implied by the TOC's visual indentation or numbering.

A sub-section (e.g., 1.2.1) appears as a top-level entry, or a parent section's children are missing.

Deserialize the output. Assert that entries with a [DEPTH] value greater than 1 are nested within the correct parent entry based on their [SECTION_NUMBER] prefix.

Entry Completeness

Every visible TOC entry with an interactive link is captured in the output. No entries are skipped.

The output contains 15 entries, but manual inspection of the PDF shows the TOC has 20 clickable lines.

Count the number of entries in the output. Compare against a ground-truth count obtained by manually inspecting the PDF's link annotations using a tool like Adobe Acrobat's link inspector.

Duplicate Entry Handling

If a TOC entry links to the same destination multiple times, the output either deduplicates or explicitly notes the repetition.

The same section title and destination pair appears multiple times in the output array with no deduplication flag.

Group output entries by [DESTINATION]. If any group has more than one entry, check for a [DUPLICATE_OF] field or a deduplication note in the entry's metadata.

Special Character Integrity

Section titles containing special characters (e.g., ampersands, em dashes, legal section symbols) are extracted without corruption.

The section symbol '§' is replaced with '§' or a similar mojibake artifact.

Identify entries where the [LINK_TEXT] contains known special characters from the source PDF. Assert exact string matching against a manually verified ground-truth list of titles.

Confidence Score Calibration

A [CONFIDENCE] score between 0.0 and 1.0 is provided for each entry, and low-confidence entries (<0.7) correlate with actual extraction difficulties.

All entries have a confidence score of 1.0, even for entries where the link destination was ambiguous or the text was partially obscured.

Review entries with a [CONFIDENCE] score below 0.7. Manually verify that these entries correspond to TOC lines with complex formatting, small font sizes, or ambiguous link regions in the source PDF.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single PDF and lighter validation. Focus on getting the TOC link extraction working for one document type before adding schema enforcement. Replace [OUTPUT_SCHEMA] with a simple JSON array of {text, destination} objects. Skip confidence scoring and just flag entries where the link destination is null or unresolvable.

Watch for

  • External URLs (https://) appearing in TOC links and being treated as internal document references
  • Link text that differs from the destination page's actual heading title
  • Multi-line TOC entries where the link spans only part of the displayed text
  • Silent failures when the PDF has no interactive TOC links at all
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.