# Redact PDF text, images, and patterns in Rust

Source: https://pdfluent.com/how-to/redaction/

This guide shows you how to use the PDFluent SDK to permanently remove sensitive content from your PDF documents. It is for developers who need to implement secure and compliant redaction.

**New in SDK 1.3.0:** `search_and_redact` also masks the term where the saved file quotes it outside the page: notes, bookmarks, form values, attachment names, scripts and more. Attachment contents are not searched; redact files made with earlier versions again. [Release post](https://pdfluent.com/blog/sdk-1-3-0/)

## On this page

- Permanently redact text and images from a PDF in Rust
- Redact text matching a regex pattern from a PDF in Rust
- GDPR-compliant PDF redaction in Rust

## Add PDFluent to your project

Add the pdfluent crate to Cargo.toml. No system libraries to install.

toml

```
[dependencies]
pdfluent = "1.5.0"
```

## Permanently redact text and images from a PDF in Rust

Remove sensitive content from PDF files with black-box redaction. PDFluent removes the underlying text and image data, not just paints over it.

Name and code dissolve into pixels.

rust

```
use pdfluent::{PdfDocument, RedactOptions};

fn main() -> pdfluent::Result<()> {
    let mut doc = PdfDocument::open("contract.pdf")?;
    doc.redact("CONFIDENTIAL", RedactOptions::new())?;
    doc.save("redacted.pdf")?;
    Ok(())
}
```

1. Step 1 Open the PDF documentLoad the PDF you want to redact. Use open() for files on disk or from_bytes() for in-memory data. rust `*use pdfluent::PdfDocument;**let mut doc = PdfDocument::open("sensitive_report.pdf")?;*`
2. Step 2 Redact text across the documentCall redact_text() with the exact string to remove. PDFluent searches all pages and marks every occurrence. The text is not yet removed at this step. rust `*use pdfluent::RedactOptions;**// Remove specific strings (search + redact across all pages)**doc.redact("Alice Johnson", RedactOptions::new())?;**doc.redact("account: 4111-1111-1111-1111", RedactOptions::new())?;**// Redact a page region by coordinates [x1, y1, x2, y2] (points, from bottom-left)**doc.redact_region(0, [50.0, 700.0, 300.0, 720.0])?;*`
3. Step 3 Configure the redaction fillThe default fill is solid black. You can change the fill colour or add a label such as "REDACTED" over the box. rust `*use pdfluent::RedactOptions;**// Scope a redaction to specific pages, case-insensitive**let opts = RedactOptions::new().case_sensitive(false).on_pages(&[0, 1]);**doc.redact("SSN: 123-45-6789", opts)?;*`
4. Step 4 Apply redactions and saveredact() and redact_region() have already removed the content from the data stream. This step writes the result to a file, from which the removed content cannot be recovered. rust `*// redact() / redact_region() apply in place — write the sanitised file**doc.save("report_redacted.pdf")?;**println!("All redactions applied and saved.");*`

- redact() removes text from the content stream. Simply drawing a black box does not remove the underlying text.
- Redaction applies to all pages unless you narrow it with RedactOptions::new().on_pages(&[..]).
- Scanned PDFs contain images, not text. Use redact_region() with pixel coordinates for those pages.
- Always verify the output in a PDF viewer before distributing redacted documents.

Does PDFluent actually remove the text data or just cover it?

PDFluent removes the text from the content stream and clears the glyph data from the page. redact() does that as it runs, so the document in memory is already sanitised; save() writes that state to disk.

Can I redact images as well as text?

Yes. Use redact_region() to specify a rectangle over an image. PDFluent clips and replaces the image data in that region with the fill colour. The original image bytes are removed from the PDF.

What happens if the same text appears in headers created by a PDF viewer overlay?

PDFluent operates on the PDF content streams. Viewer-level overlays (added by Acrobat as optional content groups) are separate layers, and redaction does not reach into them.

Can I undo a redaction?

No. redact() is destructive and permanent. Keep a copy of the original file before redacting.

## Redact text matching a regex pattern from a PDF in Rust

Use regular expressions to find and permanently remove credit card numbers, SSNs, email addresses, or any structured data from a PDF.

rust

```
use pdfluent::{PdfDocument, RedactOptions};

fn main() -> pdfluent::Result<()> {
    let mut doc = PdfDocument::open("data.pdf")?;
    doc.redact(r"\d{3}-\d{2}-\d{4}", RedactOptions::new().regex(true))?;
    doc.save("redacted.pdf")?;
    Ok(())
}
```

1. Step 1 Open the PDFLoad the file from disk or from an in-memory buffer. rust `*use pdfluent::PdfDocument;**let mut doc = PdfDocument::open("customer_data.pdf")?;*`
2. Step 2 Define your regex patternsWrite patterns for the data types you want to remove. PDFluent uses the Rust regex crate syntax. rust `*// Credit card: Visa, Mastercard, Amex formats**let cc_pattern = r"\b(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13})\b";**// Email addresses**let email_pattern = r"[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}";**// US phone numbers**let phone_pattern = r"\b\(?\d{3}\)?[\s.\-]?\d{3}[\s.\-]?\d{4}\b";*`
3. Step 3 Apply pattern-based redactionCall redact() once per regex, with RedactOptions::new().regex(true). Each call removes its own matches as it runs; there is no separate apply step to follow them with. rust `*use pdfluent::RedactOptions;**let opts = RedactOptions::new().regex(true);**doc.redact(cc_pattern, opts.clone())?;**doc.redact(email_pattern, opts.clone())?;**doc.redact(phone_pattern, opts)?;*`
4. Step 4 Apply and saveredact() has already removed every match from the content stream. This step writes that document to disk. rust `*// Pattern redactions apply in place — write the cleaned file**doc.save("customer_data_clean.pdf")?;**println!("Pattern redaction complete.");*`

- PDFluent uses the Rust regex crate. Patterns are case-sensitive by default. Use (?i) for case-insensitive matching.
- Text in PDFs may include ligatures or kerning gaps. If a pattern does not match expected text, extract the raw text first to inspect the actual character sequence.
- Pattern redaction works on text content streams only. Text inside images requires OCR before redaction.
- There is no preview: redact() removes its matches as it runs. Run the same regex over doc.text()? first if you want to see what it will match.

How do I preview matches before permanently removing them?

Not from the redaction API — it has no preview stage, and a redaction is applied by the same call that finds the match. Extract the text with doc.text()? and run the same regex over it to see what would match before you redact.

Can I redact patterns on a specific page only?

Yes. Name the pages in the options: doc.redact(pattern, RedactOptions::new().regex(true).on_pages(&[1]))?.

What if the regex matches text that spans a line break?

PDF text tokens do not always align with visual lines. PDFluent reassembles token sequences before matching, so patterns can span tokens. Line breaks within a match are handled transparently.

Does PDFluent support PCRE features like lookaheads?

PDFluent uses the Rust regex crate, which does not support PCRE lookaheads or backreferences. For complex patterns, extract text first and compute match offsets manually, then pass bounding boxes to redact_region().

## GDPR-compliant PDF redaction in Rust

Permanently remove personal data from PDF content streams — not just visually. A black-box overlay leaves text extractable; PDFluent removes it from the object layer.

rust

```
use pdfluent::{PdfDocument, RedactOptions};

fn main() -> pdfluent::Result<()> {
    let mut doc = PdfDocument::open("records.pdf")?;
    doc.redact("john.doe@example.com", RedactOptions::new())?;
    doc.redact_region(0, [72.0, 700.0, 320.0, 720.0])?;
    doc.save("redacted.pdf")?;
    Ok(())
}
```

1. Step 1 Identify what needs to be redactedDetermine which personal data is present in the document. PDFluent supports regex-based pattern matching, manual region selection, and full-text search. Common patterns include social security numbers, names, email addresses, phone numbers, and financial identifiers. rust `*use pdfluent::{PdfDocument, RedactOptions};**let mut doc = PdfDocument::open("contract_with_pii.pdf")?;**// Regex match — redact all occurrences across all pages**let re = RedactOptions::new().regex(true);**doc.redact(r"\b[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}\b", re.clone())?; // email**doc.redact(r"\b\d{3}-\d{2}-\d{4}\b", re.clone())?; // US SSN**doc.redact(r"\b\d{4}[\s\-]?\d{4}[\s\-]?\d{4}[\s\-]?\d{4}\b", re)?; // credit card*`
2. Step 2 Redact a region by coordinateThere is no marking stage. redact_region() removes the content of the rectangle as it runs, and redact() removes every match of the text or pattern you give it. Check the coordinates or the pattern before you call them, because there is nothing left to review afterwards. rust `*// Redact a specific region by coordinates [x1, y1, x2, y2] (page index first)**doc.redact_region(0, [72.0, 600.0, 300.0, 620.0])?;**// Or redact an exact text string**doc.redact("Jan de Vries", pdfluent::RedactOptions::new())?;*`
3. Step 3 Apply redactions: permanently removes content from the content streamredact() and redact_region() modify the PDF content stream directly. Text and image data in the redacted regions is removed from the object layer, not just hidden. The content cannot be recovered afterwards, even by a PDF parser operating on the raw bytes. rust `*use pdfluent::RedactOptions;**// RedactOptions controls matching. redact() / redact_region() mutate the**// document in place — there is no separate "apply" step.**let _opts = RedactOptions::new().case_sensitive(false).regex(true);*`
4. Step 4 Verify: confirm the content is goneAfter applying redactions, extract the text and check that the personal data is absent. This step is important for audit purposes and to confirm the redaction worked as intended before delivering or storing the document. rust `*// Verify: extracted text must not contain the redacted values**let text = doc.text()?;**assert!(!text.contains("Jan de Vries"), "Redaction failed: name still present");**assert!(!text.contains("123-45-6789"), "Redaction failed: SSN still present");**println!("Verification passed — PII removed from content stream");*`
5. Step 5 Clear metadata and save to a new filePDF metadata (Author, Title, Subject, Keywords) and XMP metadata may contain PII independently of the page content. Clear it before saving. Keep the original file for your audit trail if required by your data retention policy. rust `*// Clear document Info metadata that may carry PII**doc.metadata_mut().set_title("").set_author("").set_subject("").commit()?;**// Save to a new path — keep the original for audit**doc.save("contract_redacted.pdf")?;**println!("Redacted document saved.");*`

- Redaction via redact() is irreversible. Always work on a copy of the original document.
- A black rectangle drawn as a PDF annotation or content stream overlay does NOT constitute GDPR-compliant redaction. The underlying text remains in the content stream and can be extracted with any PDF parser.
- Annotations, bookmarks, form fields, and JavaScript may also contain PII. Review these separately after redacting page content.
- GDPR Article 17 requires erasure "without undue delay" — in practice, supervisory authorities interpret this as within one month of a valid request.
- For CCPA compliance (California Consumer Privacy Act), the same principle applies: visual hiding is not deletion. Use redact() to permanently remove data from the content layer.

Why is a black box overlay not GDPR compliant?

A visual overlay — whether drawn as a filled rectangle in the content stream or as an annotation — only hides text in the rendered view. The underlying text operators remain in the PDF content stream and can be extracted by any PDF parser, including simple command-line tools. GDPR Article 17 requires that the data be erased, not merely hidden. PDFluent's redact() removes the text from the content stream itself.

Does PDFluent's redaction permanently remove the text?

Yes. redact() modifies the PDF content stream directly, removing the text and image drawing operators for every match. The data is not present in the saved file at any layer. It cannot be recovered by removing an overlay or parsing the raw PDF bytes.

Does GDPR require immediate deletion or can I process redactions in bulk?

GDPR Article 17 requires erasure "without undue delay." The European Data Protection Board guidance indicates this generally means within one month of receiving a valid erasure request. Bulk processing workflows are acceptable as long as redactions are completed within that window.

What about metadata, bookmarks, and annotations that may contain PII?

Page content redaction does not affect document metadata (Author, Creator, Subject), XMP metadata, bookmarks, annotations, or embedded attachments. Call doc.clear_metadata() to remove document-level metadata. Review annotations and bookmarks separately — PDFluent provides doc.annotations() and doc.bookmarks() iterators to inspect and remove these.
