Forum Discussion
How to properly redact a PDF?
You are right: drawing a black rectangle is not redaction. For a local, code-based solution, PyMuPDF supports actual PDF redaction without uploading the document.
The basic process is:
- Work on a copy. Locate sensitive text with page.search_for() and mark the matching areas using page.add_redact_annot(). Mark image areas by coordinates too. Scanned text needs local OCR or manual review because ordinary text search will miss it.
- Call page.apply_redactions() on each affected page. Adding the annotations alone does not remove content. Configure it to remove text, blank overlapping image pixels and remove overlapping vector graphics as appropriate.
- Remove remaining comments, unwanted attachments and metadata. PyMuPDF provides methods such as delete_annot(), embfile_del(), set_metadata({}) and del_xml_metadata(). Those operations are not a universal sanitizer: forms, layers and other PDF structures need separate attention.
- Save to a new file, using a full save with garbage collection, such as doc.save("redacted.pdf", garbage=4, deflate=True). Do not use an incremental save, which can retain earlier document data.
For a document with complex hidden content, a simpler security-focused option is to render the redacted pages to images and build a fresh PDF containing only those images. This avoids carrying over the original text objects, comments, forms, attachments and metadata. Rebuild from the rendered pages; merely flattening annotations or printing to PDF is not equivalent. The tradeoff is losing selectable text, accessibility information and interactive features.
Before sharing, reopen the new file and:
- Search for the removed names and addresses, and try selecting or copying around each redaction.
- Extract its text with a separate tool such as Poppler’s pdftotext.
- Inspect every page visually, including images and repeated occurrences.
- Check document properties, comments and attachments.
A failed text search alone is not proof of successful redaction—sensitive details may still be visible in images. For highly sensitive material, have someone else review the final output as well.