Skip to content

Commit 1833358

Browse files
committed
Access pdf annotations while inside pikepdf.Pdf context manager.
Depending on the exact way the pdf file is written, iterating over Annots can fail after the file has been closed. This is not the case for matplotlib-generated pdfs, but is the case for mplcairo-generated ones. As a simple repro of the different behavior between "in-the-contextmanager" and "out-of-the-contextmanager": ``` from matplotlib import pyplot as plt plt.figtext(.5, .5, "hello, world", url="https://www.google.com") plt.savefig("/tmp/test.pdf", backend="pdf") import pikepdf with pikepdf.Pdf.open("/tmp/test.pdf") as pdf: page = pdf.pages[0] print(repr(page.Annots)) # within contextmanager: ok with pikepdf.Pdf.open("/tmp/test.pdf") as pdf: page = pdf.pages[0] print(repr(page.Annots)) # after contextmanager: AttributeError ```
1 parent 7b3ac93 commit 1833358

File tree

1 file changed

+17
-13
lines changed

1 file changed

+17
-13
lines changed

lib/matplotlib/tests/test_backend_pdf.py

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -227,13 +227,15 @@ def test_text_urls():
227227
with pikepdf.Pdf.open(fd) as pdf:
228228
annots = pdf.pages[0].Annots
229229

230-
for y, fragment in [('0.1', 'plain'), ('0.4', 'mathtext')]:
231-
annot = next(
232-
(a for a in annots if a.A.URI == f'{test_url}{fragment}'),
233-
None)
234-
assert annot is not None
235-
# Positions in points (72 per inch.)
236-
assert annot.Rect[1] == decimal.Decimal(y) * 72
230+
# Iteration over Annots must occur within the context manager,
231+
# otherwise it may fail depending on the pdf structure.
232+
for y, fragment in [('0.1', 'plain'), ('0.4', 'mathtext')]:
233+
annot = next(
234+
(a for a in annots if a.A.URI == f'{test_url}{fragment}'),
235+
None)
236+
assert annot is not None
237+
# Positions in points (72 per inch.)
238+
assert annot.Rect[1] == decimal.Decimal(y) * 72
237239

238240

239241
@needs_usetex
@@ -251,12 +253,14 @@ def test_text_urls_tex():
251253
with pikepdf.Pdf.open(fd) as pdf:
252254
annots = pdf.pages[0].Annots
253255

254-
annot = next(
255-
(a for a in annots if a.A.URI == f'{test_url}tex'),
256-
None)
257-
assert annot is not None
258-
# Positions in points (72 per inch.)
259-
assert annot.Rect[1] == decimal.Decimal('0.7') * 72
256+
# Iteration over Annots must occur within the context manager,
257+
# otherwise it may fail depending on the pdf structure.
258+
annot = next(
259+
(a for a in annots if a.A.URI == f'{test_url}tex'),
260+
None)
261+
assert annot is not None
262+
# Positions in points (72 per inch.)
263+
assert annot.Rect[1] == decimal.Decimal('0.7') * 72
260264

261265

262266
def test_pdfpages_fspath():

0 commit comments

Comments
 (0)