PDF table of contents is clickable, but the hierarchy is lost after extraction — what should I do?
Bookmark levels must be checked before they are written. The first item is level one, and each subsequent item may increase by at most one level over the item before it. The example rejects illegal levels and out-of-range page numbers, and does not automatically change levels to fabricate a directory structure. Bookmark page numbers start from one, while page indexes usually start from zero.
Key Points of This Article
- Bookmark levels must be validated before they are written; the first item must be level 1.
- Each subsequent level may increase by at most one level relative to the previous item. A non-compliant table of contents should be rejected for writing rather than automatically corrected.
- Bookmark page numbers start counting from 1, whereas page indexes usually start from 0; the two must be distinguished.
- An empty list returned by get_toc() may indicate that the PDF has no embedded bookmarks, in which case text layout analysis should be used instead.
- When a page number is out of range, PyMuPDF may only print a warning without raising an exception, so the validation function must actively filter such entries.
The PDF's table of contents navigates correctly in the reader, but when extracted with a script, the hierarchy may come out flat, page numbers may be misaligned, or the index may be abnormal. These problems are common in files that come from merged scanned documents or have irregularly structured bookmarks. If the extraction results are passed directly to downstream processes, translation segmentation and links may both end up wrong.
This article is for developers and documentation teams who need to batch-process PDF tables of contents. After reading it, you will understand the meaning of get_toc() return values, master the validation rules for levels and page numbers, and know which cases should be handed over to manual verification. Before processing important files, keep the originals, and review them against the boundaries and acceptance items described in the text.
Clickable PDF table of contents still works, but the hierarchy was lost after extraction: what should I do? One-sentence conclusion
Validate first, then write: bookmark levels must be checked beforehand. The first item is treated as level 1, and each subsequent level may not exceed the previous item's level plus one. Entries whose page numbers are out of range are not written.
| Your situation | Recommended Practices | Cause |
|---|---|---|
| The table of contents page is clickable, but after extraction the hierarchy is flat or misaligned. | First fetch the original list using get_toc(), then verify each item before use. | get_toc() returns the raw list without structural validation |
| Page number is 0 or exceeds the total number of pages | Discard the entry and log it | Out-of-range page numbers cause navigation to fail. |
get_toc() returns an empty list | Switch to text layout analysis instead of blindly retrying. | The document may not have bookmark metadata embedded. |
| Same heading corresponds to multiple different page numbers | Marked as ambiguous; forwarded to manual review. | Unable to automatically determine which page number is correct |
Why does the extraction result lose its hierarchy?
get_toc() outputs a list of [level, title, page] triples by default. Here, page is the 1-based physical page number, and level only indicates nesting depth; it is not guaranteed to be consecutive or valid.
If the source PDF was generated by a scan-merging tool, common problems include:
- Level skipping: e.g., jumping directly from 1 to 3
- Abnormal page numbers: page number is 0 or exceeds the total page count
- Abnormal titles: title contains control characters
It can be used directly in downstream tasks, but this will cause translation segments to become misaligned or links to break. Even more insidious, some PDFs visually have a table of contents page but contain no embedded bookmark metadata. In this case, get_toc() returning an empty list is normal, and you need to switch to text layout analysis instead.
Self-contained Synthetic Example
Example dependencies are listed in the import list.
import pymupdf
def validate(rows, pages):
previous = 0
for level, title, page in rows:
if type(level) is not int or level < 1 or level > previous + 1:
raise ValueError("invalid hierarchy")
if type(page) is not int or not 1 <= page <= pages:
raise ValueError("invalid destination")
if not isinstance(title, str) or not title.strip():
raise ValueError("empty title")
previous = level
return rows
with pymupdf.open() as doc:
for _ in range(3):
doc.new_page()
rows = [[1, "Chapter", 1], [2, "Section", 2], [1, "Appendix", 3]]
doc.set_toc(validate(rows, doc.page_count))
assert doc.get_toc() == rows
assert len(doc.get_toc()) == 3
for bad in [[[2, "Bad", 1]], [[1, "Bad", 99]], [[1, "", 1]]]:
try:
validate(bad, doc.page_count)
except ValueError:
pass
else:
raise AssertionError("invalid outline accepted")
Handling Rules for Valid and Invalid Input
Valid input should satisfy: a list of triples where levels are consecutive and page numbers are within the [1, doc.page_count] range. For example, [[1, "引言", 1], [2, "背景", 2], [1, "方法", 5]] is valid, since the second level appears after the first level, conforming to PDF outline syntax.
Common incorrect inputs include:
- Level is 0 or negative
- Page number is 0
- Page number exceeds the total number of pages
- Title is an empty string or contains only whitespace characters
In these situations, the text gives the following ways of handling them:
- Skip entries with invalid page numbers and log a warning.
- For empty titles, keep placeholders such as
[untitled]to maintain structural integrity. - Do not interrupt the parsing of the entire table of contents because of a single error.
Regarding levels less than 1, two strategies need attention: the summary section of the example advocates rejecting illegal levels without automatic correction, while the rule description in the text forces them to 1. Choose between the two according to your own process. Also note that these rules exist to make downstream processing robust and are not mandatory requirements of the PDF standard. In testing, PyMuPDF printed a warning but did not raise an exception when a page number was out of range, so the validation function must filter these values actively and cannot rely on the library's behavior.
📊 Core Comparison
Depending on the document, the results and recommended handling for get_toc() differ:
| Document status | get_toc() Results | Recommended handling |
|---|---|---|
| Has bookmarks and a valid structure | Return a list of triples | Use directly after verification |
| Has bookmarks, but the hierarchy or page numbers are abnormal | Return a list containing the exceptional items | Filter, log, and escalate to a human when necessary |
| Visual table of contents page but no bookmarks | Return an empty list | Switch to text layout analysis |
| EPUB reflowable document | Page number format is (chapter, pno) | This page-number validation logic does not apply; it requires dedicated handling. |
Acceptance Criteria and Boundaries for Manual Review
The following table covers only the extraction step for the PDF directory metadata:
| Observe the phenomenon | Handling decision | Is automation applicable? |
|---|---|---|
| Page number is 0 or greater than the total number of pages | Discard this entry and log it | Yes |
| Level less than 1 or not an integer | Process according to the rules above (see the earlier instructions). | Yes |
| Title is entirely blank or pure symbols | [untitled] | Yes |
| Level skipping (e.g., from 1 to 3) | Retain the original hierarchy; do not add intermediate levels. | Yes (structurally valid) |
| The same heading corresponds to multiple different page numbers | Marked as ambiguous, transferred to human review | No |
| Number of entries exceeds 200 with no change in level | Suspected OCR misrecognition; manual verification required | No |
| Contains external URIs or JavaScript actions | Filter out non-page-navigation items | Yes (security policy) |
| EPUB and other reflowable documents: page numbers are given as (chapter, pno) | This page-number validation logic does not apply. | No (requires special handling) |
It should be noted that the code demonstration only verifies structural validity; the end-to-end effect still needs to be checked in conjunction with rendering to confirm whether the jumps are accurate.
🎯 Which Approach Suits You?
If you need to extract directories in bulk
First validate the structure of the get_toc() results, then write them into the downstream process, and keep logs for later review.
If your PDF visually has a table of contents but extraction returns empty
Do not keep retrying get_toc(); switch to text layout analysis instead.
If your table of contents entries show the same name on different pages
Flag these entries for manual review; do not automatically choose one of the page numbers.
If you are going to hand the document over to a translation workflow
First confirm that the directory structure and page numbers are correct, then proceed with translation to avoid misaligned segments.
❓ Frequently Asked Questions (FAQ)
1. Why do page numbers start at 1, while page indices usually start at 0?
Bookmark page numbers are 1-based physical page numbers, whereas page indices in libraries such as PyMuPDF usually start at 0. This difference must be taken into account during conversion; otherwise, page numbers will be misaligned.
2. Does get_toc() returning an empty list necessarily mean the file has a problem?
Not necessarily. Some PDFs have a visible table of contents page but no embedded bookmark metadata. In that case, returning an empty list is normal behavior, and text layout analysis should be used instead.
3. Will the library raise an error directly when the page number is out of range?
No. Testing in this article found that PyMuPDF prints a warning but does not raise an exception when the page number is out of range, so the validation function must filter actively.
4. Do level skips (e.g., going directly from 1 to 3) need intermediate levels filled in?
The text recommends keeping the original heading levels and not inserting intermediate levels, because this structure is still valid.
📝 Summary
The hierarchy and page numbers of a PDF table of contents must be validated before use. get_toc()'s raw output should not be treated as a reliable structure directly. When there is ambiguity or no bookmarks, escalate to a human or switch to another method in time, which helps prevent errors in downstream workflows.
Try it now: upload a document and start translating right away, with the original layout preserved.
References and Next Steps
Suggested next steps: prepare a test PDF containing known table-of-contents issues, run the above validation script, and tally the proportion of each type of anomaly. If level skips or page-number offsets occur frequently, consider adding a table-of-contents rebuilding step before translation.
Using this checklist for document translation
First, check the page order, source locations, and text completeness. Then send the same sample to the translation pipeline. After translation, verify that headings, body text, and captions correspond correctly. Don't judge only by whether the text reads smoothly.
OmniDoc's document translation supports formats such as PDF, Word, PPT, and Excel. Scanned documents have their text recognized first, tables are translated cell by cell with rows and columns preserved, and PDFs produce two versions: a bilingual side-by-side version and a translation-only version. Paid translation also lets you upload a glossary and enable context-aware translation.


