Merged paragraph across pages of different heights: continuation bbox uses the first page's height

Open Beginner friendly
#5,286 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 2 days

@galer1us is already working on this.

Since Nov 10, 2026.

  • #5287 by @galer1us — open

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
78/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
python
Domain
backend

Research direction

Read docling/models/stages/reading_order/readingorder_model.py, especially the call to _merge_elements around line 780 and the bbox conversion in _merge_elements around line 1066. Use the supplied two-page PDF reproducer with page heights 792 and 700 to check the continuation provenance bbox. Done means the page-2 bbox uses page 2's height and matches the reported t=635.9, b=597.7 result.

Written by the indexing model from the issue text.

Description

Bug

ReadingOrderModel merges a text element with its continuation on the next page (predict_merges). The continuation gets its own ProvenanceItem with the correct page_no, but its bbox is wrong when the two pages have different heights.

Observed: the continuation bbox is moved by the height difference of the two pages. In the reproducer below, page 1 is 792 pt high and page 2 is 700 pt high. The continuation box on page 2 has t=727.9, which is above the top of the page. The page-2 text is at t=635.9. The error is exactly 792 - 700 = 92 pt.

Expected: each ProvenanceItem bbox is converted with the height of its own page.

Root cause (main at 1ae470a, docling/models/stages/reading_order/readingorder_model.py):

  • line 748: page_height is the height of the page of the first element (element.page_no).
  • lines 780-782: this page_height goes into _merge_elements(element, merged_elem, new_item, page_height).
  • line 1066: _merge_elements converts the box of merged_elem with it: merged_elem.cluster.bbox.to_bottom_left_origin(page_height). merged_elem can be on another page.

to_bottom_left_origin computes t = page_height - top, so the result is off by H(first page) - H(continuation page). The l and r values are correct. When all pages have the same height, the output is correct, so the bug is not visible in most documents. Scanned documents and TIFF files often mix page sizes.

#1699 reported the wrong page_no/bbox source for merged elements. That part is fixed. The page height is the part that remains.

Steps to reproduce

The script builds a synthetic two-page PDF (612x792, then 612x700) with one paragraph that continues across the page break. It needs no other files.

"""Build a two-page PDF (612x792, then 612x700) with one paragraph that runs
across the page break, convert it, and compare the continuation box on page 2
with the real position of the page-2 text."""

import sys
from pathlib import Path

from docling.datamodel.base_models import InputFormat
from docling.datamodel.pipeline_options import PdfPipelineOptions
from docling.document_converter import DocumentConverter, PdfFormatOption
from docling_core.types.doc import TextItem


def page_stream(lines):
    ops = ["BT", "/F1 11 Tf"]
    for x, y, text in lines:
        ops.append(f"1 0 0 1 {x} {y} Tm ({text}) Tj")
    ops.append("ET")
    return "\n".join(ops).encode()


FILLER = [
    "Docling converts documents into a structured representation for later use.",
    "Each page holds several paragraphs of plain body text in a single column,",
    "set in a regular sans-serif face with an even line spacing of fourteen points.",
    "The text has no tables, no figures and no headers so that the layout model",
    "treats every block as an ordinary paragraph of running body text here.",
]


def paragraph_lines(top, n_paragraphs):
    lines, y = [], top
    for _ in range(n_paragraphs):
        for i, text in enumerate(FILLER):
            lines.append((72, y, text if i < len(FILLER) - 1 else text[:-5] + "end."))
            y -= 14
        y -= 14
    return lines, y


def build_pdf(path, heights=(792, 700)):
    page1, y = paragraph_lines(heights[0] - 72, 7)
    page1 += [
        (72, y, "The paragraph under test begins near the bottom of the first page and it"),
        (72, y - 14, "keeps running for several lines so that the layout model sees body text,"),
        (72, y - 28, "and the sentence deliberately does not finish here but continues onto the"),
    ]
    page2 = [
        (72, heights[1] - 72, "next page, where the remaining words of the same sentence appear at the"),
        (72, heights[1] - 86, "top of the second page, which is shorter than the first page, and this"),
        (72, heights[1] - 100, "is where the reading order model merges the two text elements."),
    ]
    more, _ = paragraph_lines(heights[1] - 128, 6)
    page2 += more
    streams = [page_stream(page1), page_stream(page2)]
    objs = [
        b"<< /Type /Catalog /Pages 2 0 R >>",
        b"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>",
    ]
    for i, h in enumerate(heights):
        objs.append(
            b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 %d] "
            b"/Resources << /Font << /F1 7 0 R >> >> /Contents %d 0 R >>" % (h, 5 + i)
        )
    for s in streams:
        objs.append(b"<< /Length %d >>\nstream\n" % len(s) + s + b"\nendstream")
    objs.append(b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>")
    buf = b"%PDF-1.4\n"
    offsets = []
    for i, o in enumerate(objs, 1):
        offsets.append(len(buf))
        buf += b"%d 0 obj\n" % i + o + b"\nendobj\n"
    xref = len(buf)
    buf += b"xref\n0 %d\n0000000000 65535 f \n" % (len(objs) + 1)
    for o in offsets:
        buf += b"%010d 00000 n \n" % o
    buf += b"trailer\n<< /Size %d /Root 1 0 R >>\nstartxref\n%d\n%%%%EOF\n" % (
        len(objs) + 1,
        xref,
    )
    Path(path).write_bytes(buf)


pdf = Path(sys.argv[1] if len(sys.argv) > 1 else "two_heights.pdf")
build_pdf(pdf)
opts = PdfPipelineOptions(do_ocr=False, do_table_structure=False)
conv = DocumentConverter(format_options={InputFormat.PDF: PdfFormatOption(pipeline_options=opts)})
doc = conv.convert(pdf).document
print("page heights:", {n: p.size.height for n, p in doc.pages.items()})
for item in doc.texts:
    if isinstance(item, TextItem) and len({p.page_no for p in item.prov}) > 1:
        print(f"merged {item.label.value}: {item.text[:50]!r}...")
        for p in item.prov:
            b = p.bbox
            print(f"  page {p.page_no}: l={b.l:.1f} t={b.t:.1f} r={b.r:.1f} b={b.b:.1f} ({b.coord_origin.value})")
print("expected page-2 continuation top: about 636 (first baseline 628 + cap height), BOTTOMLEFT on the 700 pt page")

Output on 2.150.0 and on main:

page heights: {1: 792.0, 2: 700.0}
merged text: 'The paragraph under test begins near the bottom of'...
  page 1: l=72.0 t=139.9 r=426.0 b=101.7 (BOTTOMLEFT)
  page 2: l=72.0 t=727.9 r=434.6 b=689.7 (BOTTOMLEFT)

The page-2 box is above the 700 pt page. With the fix below it is t=635.9 b=597.7, on the page-2 text.

Proposed fix: in the call at line 780, pass page_no_to_pages[merged_elem.page_no].size.height instead of page_height. I can open a PR with this change and a regression test.

Docling version
Docling version: 2.150.0
Docling Core version: 2.106.0
Docling IBM Models version: 4.0.4
Docling Parse version: 7.23.0

Also reproduced on main at 1ae470a.

Python version

Python 3.14.6 (macOS arm64)


Found, reproduced and the fix drafted with an AI coding agent (Claude Code). A person reviewed it before filing.

Dominant language
Python
Stars
71k
Forks
5.4k
Avg merge
2d 22h
Merged PRs (30d)
161

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from docling-project/docling

All issues in docling-project/docling

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.