From 41885532672a5edea0a75036f0c48ee393456efd Mon Sep 17 00:00:00 2001 From: "Jorj X. McKie" Date: Mon, 30 Nov 2026 12:02:37 -0400 Subject: [PATCH 1/2] Fixes #5321 In page method get_sorted_text() we previously only sorted by span coordinates to produce legible text. This change introduces a by character ("rawdict") approach to ensure that mis-shaped words and spans do not spoil the final result. Other changes include also outputting vertical text (after all horizontal text) and optionally (default) removing page rotation. --- changes.txt | 61 ++++---- src/utils.py | 387 ++++++++++++++++++++++++++++++++++++++------------- 2 files changed, 320 insertions(+), 128 deletions(-) diff --git a/changes.txt b/changes.txt index 137e1d24e..0f60a2a06 100644 --- a/changes.txt +++ b/changes.txt @@ -7,11 +7,16 @@ Change Log Fixed issues: * **Fixed** `4755 `_: Unexpected behavior of annot.set_rect() with carets and strikeouts +* **Fixed** `5310 `_: Document.extract_image raises "pixmap may not have alpha to save as JPEG" for a CMYK JPEG with a soft mask +* **Fixed** `5319 `_: get_text keeps descending-x glyphs in content order, reversing numbers (7,0 → 0,7) + Other: * Modified return value from `Annot.rect` attribute. * Added `Annot.bounds` attribute. +* Improved method `Document.recalculate_form() `_: we now generate new appearance streams for the widgets of form fields that are subject to cross-field calculations via JavaScript. +* Improved method `Page.get_text() `_, version `page.get_text("text", sort=True)` to produce the same output as the CLI command `pymupdf gettext -mode layout`. **Changes in version 2.2** (2026-11-26) @@ -174,7 +179,7 @@ Other: Fixed issues: -* **Fixed** `4114 `_: ComboBox choice_values full of empty strings despite PDF having valid choices. +* **Fixed** `4114 `_: ComboBox choice_values full of empty strings despite PDF having valid choices. * **Fixed** `4950 `_: remove_rotation() raises ValueError on widgets with empty/infinite rects * **Fixed** `5001 `_: Formulae incorrectly rendered as black boxes * **Fixed** `5033 `_: Annot.set_rotation(0) followed by Annot.update() throws AttributeError @@ -231,12 +236,12 @@ Other: * **Fixed** `4903 `_: Typing broken because of `*_forward_decl` * **Fixed** `3842 `_: Partial OCR using "get_textpage_ocr" ignores image masks while extracting text - + * Other: * Retrospectively marked #4907 as fixed in pymupdf-1.27.1. * Improved `get_textpage_ocr()`. - + For partial OCR, **all** page areas outside legible text are now OCRed, not just those within images. This means that OCR will now also be performed for vector graphics, and for text containing illegible characters. @@ -340,7 +345,7 @@ Other: * **Fixed** `4639 `_: pymupdf.mupdf.FzErrorGeneric: code=1: Director error: : 'JM_new_bbox_device_Device' object has no attribute 'layer_name' * Other: - + * Check that #4392 `Segfault when running with pytest and -Werror` is fixed if PyMuPDF is built with swig>=4.4. * Add `Page.clip_to_rect()`. * Improved search for Tesseract data. @@ -639,7 +644,7 @@ Other: so will raise an exception. (#3603) * Fixed handling of non-existing /Contents object. - + **Changes in version 1.24.9 (2024-07-24)** * Use MuPDF-1.24.8. @@ -693,11 +698,11 @@ Other: * Other: * Fixed concurrent use of PyMuPDF caused by use of constant temporary filenames. - + * Add musllinux x86_64 wheels to release. * Added clearer version information: - + * `pymupdf.pymupdf_version`. * `pymupdf.mupdf_version`. * `pymupdf.pymupdf_date`. @@ -777,14 +782,14 @@ Other: * Other: * New/modified methods: - + * `Document.bake()`: new, make annotations / fields permanent content. * `Page.cluster_drawings()`: new, identifies drawing items (i.e. vector graphics or line-art) that belong together based on their geometrical vicinity. * `Page.apply_redactions()`: added new parameter `text`. * `Document.subset_fonts()`: use MuPDF's `pdf_subset_fonts()` instead of PyMuPDF code. - + * The `Document` class now supports page numbers specified as slices. * Avoid causing MuPDF warnings. @@ -828,11 +833,11 @@ Other: * Use MuPDF-1.24.0. * Add support for redacting vector graphics. * Several fixes for table module - + * Add new method for outputting the table as a markdown string. - + * Address errors in computing the table header object: - + We now allow None as the cell value, because this will be resolved where needed (e.g. in the pandas DataFrame). @@ -847,7 +852,7 @@ Other: * Improved exception text if we fail to open document. * Fixed build with new libclang 18. - + **Changes in version 1.23.26 (2024-02-29)** @@ -859,7 +864,7 @@ Other: * Other: * Improvements to table detection: - + * Improved check for empty tables, fixes bugs when determining table headers. * Improved computation of enveloping vector graphic rectangles. * Ignore more meaningless "pseudo" tables @@ -968,7 +973,7 @@ Other: * Other: * When finding tables: - + * Allow addition of user-defined "virtual" vector graphics when finding tables. * Confirm that the enveloping bboxes of vector graphics are inside the clip rectangle. * Avoid slow finding of rectangle intersections. @@ -1123,13 +1128,13 @@ Other: * **Fixed** `2886 `_: Error in Skeleton for Named Link Destinations * Bug fixes (rebased and classic implementations): - + * **Fixed** `2885 `_: pymupdf find tables too slow * Other: * Rebased implementation: - + * `Page.insert_htmlbox()`: new, much more powerful alternative to `Page.insert_textbox()` or `TextWriter.fill_textbox()`, using `Story`. * `Story.fit*()`: new methods for fitting a Story into an expanded rect. * `Story.write_with_links()`: add support for external links. @@ -1169,17 +1174,17 @@ Other: * Other: * Rebased implementation: - + * Added flake8 code checking to test suite, and made various fixes. * Disable diagnostics during Document constructor to match classic implementation. - + * Additional fix to `2553 `_: Invalid characters in versions >= 1.22 * Fixed `MuPDF Bug 707324 `_: Story: HTML table row background color repeated incorrectly * Added `scripts/test.py`, for simple build+test of PyMuPDF git checkout. * Added `fitz.pymupdf_version_tuple`, e.g. `(1, 23, 6)`. * Restored mistakenly-reverted fix for `2345 `_: Turn off print statements in utils.py * Include any trailing `... repeated times...` text in warnings returned by `mupdf_warnings()` (rebased only). - + **Changes in version 1.23.6 (2023-11-06)** @@ -1301,13 +1306,13 @@ Other: * Dropped support for Python-3.7. * Fix for wrong page / annot `/Contents` cleaning. - + We need to set `pdf_filter_options::no_update` to zero. * Added new function get_tessdata(). * Cope with problem `/Annot` arrays. - + When copying page annotations in method Document.insert_pdf we previously did not check the validity of members of the `/Annots` array. For faulty members (like null or non-dictionary items) this @@ -1321,12 +1326,12 @@ Other: accordance with MuPDF. * Increase fault tolerance. - + Avoid exceptions in method `insert_pdf()` when source pages contains invalid items in the `/Annots` array. * Return empty border dict for applicable annots. - + We previously were returning a non-empty border dictionary even for non-applicable annotation types. We now return the empty dictionary `{}` in these cases. This requires some corresponding changes in the @@ -1339,13 +1344,13 @@ Other: annotations and return `False` in these cases. * Wrong fontsize computation in `page.get_texttrace()`. - + When computing the font size we were using the final text transformation matrix, where we should have taken `span->trm` instead. This is corrected here. * Updates to cope with changes to latest MuPDF. - + `pdf_lookup_anchor()` has been removed. * Update fill_textbox to better respect rect.width @@ -1375,7 +1380,7 @@ Other: * **Fixed** `#2430 `_: Incorrectly reducing ref count of Py_None. * **Fixed** `#2450 `_: Empty fill color and fill opacity for paths with fill and stroke operations with 1.22.* * **Fixed** `#2462 `_: Error at "get_drawing(extended=True )" - * **Fixed** `#2468 `_: Decode error when trying to get drawings + * **Fixed** `#2468 `_: Decode error when trying to get drawings * **Fixed** `#2710 `_: page.rect and text location wrong / differing from older version * **Fixed** `#2723 `_: When will a Python 3.12 wheel be available? @@ -1606,7 +1611,7 @@ Other: * Fixed various broken links and typos in docs. * Mention install of `swig-python` on MacOS for #875. * Added (untested) wheels for macos-arm64. - + diff --git a/src/utils.py b/src/utils.py index 34b67b849..b703bcc47 100644 --- a/src/utils.py +++ b/src/utils.py @@ -1,13 +1,34 @@ -# ------------------------------------------------------------------------ -# Copyright 2020-2022, Harald Lieder, mailto:harald.lieder@outlook.com -# License: GNU AFFERO GPL 3.0, https://www.gnu.org/licenses/agpl-3.0.html -# -# Part of "PyMuPDF", a Python binding for "MuPDF" (http://mupdf.com), a -# lightweight PDF, XPS, and E-book viewer, renderer and toolkit which is -# maintained and developed by Artifex Software, Inc. https://artifex.com. -# ------------------------------------------------------------------------ +""" +Copyright (C) 2023 Artifex Software, Inc. + +This file is part of PyMuPDF. + +PyMuPDF is free software: you can redistribute it and/or modify it under the +terms of the GNU Affero General Public License as published by the Free +Software Foundation, either version 3 of the License, or (at your option) +any later version. + +PyMuPDF is distributed in the hope that it will be useful, but WITHOUT ANY +WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more +details. + +You should have received a copy of the GNU Affero General Public License +along with MuPDF. If not, see + +Alternative licensing terms are available from the licensor. +For commercial licensing, see or contact +Artifex Software, Inc., 39 Mesa Street, Suite 108A, San Francisco, +CA 94129, USA, for further information. +""" + import typing import weakref +import io +import statistics +import collections +import bisect +from typing import List, Dict, Set try: from . import pymupdf @@ -153,119 +174,285 @@ def sort_words(words): def get_sorted_text( page: pymupdf.Page, + *, clip: rect_like = None, flags: OptInt = None, textpage: pymupdf.TextPage = None, tolerance=3, + remove_rotation=True, ) -> str: - """Extract plain text avoiding unacceptable line breaks. + """Extract text avoiding line breaks when y-coordinates do not differ. - Text contained in clip will be sorted in reading sequence. Some effort - is also spent to simulate layout vertically and horizontally. + Text contained in the clip will printed close to its visual appearance by + rearranging all characters according to their visual positions. + + Note that + - diagonal text will be ignored + - vertical text will be printed after horizontal text Args: page: pymupdf.Page + KW-Args: clip: (rect-like) only consider text inside - flags: (int) text extraction flags - textpage: pymupdf.TextPage - tolerance: (float) consider words to be on the same line if their top - or bottom coordinates do not differ more than this. - - Notes: - If a TextPage is provided, all text is checked for being inside clip - with at least 50% of its bbox. - This allows to use some "global" TextPage in conjunction with sub- - selecting words in parts of the defined TextPage rectangle. + flags: (int) text extraction flags. Use if not None making sure to + preserve ligatures and whitespace. + textpage: use if a TextPage + tolerance: (float) consider characters to be on the same line if their + bottom coordinates do not differ more than this. + remove_rotation: (bool) if True, remove page rotation Returns: - A text string in reading sequence. Left indentation of each line, - inter-line and inter-word distances strive to reflect the layout. + A text string reflecting the visual appearance as much as possible. + This includes left indentations, inter-line and inter-word distances. + Any vertical text will be printed after horizontal text. """ + if remove_rotation: + page.remove_rotation() + textout = io.BytesIO() + # accept flags if provided, but make sure we always preserve + # ligatures and whitespace + if isinstance(flags, int) and flags >= 0: + flags |= pymupdf.TEXT_PRESERVE_LIGATURES | pymupdf.TEXT_PRESERVE_WHITESPACE + else: + flags = ( + pymupdf.TEXT_PRESERVE_LIGATURES + | pymupdf.TEXT_PRESERVE_WHITESPACE + | pymupdf.TEXT_ACCURATE_BBOXES + ) + + # accept or create a textpage + if isinstance(textpage, pymupdf.TextPage): + tp = textpage + else: + tp = page.get_textpage(clip=clip, flags=flags) + + # curate clip parameter + if clip is None: + clip = page.rect + else: + clip = page.rect & clip - def line_text(clip, line): - """Create the string of one text line. + def find_line_y(values: List[int], value: int) -> int: + """Find the right row coordinate. - We are trying to simulate some horizontal layout here, too. + Args: + values: (list) y-coordinates of rows. + value: (int) lookup for this value (y-origin of char). + Returns: + y-coordinate of appropriate line for value. + """ + i = bisect.bisect_right(values, value) + if i: + return values[i - 1] + raise RuntimeError(f"Line for {value:g} not found in {values}") + + def curate_rows(rows: Set[int], tolerance) -> List: + """Select significantly different row coordinates.""" + if not rows: + return rows + rows = sorted(rows) + nrows = [rows[0]] + for y in rows[1:]: + if y >= nrows[-1] + tolerance: # only keep significant differences + nrows.append(y) + return nrows # curated list of line bottom coordinates + + def bbox_in_clip(bbox, clip): + """Check if bbox and clip intersect significantly.""" + x0, y0, x1, y1 = bbox + item_area = (x1 - x0) * (y1 - y0) + if not item_area: + return False + inter_x0 = max(x0, clip[0]) + inter_y0 = max(y0, clip[1]) + inter_x1 = min(x1, clip[2]) + inter_y1 = min(y1, clip[3]) + inter_area = max(0, inter_x1 - inter_x0) * max(0, inter_y1 - inter_y0) + return inter_area > 0.5 * item_area + + def process_blocks(blocks: List[Dict], page: pymupdf.Page, clip): + """Extract characters and row information from text blocks. Args: - clip: (pymupdf.Rect) the area from which all text is being read. - line: (list) word tuples (rect, text) contained in the line + blocks: (list) "rawdict" text blocks from the page. + page: (pymupdf.Page) the page object. Returns: - Text in this line. Generated from words in 'line'. Distance from - predecessor is translated to multiple spaces, thus simulating - text indentations and large horizontal distances. + chars: (list) all characters on the page. + rows: (set) y-coordinates of rows. + left: (float) leftmost coordinate used on the page. + right: (float) rightmost coordinate used on the page. + rowheight: (float) maximum row height encountered. """ - line.sort(key=lambda w: w[0].x0) - ltext = "" # text in the line - x1 = clip.x0 # end coordinate of ltext - lrect = pymupdf.EMPTY_RECT() # bbox of this line - for r, t in line: - lrect |= r # update line bbox - # convert distance to previous word to multiple spaces - dist = max( - int(round((r.x0 - x1) / r.width * len(t))) if r.width else 0, - 0 if (x1 == clip.x0 or r.x0 <= x1) else 1, - ) # number of space characters - - ltext += " " * dist + t # append word string - x1 = r.x1 # update new end position - return ltext - - # Extract words in correct sequence first. - words = [ - (pymupdf.Rect(w[:4]), w[4]) - for w in get_text_words( - page, - clip=clip, - flags=flags, - textpage=textpage, - sort=True, - tolerance=tolerance, - ) - ] + rows = set() + page_width = page.rect.width + page_height = page.rect.height + rowheight = page_height + left = page_width + right = 0 + chars = [] + vertical_lines = [] + for block in blocks: + if block["type"] != 0: # skip non-text blocks + continue + for line in block["lines"]: + x_dir, y_dir = line["dir"] + if x_dir != 0 and y_dir != 0: # ignore "diagonal" lines + continue + if x_dir == 0: + # vertical lines are handled separately + vertical_lines.append(line) + continue + rtl = 1 if x_dir >= 0 else -1 # mark as right to left + line_y = int(round(line["bbox"][3])) + rows.add(line_y) + # update row height + rowheight = max(rowheight, abs(line["bbox"][3] - line["bbox"][1])) + for span in line["spans"]: + if span["size"] <= tolerance: + # ignore small text + continue + for c in span["chars"]: + if not bbox_in_clip(c["bbox"], clip): + continue + x0, _, x1, _ = c["bbox"] + cwidth = abs(x1 - x0) # character width + if not c["c"].isspace(): # adjust left / right limits + left = min(left, x0) + right = max(right, x1) + cdict = { + "ch": c["c"], + "x": x0 if rtl > 0 else x1, + "y": line_y, + "w": cwidth, + "rtl": rtl, + } + chars.append(cdict) # all chars on page + return chars, rows, left, right, rowheight, vertical_lines + + def make_textline(left, slot, minslot, lchars): + """Produce the text of one output line. - if not words: # no text present + Args: + left: (float) left most coordinate used on page + slot: (float) avg width of one character in any font in use. + minslot: (float) min width for the characters in this line. + lchars: (dict) characters of this line. + Returns: + text: (str) text string for this line + """ + text = "" # we output this + old_char = "" + old_x1 = 0 # end coordinate of last char + old_ox = 0 # x-origin of last char + if minslot <= pymupdf.EPSILON: + raise RuntimeError(f"program error: minslot too small = {minslot:g}") + + for c in lchars: # loop over characters + char, ox, _, cwidth = c["ch"], c["x"], c["y"], c["w"] + ox = ox - left # its (relative) start coordinate + x1 = ox + cwidth # ending coordinate + + # eliminate overprint effect + if old_char == char and ox - old_ox <= cwidth * 0.2: + continue + + # omit spaces overlapping previous char + if char == " " and (old_x1 - ox) / cwidth > 0.8: + continue + + old_char = char + # close enough to previous? + if ox < old_x1 + minslot: # assume char adjacent to previous + text += char # append to output + old_x1 = x1 # new end coord + old_ox = ox # new origin.x + continue + + # else next char starts after some gap: + # fill in right number of spaces, so char is positioned + # in the right slot of the line + if char == " ": # rest relevant for non-space only + continue + delta = int(ox / slot) - len(text) + if ox > old_x1 and delta > 1: + text += " " * delta + # now append char + text += char + old_x1 = x1 # new end coordinate + old_ox = ox # new origin + return text.rstrip() + + # extract page text by single characters ("rawdict") + blocks = tp.extractRAWDICT()["blocks"] + chars, rows, left, right, rowheight, vertical_lines = process_blocks( + blocks, page, clip + ) + + if not chars and not vertical_lines: # no text on page return "" - totalbox = pymupdf.EMPTY_RECT() # area covering all text - for wr, text in words: - totalbox |= wr - - lines = [] # list of reconstituted lines - line = [words[0]] # current line - lrect = words[0][0] # the line's rectangle - - # walk through the words - for wr, text in words[1:]: # start with second word - w0r, _ = line[-1] # read previous word in current line - - # if this word matches top or bottom of the line, append it - if abs(lrect.y0 - wr.y0) <= tolerance or abs(lrect.y1 - wr.y1) <= tolerance: - line.append((wr, text)) - lrect |= wr - else: - # output current line and re-initialize - ltext = line_text(totalbox, line) - lines.append((lrect, ltext)) - line = [(wr, text)] - lrect = wr - - # also append unfinished last line - ltext = line_text(totalbox, line) - lines.append((lrect, ltext)) - - # sort all lines vertically - lines.sort(key=lambda l: (l[0].y1)) - - text = lines[0][1] # text of first line - y1 = lines[0][0].y1 # its bottom coordinate - for lrect, ltext in lines[1:]: - distance = min(int(round((lrect.y0 - y1) / lrect.height)), 5) - breaks = "\n" * (distance + 1) - text += breaks + ltext - y1 = lrect.y1 - - # return text in clip - return text + # compute list of line coordinates - ignoring small (tolerance) differences + rows = curate_rows(rows, tolerance) + + # Sort all chars by x-coordinates, so every line will receive char info, + # from left to right (or rtl if rotation = 180 degrees) + chars.sort(key=lambda c: c["x"] * c["rtl"]) + + # populate the lines with char info + lines = collections.defaultdict(list) # key: y coordinate, value: chars + for c in chars: + y = find_line_y(rows, c["y"]) # find the right line + lines[y].append(c) # append this char + + # ensure line coordinates are ascending + keys = list(lines.keys()) + keys.sort() + + # ------------------------------------------------------------------------- + # Compute "char resolution" for the page: the char width corresponding to + # 1 text char position on output - call it 'slot'. + # For each line, compute median of its char widths. The minimum across all + # lines is 'slot'. + # The minimum char width of each line is used to determine if spaces must + # be inserted in between two characters. + # ------------------------------------------------------------------------- + slot = right - left + minslots = {} + for y in keys: + lchars = lines[y] + ccount = len(lchars) + if ccount < 2: + minslots[y] = 1 + continue + widths = sorted([c["w"] for c in lchars]) + this_slot = statistics.median(widths) # take median value + if this_slot < slot: + slot = this_slot + minslots[y] = widths[0] + + # compute line advance in text output + if rows: + rowheight = rowheight * (rows[-1] - rows[0]) / (rowheight * len(rows)) * 1.2 + rowpos = rows[0] # first line positioned here + else: + rowheight = 0 + rowpos = 0 + for y in keys: # walk through the lines + while rowpos < y: # honor distance between lines + textout.write(b"\n") + rowpos += rowheight + text = make_textline(left, slot, minslots[y], lines[y]) + textout.write((text + "\n").encode("utf8", errors="surrogatepass")) + rowpos = y + rowheight + + for line in vertical_lines: + if not bbox_in_clip(line["bbox"], clip): + continue + line_text = " ".join( + w[4] for w in tp.extractWORDS() if bbox_in_clip(w[:4], line["bbox"]) + ) + textout.write((line_text + "\n").encode("utf8", errors="surrogatepass")) + + return textout.getvalue().decode("utf8", errors="surrogatepass") def get_textbox( From e95e371ebada04ec1f3b74078a89e4a2a34f0a0e Mon Sep 17 00:00:00 2001 From: "Jorj X. McKie" Date: Thu, 3 Dec 2026 09:24:48 -0400 Subject: [PATCH 2/2] update --- tests/resources/test_5319.pdf | Bin 0 -> 1383 bytes tests/test_textextract.py | 8 ++++++++ 2 files changed, 8 insertions(+) create mode 100644 tests/resources/test_5319.pdf diff --git a/tests/resources/test_5319.pdf b/tests/resources/test_5319.pdf new file mode 100644 index 0000000000000000000000000000000000000000..43e8c6c5223c9db3a9c95732f2588089dac30b6a GIT binary patch literal 1383 zcmah}+j7$|5PkPoEKJinKq}kuC2mV^xwIiIElIePv@z z1jt)14n)E46))+OfeA_m^Rd32p)kZh%4WhHj8!_SUOK9YTL`s)$lw8T%2G}bU|mDxI#DQ5Y)U@xV>g;5nNpmz*3siwJ{ zlwt&>7zcCxQ7W*hkm7bK=S3ArQ!%Q!6fJ|yZf$vv7rL$&yZCd1n&WRc&c@2_p>vPj zevv9Iz(xy1_rD;>SvpS`Lb$IfL*5A=E2?gx2A8E;x~x_g+~8$jvjod*E{YjTc*a?Z z=MA~e5%OGUvsh>poz1W~Nr&b|nMiY)Dr5o?1t=sMjv0gS}vVJAV9h zYg8or(W4jpr)wAE?c(_~^&@+;mQOeMg^H4QYD4UE^5)ZVueWb+XPqm%ejK&Q-lg39 zP!t zs+69&$-keuS`AW;E%)HTvq)ED5=^7@E$nfr!89(e2mC8TMi(_em0nQnI<99`D($n5 F^&8@nge(96 literal 0 HcmV?d00001 diff --git a/tests/test_textextract.py b/tests/test_textextract.py index 38cebab88..7bc4fdf39 100644 --- a/tests/test_textextract.py +++ b/tests/test_textextract.py @@ -1079,3 +1079,11 @@ def test_5218(): assert not num_errors else: assert num_errors + +def test_5319(): + path = os.path.normpath(f'{__file__}/../../tests/resources/test_5319.pdf') + doc = pymupdf.open(path) + page = doc[0] + text = page.get_text(sort=True) + assert "7,0" in text + assert "12,9" in text