Obvious non-repeating header removed
I have requirement to convert PDF to markdown for LLM processing. In many PDFs, It does fantastic job of removing header/footers which needs to be removed.
However in one PDF, all obvious top headings are removed (non repeating) as header/footer which is major issue. Here is the PDF - https://www.airlinepilotcentral.com/files/republiccontract.pdf.
Hi, I dug into this and traced the mechanism. Sharing in case it's useful and to float a fix approach before opening a PR.
Root cause
The layout model labels regions per-page from positional cues, so a non-repeating heading sitting at the top/bottom of a page gets tagged PAGE_HEADER/PAGE_FOOTER. From there:
- The layout postprocessor only gates these labels by a confidence threshold (
page_header/page_footer≥ 0.5), and there's no cross-page check anywhere in the pipeline. ReadingOrderModelunconditionally maps both labels toContentLayer.FURNITURE.- Default exporters use
DEFAULT_CONTENT_LAYERS = {ContentLayer.BODY}, so the heading is silently dropped.
The export-time workaround (included_content_layers={ContentLayer.BODY, ContentLayer.FURNITURE}) brings the heading back, but it's lossy the other way. It also re-injects every genuine repeating header/footer onto every page. So it's a mitigation, not a fix.
The core gap: docling equates "looks like a header by position on a single page" with "is repeating furniture." A real running header/footer repeats across pages; a one-off heading does not, and nothing currently checks that.
Proposed approach
Add a document-level reclassification pass (e.g. in ReadingOrderModel, which already has whole-document context) that runs before the FURNITURE assignment:
- Collect all
PAGE_HEADER/PAGE_FOOTERelements and build a normalized signature per element (lowercased, digits stripped so"Page 3 of 10"/ dates still match across pages), bucketed by side. - Signature on ≥2 pages → genuine running furniture, keep as-is.
- Signature on only one page → reclassify so it survives in
BODY(non-repeating top-of-page →SECTION_HEADER, which then flows into the existing PDF heading-level inference; footers →TEXT).
To keep it safe and reviewable:
- Gate it behind a
LayoutOptionstoggle (default on) so detection can be disabled at the processing stage — which isn't possible today. - Conservative guards (e.g. only act when the doc has ≥3 pages, since repetition is unobservable in 1–2 page docs).
- Regenerate and carefully review the e2e reference data, plus a focused test using a synthetic multi-page PDF (repeating running header stays out of body; one-off top heading appears in it).
Would the maintainers be open to a PR along these lines? Happy to adjust the heuristic (e.g. fraction-of-pages threshold vs. a hard ≥2) or the reclassification target before I start. If a sample of the affected PDF can be shared, I'll validate against it. Thanks a lot!
I like the approach. Here are sample PDF's that we can use Affected PDF - https://www.airlinepilotcentral.com/files/republiccontract.pdf In the pdf, there are no running headers in any page and many pages are captured wrongly. There is genuine footer, which are detected well.
Works well pdf - https://www.local135.com/wp-content/uploads/2023/08/Republic-Contract.pdf In this PDF, there are running header/footers and detected well.
This issue is more problematic in case of Headers where some major text/heading can be missed. For footers - I do not see a big issue.
One more logic we can add - if the PDF has any headers at all? It is unlikely that some pages will have headers and some pages not. If there is running header in every page, they are most likely genuine. If headers appear randomly in only few pages - they are most likely incorrect ones. In the problematic pdf, there is actually no header in any page.
Hi @LalitAgarwalla, Thanks you very much for all this sample PDF, it is really helpful. I find the logic interesting too and love it. I'll try to add it and test it. Thanks again!
Excellent root-cause writeup, and the sample choice is perfect for stress-testing this — @LalitAgarwalla's affected PDF is literally a collective bargaining agreement (Republic Airways pilot contract), which is exactly the regulated/legal-document corpus where this failure mode stops being cosmetic.
A legal-domain angle on why the signature-based reclassification matters more than "lost navigation":
-
Contract section headings are cross-reference targets, not just anchors. Legal documents self-reference constantly — "as provided in Section 25", "subject to Article VIII", "pursuant to Section 4.2(b)". When a non-repeating
SECTION 25 – SICK LEAVEheading sits at the top of a page and gets reclassified toFURNITUREthen dropped fromBODY, you don't just lose a navigation bookmark: every downstream string-search / cross-reference resolver that anchors on"Section 25"now has no target to land on. The retrieval layer can't stitch "Section 25" references to their operative text because the heading token that defines the boundary was discarded. So the surface symptom ("a heading is missing") understates the blast radius — it's a broken reference graph, silent, with no error. -
The cross-page repetition invariant is the right one, and it generalizes well to legal corpora where genuine running furniture is common and stable (page numbers, "Confidential — Subject to Protective Order" banners, exhibit labels like
EXHIBIT Bon every page of an attachment). Those repeat on ≥2 pages and correctly survive as furniture. The inverse edge — a genuinely repeating element that is load-bearing content — is rare in contracts (footers are almost always furniture), so the ≥2-page heuristic is safe here. The one case worth a guardrail: a clause-reference footer that embeds operative text, but that's unusual. -
Test suggestion for the synthetic fixture: beyond "repeating running header stays out / one-off heading appears in body", add a provenance-continuity assertion — a non-repeating heading at a page top that is referenced from body text (e.g. a heading
Section 4.2with body text "see Section 4.2"). Assert not only that the heading survives inBODY, but that a plain string-search for the section identifier finds the heading and the reference resolves to it. That catches the failure mode that actually bites legal/regulatory consumers (reference graph intact), not just presence/absence. @LalitAgarwalla's airline contract would be a great real-world fixture for this since CBAs are cross-reference-dense. -
This is the same class as the other export-layer asymmetries the project has been hitting — content survives in the internal
DoclingDocumentmodel but is silently absent from the default export (md_content/DEFAULT_CONTENT_LAYERS = {BODY}), so the two readers (JSON consumer vs markdown consumer) see materially different documents with no error signal. Fixing it at the source via a reclassification pass (this proposal) is strictly better than a downstream coverage warning, because the warning approach still leaves the JSON/markdown readers disagreeing — the reclassification makes them agree by construction. TheLayoutOptionstoggle + ≥3-page guard are the right safety rails.
Would a fixture along these lines (cross-reference targets landing at page tops) be useful for the PR? Happy to contribute a minimal synthetic PDF or the assertion logic if @DanielNg0729 is taking this on.
@DanielNg0729, here is a public test case for the inverse direction of the repetition check you describe. In this document a header that repeats on every page is labelled text, and only partly so, which varies from page to page. A signature-based check would fix both directions at once.
Document: a public tender bill of quantities (RAW inschrijvingsstaat), Gemeente De Ronde Venen, published on TenderNed (art. 15b of the Dutch Copyright Act): https://www.tenderned.nl/papi/tenderned-rs-tns/v2/publicaties/442062/documenten/14939169/content
Every page prints the same three-line header block above a rule:
RAW1157-160339 | Herinrichting Dukaton te Mijdrecht | Bladnr. N
| Opdrachtgever: gemeente De Ronde Venen |
| Bestek 2026-1 25 september 2026 - DEFINITIEF incl. NvI 2 -
docling 2.135.0 (standard pipeline, OCR off), on pages 2 and 3:
p2 [page_header] 'Herinrichting Dukaton te Mijdrecht'
p2 [page_header] 'Bestek 2026-1'
p2 [page_header] 'Bladnr. 2'
p2 [text] 'Opdrachtgever: gemeente De Ronde Venen'
p2 [text] '25 september 2026'
p2 [text] '- DEFINITIEF incl. NvI 2 - Opdrachtgever: gemeente De Ronde Venen'
p3 [page_header] 'Herinrichting Dukaton te Mijdrecht'
p3 [page_header] 'Bestek 2026-1'
p3 [page_header] '- DEFINITIEF incl. NvI 2 -'
p3 [page_header] 'Bladnr. 3'
p3 [text] '25 september 2026'
Opdrachtgever: …and the date stay in the body on every page.- DEFINITIEF incl. NvI 2 -is furniture on p. 3 but body text on p. 2, where it is also merged with a copy of theOpdrachtgeverline, so that line appears twice.
These lines land between the table fragments of consecutive pages, which matters for anything that tries to join a table continued over a page break (#2976). On our side we treat a line as furniture when it sits in the top or bottom 8% of the page and the same text recurs in the margin of another page. That is the signature idea from this thread, applied the other way round.
Classification labels added: priority:medium, pdf.
These labels are advisory. Maintainers can correct them. The workflow preserves these corrections.
A centred section sign at the page edge is labelled page_footer / page_header and
vanishes from Markdown
Another case of the same root cause, with a synthetic reproducer, and a note on why the heuristic in #3697 would not recover it.
Legal documents (statutes, orders, regulations) open every unit with a short centred line such as § 6. When
such a line happens to sit at the bottom or the top edge of a page, the layout model labels it page_footer or
page_header. The reading-order step moves it to the furniture layer, and the default Markdown export drops it.
The unit's text is then merged into the previous unit, so a reader (or a RAG chunker) cannot see where § 6
begins.
Reproducer: a 2-page PDF. § 6 is the last line of page 1 and § 7 is the first line of page 2. Body text sits
between them as usual.
# make.py: pip install reportlab; python make.py synthetic.pdf
import sys
from reportlab.lib.pagesizes import A4
from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
pdfmetrics.registerFont(TTFont("Serif", "/usr/share/fonts/truetype/dejavu/DejaVuSerif.ttf"))
W, H = A4
LEFT, SIZE, LEAD = 70.9, 11, 15.5
out = canvas.Canvas(sys.argv[1], pagesize=A4)
y = H - 70
def text(words):
global y
out.setFont("Serif", SIZE)
out.drawString(LEFT, y, words)
y -= LEAD
def centred(words):
global y
out.setFont("Serif", SIZE)
out.drawCentredString(W / 2, y, words)
y -= LEAD
def paragraph(lines):
global y
for line in lines:
text(line)
y -= 6
filler = [
"The employer keeps a register of the cards issued to employees and checks it once a year,",
"comparing the entries with the statements of the bank and with the documents of each card.",
"Any difference found during the check is described in a note and sent to the head of finance.",
]
centred("ORDER No. 7/2026")
centred("of the Director of the Institute")
y -= 10
for mark in range(1, 6):
centred(f"§ {mark}")
paragraph(filler * 2)
while y > 120:
paragraph(filler[:2])
y = 62
centred("§ 6")
out.showPage()
y = H - 60
centred("§ 7")
paragraph(filler * 2)
for number in range(1, 9):
text(f"{number}) the employee returns the card to the finance department when the employment ends,")
y -= 6
centred("§ 8")
text("The order enters into force today.")
y -= 6
centred("§ 9")
text("At the same time order No. 5/2020 of the Director of the Institute loses its force.")
out.showPage()
out.save()
# convert.py: python convert.py synthetic.pdf
import sys
from docling.datamodel.base_models import InputFormat
from docling.datamodel.pipeline_options import PdfPipelineOptions
from docling.document_converter import DocumentConverter, PdfFormatOption
options = PdfPipelineOptions(do_ocr=False)
converter = DocumentConverter(format_options={InputFormat.PDF: PdfFormatOption(pipeline_options=options)})
document = converter.convert(sys.argv[1]).document
for item in document.texts:
if item.text.startswith("§"):
print(item.label.value, item.content_layer.value, item.prov[0].page_no, repr(item.text))
print("in markdown:", [m for m in ("§ 6", "§ 7") if m in document.export_to_markdown()])
Output with docling 2.142.1 and 2.150.1 (docling-ibm-models 4.0.4, docling-core 2.107.1). The default backend and
PyPdfiumDocumentBackend give the same result:
page_footer furniture 1 '§ 6'
page_header furniture 2 '§ 7'
in markdown: []
Expected: § 6 and § 7 stay in the body (as section_header or text) in the order of the page.
On #3697: in documents like this, the heuristic keeps both marks as furniture, for two independent reasons:
_normalize_signaturestrips digits, so every unit sign collapses to the signature§. Two unit signs on the footer side on different pages already count as a repeating running footer (min_repeat_pages = 2).- Such documents usually carry a real page number in the footer of most pages (
- 2 -,- 3 -, ...). That makes the footer side "genuine" by coverage, so every other footer detection on that side is kept too.
The second point applies to any short heading that lands at the page edge of a document with page numbers, not
only to unit signs. A per-element test may separate the two kinds better than a per-side test. A running footer
repeats at about the same position with about the same text; a unit sign continues the sequence of the body
headings, with the same font and alignment as the other § N lines that are body text.