From 785438a743e69632df44073a47aa6cbf8fca7bba Mon Sep 17 00:00:00 2001 From: "Jorj X. McKie" Date: Mon, 30 Nov 2026 12:02:37 -0400 Subject: [PATCH] Fixes #5319 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We previously used separate code in method variant `page.get_text(sort=True)´ to achieve text output as close as possible to the visual appearance. This change replaces the code by instead invoking the CLI command `pymupdf gettext -mode layout`. This entailed adding a new "clip" keyword parameter to the respective function, which is only reachable in the programming API. --- changes.txt | 61 +++++++++--------- src/__main__.py | 4 +- src/utils.py | 132 ++++++++++----------------------------- tests/test_linebreaks.py | 3 +- 4 files changed, 71 insertions(+), 129 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/__main__.py b/src/__main__.py index 658ef4f1f..bd30f823c 100644 --- a/src/__main__.py +++ b/src/__main__.py @@ -582,7 +582,7 @@ def page_blocksort(page, textout, GRID, fontsize, noformfeed, skip_empty, flags) return -def page_layout(page, textout, GRID, fontsize, noformfeed, skip_empty, flags): +def page_layout(page, textout, GRID, fontsize, noformfeed, skip_empty, flags, clip=None): eop = b"\n" if noformfeed else bytes([12]) # -------------------------------------------------------------------- @@ -742,7 +742,7 @@ def make_textline(left, slot, minslot, lchars): return text.rstrip() # extract page text by single characters ("rawdict") - blocks = page.get_text("rawdict", flags=flags)["blocks"] + blocks = page.get_text("rawdict", flags=flags, clip=clip)["blocks"] chars, rows, left, right, rowheight = process_blocks(blocks, page) if chars == []: diff --git a/src/utils.py b/src/utils.py index 34b67b849..2b2b9f649 100644 --- a/src/utils.py +++ b/src/utils.py @@ -1,11 +1,27 @@ -# ------------------------------------------------------------------------ -# 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 @@ -167,105 +183,25 @@ def get_sorted_text( page: pymupdf.Page clip: (rect-like) only consider text inside flags: (int) text extraction flags - textpage: pymupdf.TextPage + textpage: deprecated and ignored here tolerance: (float) consider words to be on the same line if their top or bottom coordinates do not differ more than this. + clip: (rect-like) only consider text inside 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. + This method makes available a function of the CLI version as implemented + in module __main__.py. Returns: A text string in reading sequence. Left indentation of each line, inter-line and inter-word distances strive to reflect the layout. """ - - def line_text(clip, line): - """Create the string of one text line. - - We are trying to simulate some horizontal layout here, too. - - Args: - clip: (pymupdf.Rect) the area from which all text is being read. - line: (list) word tuples (rect, text) contained in the line - 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. - """ - 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, - ) - ] - - if not words: # no text present - 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 + from .__main__ import page_layout + import io + + textout = io.BytesIO() + page_layout(page, textout, tolerance, tolerance, True, False, flags, clip=clip) + return textout.getvalue().decode("utf-8") def get_textbox( diff --git a/tests/test_linebreaks.py b/tests/test_linebreaks.py index 3085faa25..e4bad2614 100644 --- a/tests/test_linebreaks.py +++ b/tests/test_linebreaks.py @@ -11,6 +11,7 @@ def test_linebreaks(): tp = page.get_textpage(flags=pymupdf.TEXTFLAGS_WORDS) word_count = len(page.get_text("words", textpage=tp)) line_count1 = len(page.get_text(textpage=tp).splitlines()) - line_count2 = len(page.get_text(sort=True, textpage=tp).splitlines()) + # the new full layout mode has front and back additional line breaks + line_count2 = len(page.get_text(sort=True, textpage=tp).splitlines()) - 2 assert word_count == line_count1 assert line_count2 < line_count1 / 2