Description
There appears to be an interaction between pymupdf and pymupdf4llm that affects text replacement using PyMuPDF redaction annotations.
The replacement code itself uses only pymupdf. It does not call pymupdf4llm.
The same PyMuPDF replacement operation behaves differently depending on whether pymupdf4llm has been imported in the Python process.
Versions
I installed latest versions and some other versions with same problem.
pymupdf v1.26.7 and v1.27.1pymupdf4llm v0.2.9 and v0.3.4pymupdf v1.26.7 and v1.27.1
Observed behavior
With only pymupdf imported:
- The target text is found.
- The redaction annotation is applied.
- The replacement text is inserted correctly.
After importing pymupdf4llm:
- The same replacement code is executed.
- For the attached PDF, the original text is removed. input.pdf (11.6 KB)
- The replacement text is NOT inserted.
This is particularly problematic because the operation does not raise an exception; it result in silent data loss.
NOTE: For PDFs that I created using save as PDF from Word, this didn’t happened. This PDF and many others I have are generated using a proprietary software in Neurology field and I am unaware of the back-end PDF engine they use. The PDF opens perfectly fine in windows, Not sure what is specific about this PDF files.
Minimal reproducer
The following script demonstrates the issue with the attached PDF.
import pymupdf
INPUT = r"input.pdf"
ORIGINAL_TEXT = "3/4/2017"
REPLACEMENT_TEXT = "3/4/2037"
def test(label: str) -> None:
print()
print("=" * 70)
print(label)
print("=" * 70)
with pymupdf.open(INPUT) as doc:
page = doc[0]
for x0, y0, x1, y1, text, *_ in page.get_text("words"):
if text != ORIGINAL_TEXT:
continue
print("WORD: ", repr(text))
print("RECT: ", (x0, y0, x1, y1))
print("HEIGHT: ", y1 - y0)
rect = pymupdf.Rect(x0, y0, x1, y1)
page.add_redact_annot(
rect,
text=REPLACEMENT_TEXT,
fontname="helv",
fontsize=8,
fill=None,
text_color=(0, 0, 0),
cross_out=False,
)
page.apply_redactions()
result = page.get_text()
replacement_found = REPLACEMENT_TEXT in result
original_found = ORIGINAL_TEXT in result
print(
f" {'✅' if replacement_found else '❌'} "
f"Replacement present: {replacement_found}"
)
print(
f" {'❌' if original_found else '✅'} "
f"Original still present: {original_found}"
)
return
# ---------------------------------------------------------------------------
# 1. Baseline: PyMuPDF only
# ---------------------------------------------------------------------------
test("1. PyMuPDF only")
# ---------------------------------------------------------------------------
# 2. Import PyMuPDF4LLM and perform exactly the same operation
# ---------------------------------------------------------------------------
import pymupdf4llm
test("2. After importing PyMuPDF4LLM")
