Skip to content
Merged
13 changes: 13 additions & 0 deletions changes.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,19 @@
Change Log
==========


**Changes in next version**

Fixed issues:

* **Fixed** `4755 <https://github.com/pymupdf/PyMuPDF/issues/4755>`_: Unexpected behavior of annot.set_rect() with carets and strikeouts

Other:

* Modified return value from `Annot.rect` attribute.
* Added `Annot.bounds` attribute.


**Changes in version 2.2** (2026-11-26)

New features:
Expand Down
18 changes: 18 additions & 0 deletions docs/annot.rst
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ There is a parent-child relationship between an annotation and its page. If the
:meth:`Annot.update` apply accumulated annot changes
:attr:`Annot.blendmode` annotation BlendMode
:attr:`Annot.border` border details
:attr:`Annot.bounds` the boundary rect.
:attr:`Annot.colors` border / background and fill colors
:attr:`Annot.file_info` get attached file information
:attr:`Annot.flags` annotation flags
Expand Down Expand Up @@ -460,6 +461,18 @@ There is a parent-child relationship between an annotation and its page. If the
The rectangle containing the annotation.

:rtype: :ref:`Rect`

* Changed in version 2.3:

* The returned rect is now consistent with the rect set by `set_rect()`.
* It may differ slightly from earlier versions:

* Internally we now use ``pdf_annot_rect()`` instead of ``pdf_bound_annot()``.
* This applies the same (usually small) ``pdf_annot_rect_diff()`` correction as `set_rect()`.
* Some attributes are defined by quads so do not have a rect attribute (e.g. StrikeOut).
In this case we return the bounds rect.

* Also see the (new in 2.3) `bound` attribute.

.. attribute:: next

Expand Down Expand Up @@ -579,6 +592,11 @@ There is a parent-child relationship between an annotation and its page. If the

:rtype: dict

.. attribute:: bounds

The attribute's boundary rect.

:rtype: :ref:`Rect`

.. _mupdficons:

Expand Down
16 changes: 8 additions & 8 deletions docs/samples/new-annots.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
def print_descr(annot):
"""Print a short description to the right of each annot rect."""
annot.parent.insert_text(
annot.rect.br + (10, -5), f"{annot.type[1]} annotation", color=red)
annot.bounds.br + (10, -5), f"{annot.type[1]} annotation", color=red)


doc = pymupdf.open()
Expand All @@ -70,13 +70,13 @@ def print_descr(annot):
annot.update(text_color=blue, fill_color=gold)
print_descr(annot)

r = annot.rect + displ
r = annot.bounds + displ
annot = page.add_text_annot(r.tl, t1)
print_descr(annot)

# Adding text marker annotations:
# first insert a unique text, then search for it, then mark it
pos = annot.rect.tl + displ.tl
pos = annot.bounds.tl + displ.tl
page.insert_text(
pos, # insertion point
highlight, # inserted text
Expand All @@ -86,25 +86,25 @@ def print_descr(annot):
annot = page.add_highlight_annot(rl[0])
print_descr(annot)

pos = annot.rect.bl # next insertion point
pos = annot.bounds.bl # next insertion point
page.insert_text(pos, underline, morph=(pos, pymupdf.Matrix(-10)))
rl = page.search_for(underline, quads=True)
annot = page.add_underline_annot(rl[0])
print_descr(annot)

pos = annot.rect.bl
pos = annot.bounds.bl
page.insert_text(pos, strikeout, morph=(pos, pymupdf.Matrix(-15)))
rl = page.search_for(strikeout, quads=True)
annot = page.add_strikeout_annot(rl[0])
print_descr(annot)

pos = annot.rect.bl
pos = annot.bounds.bl
page.insert_text(pos, squiggled, morph=(pos, pymupdf.Matrix(-20)))
rl = page.search_for(squiggled, quads=True)
annot = page.add_squiggly_annot(rl[0])
print_descr(annot)

pos = annot.rect.bl
pos = annot.bounds.bl
r = pymupdf.Rect(pos, pos.x + 75, pos.y + 35) + (0, 20, 0, 20)
annot = page.add_polyline_annot([r.bl, r.tr, r.br, r.tl]) # 'Polyline'
annot.set_border(width=0.3, dashes=[2])
Expand Down Expand Up @@ -147,7 +147,7 @@ def print_descr(annot):
annot = page.add_file_annot(
r.tl, b"just anything for testing", "testdata.txt" # 'FileAttachment'
)
print_descr(annot) # annot.rect
print_descr(annot) # annot.bounds

r += displ
annot = page.add_stamp_annot(r, stamp=10) # 'Stamp'
Expand Down
42 changes: 32 additions & 10 deletions src/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,13 @@ def __init__(self):
self.small_glyph_heights = 0
self.subset_fontnames = 0
self.skip_quad_corrections = 0

# We default to making Annot.rect fallback to Annot.bounds if
# pdf_annot_rect() raises an exception.
#
# However this is set to false when running tests, so that we don't
# rely on it in our code (see conftest.py).
self.annot_rect_fallback = True

_globals = _Globals()

Expand Down Expand Up @@ -900,6 +907,14 @@ def border(self):
ao = mupdf.pdf_annot_obj(self.this)
ret = JM_annot_border(ao)
return ret

@property
def bounds(self):
val = mupdf.pdf_bound_annot(self.this)
val = Rect(val)
p = self.get_parent()
val *= p.derotation_matrix
return val

def clean_contents(self, sanitize=1):
"""Clean appearance contents stream."""
Expand Down Expand Up @@ -1279,11 +1294,18 @@ def popup_xref(self):
@property
def rect(self):
"""annotation rectangle"""
if g_use_extra:
val = extra.Annot_rect3( self.this)
else:
val = mupdf.pdf_bound_annot(self.this)
val = Rect(val)
try:
if g_use_extra:
val = extra.Annot_rect3( self.this)
else:
val = mupdf.pdf_annot_rect(self.this)
val = Rect(val)
except Exception as e:
if _globals.annot_rect_fallback:
warnings.warn(f'Annot.rect: using annot bounds because no rect available: {e}')
return self.bounds
else:
raise

# Caching self.parent_() reduces 1000x from 0.07 to 0.04.
#
Expand Down Expand Up @@ -1816,7 +1838,7 @@ def color_string(cs, code):
TOOLS._le_slash)
le_funcs_range = range(1, len(le_funcs))
d = 2 * max(1, self.border["width"])
rect = self.rect + (-d, -d, d, d)
rect = self.bounds + (-d, -d, d, d)
ap_updated = True
points = self.vertices
if line_end_le in le_funcs_range:
Expand Down Expand Up @@ -1858,18 +1880,18 @@ def color_string(cs, code):
if rot == -1: # nothing to change
return

M = (self.rect.tl + self.rect.br) / 2 # center of annot rect
M = (self.bounds.tl + self.bounds.br) / 2 # center of annot rect

if rot == 0: # undo rotations
if abs(apnmat - Matrix(1, 1)) < 1e-5:
return # matrix already is a no-op
quad = self.rect.morph(M, ~apnmat) # derotate rect
quad = self.bounds.morph(M, ~apnmat) # derotate rect
self.set_rect(quad.rect)
self.set_apn_matrix(Matrix(1, 1)) # appearance matrix = no-op
return

mat = Matrix(rot)
quad = self.rect.morph(M, mat)
quad = self.bounds.morph(M, mat)
self.set_rect(quad.rect)
self.set_apn_matrix(apnmat * mat)

Expand Down Expand Up @@ -12557,7 +12579,7 @@ def remove_rotation(self):
state = {
"annot": annot,
"type": annot_type,
"rect": Rect(annot.rect),
"rect": Rect(annot.bounds),
"apn_matrix": Matrix(annot.apn_matrix),
}
if annot_type == mupdf.PDF_ANNOT_FREE_TEXT:
Expand Down
4 changes: 2 additions & 2 deletions src/extra.i
Original file line number Diff line number Diff line change
Expand Up @@ -1090,13 +1090,13 @@ JM_py_from_quad(fz_quad q)
//----------------------------------------------------------------
static mupdf::FzRect Annot_rect(mupdf::PdfAnnot& annot)
{
mupdf::FzRect rect = mupdf::pdf_bound_annot(annot);
mupdf::FzRect rect = mupdf::pdf_annot_rect(annot);
return rect;
}

static PyObject* Annot_rect3(mupdf::PdfAnnot& annot)
{
fz_rect rect = mupdf::ll_pdf_bound_annot(annot.m_internal);
fz_rect rect = mupdf::ll_pdf_annot_rect(annot.m_internal);
return JM_py_from_rect(rect);
}

Expand Down
6 changes: 5 additions & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,11 @@ def get_members(a):
v = getattr(a, n)
ret[n] = v
return ret


# We test without Annot.rect fallback to Annot.bounds, so that we avoid
# relying on the fallback in the main code and in tests.
pymupdf._globals.annot_rect_fallback = False

# Allow post-test checking that pymupdf._globals has not changed.
_globals_pre = get_members(pymupdf._globals)

Expand Down
55 changes: 50 additions & 5 deletions tests/test_annots.py
Original file line number Diff line number Diff line change
Expand Up @@ -682,6 +682,8 @@ def test_4755():
path = os.path.normpath(f'{__file__}/../../tests/resources/test_4755.pdf')
path_out = os.path.normpath(f'{__file__}/../../tests/test_4755_out.pdf')

errors = list()
bounds = list()
with pymupdf.open(path) as document:
for page_i, page in enumerate(document):
print(f'{page_i=}')
Expand All @@ -694,9 +696,30 @@ def test_4755():
]
for annot_i, annot in enumerate(page.annots()):
print(f'{annot_i=}')
#if annot_i != 2:
# continue
before_rect = copy.deepcopy(annot.rect)
bounds.append(annot.bounds)
e = None

try:
before_rect = copy.deepcopy(annot.rect)
except Exception as ee:
e = ee
print(f'{annot_i=} {e=}')
if annot_i == 0:
assert e and 'StrikeOut annotations have no Rect property' in str(e), (
f'Did not receive expected exception with {annot_i=}.'
)

# Check that setting pymupdf._globals.annot_rect_fallback to true allows
# annot.rect to succeed.
#
assert not pymupdf._globals.annot_rect_fallback
pymupdf._globals.annot_rect_fallback = True
before_rect = copy.deepcopy(annot.rect)
pymupdf._globals.annot_rect_fallback = False

continue
else:
assert not e, f'Received unexpected exception with {annot_i=}: {e}'

def draw_rectangle(rect, c, w):
drect = page.add_freetext_annot(rect, str(annot_i), text_color=c)
Expand All @@ -707,17 +730,39 @@ def draw_rectangle(rect, c, w):
print(f'{colour=}')
draw_rectangle(annot.rect, colour, .3)

print(f'before: {annot.rect}=')
print(f'before: {annot.rect=}')
annot.set_rect(annot.rect)
print(f' after: {annot.rect}=')
print(f' after: {annot.rect=}')

print(f'difference: {annot.rect-before_rect=}')
errors.append(annot.rect != before_rect)

draw_rectangle(annot.rect, (0, 1, 0), .3)
print()
document.save(path_out)
print(f' {path=}.')
print(f'{path_out=}.')

print(f'Bounds:')
for i, r in enumerate(bounds):
print(f' {i}: {r}')

bounds_expected = [
pymupdf.Rect(177.4219970703125, 119.0980224609375, 187.93299865722656, 127.93499755859375),
pymupdf.Rect(185.28199768066406, 123.5159912109375, 190.58399963378906, 132.35302734375),
pymupdf.Rect(49.0, 50.5, 69.0, 64.5),
]
print(f'Bounds rms:')
assert len(bounds) == len(bounds_expected)
for i, (bounds_rect_expected, bounds_rect) in enumerate(zip(bounds_expected, bounds, strict=True)):
rms = gentle_compare.rms(bounds_rect_expected, bounds_rect)
print(f' {i}: {rms=}')
assert rms < 0.1
assert bounds == bounds_expected

print(f'{errors=}')
# Expect the current broken behaviour.
assert errors == [False, False]


def test_4944():
Expand Down
13 changes: 10 additions & 3 deletions tests/test_remove-rotation.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

import pymupdf

from gentle_compare import gentle_compare, rms
import gentle_compare


scriptdir = os.path.dirname(__file__)
Expand Down Expand Up @@ -35,7 +35,7 @@ def test_remove_rotation():
words1 = doc[i].get_text("words")
words1.sort(key=lambda w: w[4]) # sort by word strings
assert pix1.digest == pix0.digest, f"{pix1.digest}/{pix0.digest}"
assert gentle_compare(words0, words1)
assert gentle_compare.gentle_compare(words0, words1)


def test_5077():
Expand Down Expand Up @@ -151,7 +151,14 @@ def test_5059():
pix_orig = page.get_pixmap(colorspace=pymupdf.csGRAY)
page.remove_rotation()
pix_rot0 = page.get_pixmap(colorspace=pymupdf.csGRAY)
rms_val = rms(pix_orig.samples, pix_rot0.samples, verbose=False)

path = os.path.relpath(os.path.normpath(f'{__file__}/../../tests/test_5059'))
pix_orig.save(f'{path}_orig.png')
pix_rot0.save(f'{path}_rot0.png')
pix_diff = gentle_compare.pixmaps_diff(pix_orig, pix_rot0)
pix_diff.save(f'{path}_diff.png')

rms_val = gentle_compare.rms(pix_orig.samples, pix_rot0.samples, verbose=False)
assert rms_val < 0.05, f"RMS diff for rotation {rot}: {rms_val}"


Expand Down
Loading