Drawing a black box over text in a PDF does not hide the text. The words are still in the file. Copy and paste, search, or a PDF-to-text tool will return them. Several public leaks happened this way.
Real redaction removes the data. Here is how to do it with PyMuPDF.
The wrong way
Open a PDF editor, draw a black rectangle over a name, save. The page looks fine. Now run:
import fitz
page = fitz.open("covered.pdf")[0]
print(page.get_text())
The name prints. The rectangle is a separate drawing on top of the text.
The right way: mark, then apply
PyMuPDF uses two steps. You add redaction annotations, then apply them. The apply step deletes what is under each one.
import fitz
doc = fitz.open("contract.pdf")
for page in doc:
for hit in page.search_for("Jane Doe"):
page.add_redact_annot(hit, fill=(0, 0, 0))
page.apply_redactions()
doc.save("contract_redacted.pdf")
search_for returns a list of rectangles, one per match. fill=(0, 0, 0) paints the box black. apply_redactions() removes the text under the box, and also the parts of any image under it.
Run get_text() on the saved file. The name is gone.
Redact by area
If the secret is in an image or you know where it sits, use a rectangle in points from the top left of the page:
rect = fitz.Rect(100, 100, 300, 150)
page.add_redact_annot(rect, fill=(0, 0, 0))
page.apply_redactions()
Clip the rectangle to the page first. A box that runs past the edge should be cut to the page, not rejected:
rect = rect & page.rect
Check the result
Do not trust your eyes. After saving, search the output for the text you removed:
out = fitz.open("contract_redacted.pdf")
assert not any(p.search_for("Jane Doe") for p in out)
Also check metadata. The title and author fields can hold names too. Redaction does not touch them.
Things that still leak
- Text in a different spelling or case than your search. Test variants.
- Names in the document metadata.
- Earlier versions inside the file, if it was saved with incremental updates. Save a fresh copy, not an incremental one.
- Bookmarks and form fields.
No code option
The redact tool on PDF Workshop lets you draw areas or enter a text pattern, and applies the redaction so the content is removed from the file. Check the output with a text search before you send it.
A black box is a drawing. Redaction is a delete. Only the second one protects you.
Top comments (0)