# PDF PII Redactor — GDPR Document Redaction (`perryay/pdf-pii-redactor`) Actor

Enterprise-grade GDPR PDF redaction. Checksum-validated detectors (Luhn, mod-97, NHS) for emails, cards, IBANs, SSNs, NHS numbers, IPs. Permanent black-bar redaction via PyMuPDF, privacy-first masked dataset. Audit-only, redact, batch modes. Per-success charging. Ideal for GDPR SAR.

- **URL**: https://apify.com/perryay/pdf-pii-redactor.md
- **Developed by:** [Perry AY](https://apify.com/perryay) (community)
- **Categories:** Developer tools
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.04 / actor start

This Actor is paid per event and usage. You are charged both the fixed price for specific events and for Apify platform usage.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## PDF PII Redactor 🛡️ — GDPR Document Redaction

**Checksum-validated PII detection and permanent black-bar redaction for PDF documents — emails, phones, IBANs, credit cards, SSNs, UK NHS numbers and IP addresses, with an audit-only mode and a privacy-first dataset that never contains raw PII.**

PDF PII Redactor downloads PDFs from URLs you provide, scans every page's text layer with regex detectors gated by mathematical checksums (Luhn for payment cards, mod-97 for IBANs, the weighted checksum for UK NHS numbers), and produces permanently redacted PDFs in the Apify Key-Value Store. The dataset gets one audit trail of findings — category, page, occurrence count and a masked preview — never the raw sensitive text.

The differentiator is false-positive control. Most redaction tools blacklist keywords and redact anything that looks like a digit string. This actor validates every candidate: a 16-digit number that fails the Luhn check is not a card, an IBAN-looking string that fails mod-97 is not an IBAN, a 10-digit sequence that fails the NHS weighted checksum is not an NHS number. Fewer false positives means fewer black bars over harmless numbers and a dataset your compliance team can trust.

***

### ✨ Features

- **8 detector categories out of the box** — email, international phone (+852/+44/+1/+86), IBAN, credit card, SSN, UK NHS number, IPv4 and IPv6, each with the appropriate checksum gate where one exists.
- **Checksum-validated detection** — Luhn (cards), mod-97 ISO 7064 (IBANs), weighted checksum (NHS), octet range (IPv4), stdlib parser (IPv6). Clock times like `10:30:45` are not flagged as IPv6.
- **Permanent black-bar redaction** — PyMuPDF redaction annotations with `apply_redactions()`: the sensitive text is removed from the content stream, not merely covered.
- **Audit-only mode** — detect and count without producing PDFs (cheapest; no `page-redact` charges).
- **Privacy-first dataset** — finding rows carry category, page, count and a masked preview (first character + asterisks). Raw PII never leaves the actor. Disable previews entirely with `mask_preview=false`.
- **Custom regex detectors** — add your own patterns (employee IDs, project codes) with per-pattern compile validation; invalid regexes are skipped with a warning, not a crash.
- **Strict level** — additionally flags date patterns and label-adjacent capitalised name sequences (best-effort heuristics, see limitations).
- **Batch with concurrency 3** — multiple URLs processed in parallel with per-URL error isolation; one bad download never sinks the run.
- **Honest billing** — failed downloads and parse errors are never charged; `document-scan` fires only after a PDF opens successfully.

### 🚀 Quick Start

**Input** — redact one PDF:

```json
{
  "mode": "redact",
  "urls": ["https://example.com/employee-record.pdf"]
}
```

**Output** — one finding row per document/page/category, one document row per URL, then a summary row:

```json
{
  "type": "finding",
  "url": "https://example.com/employee-record.pdf",
  "filename": "employee-record.pdf",
  "page": 1,
  "category": "email",
  "count_on_page": 3,
  "masked_preview": "j********",
  "redaction_applied": true
}
```

```json
{
  "type": "document",
  "url": "https://example.com/employee-record.pdf",
  "filename": "employee-record.pdf",
  "pages": 12,
  "findings_total": 45,
  "findings_by_category": {"email": 12, "credit_card": 4, "iban": 2, "phone": 27},
  "kvs_key": "redacted-employee-record.pdf",
  "status": "redacted",
  "error": null
}
```

```json
{
  "type": "summary",
  "documents": 1,
  "documents_failed": 0,
  "pages_scanned": 12,
  "total_findings": 45,
  "by_category": {"email": 12, "credit_card": 4, "iban": 2, "phone": 27},
  "redacted_documents": 1
}
```

The redacted PDF is stored in the default Key-Value Store under `redacted-<filename>` (download pattern: `https://api.apify.com/v2/key-value-stores/{storeId}/records/redacted-employee-record.pdf?token={token}`).

### Input Parameters

| Field | Type | Required | Default | Description |
|---|---|---|---|---|
| `mode` | select | no | `redact` | `redact` (detect + produce redacted PDF), `audit-only` (detect and count, no PDF), or `batch` (same as redact; the name documents multi-URL intent). |
| `urls` | array of strings | no | `[]` | HTTP(S) URLs of PDFs to scan. A single plain string is accepted and wrapped into a one-element array. |
| `redaction_level` | select | no | `standard` | `standard` (8 detector categories) or `strict` (adds date patterns and label-adjacent capitalised name sequences — best-effort). |
| `custom_patterns` | array of objects | no | `[]` | Extra detectors as `{name, pattern}` Python regex pairs. `name` becomes the finding category. Invalid regexes are skipped with a warning. |
| `max_pdf_mb` | number | no | `25` | Per-file size cap in MB (1–100). Larger files produce an error row and are never charged. |
| `mask_preview` | boolean | no | `true` | Include a masked preview (first character + asterisks) in finding rows. When false, the preview field is empty — raw PII is never included either way. |
| `output_redacted_pdf` | boolean | no | `true` | Write the redacted PDF to the default key-value store in redact/batch mode. When false, the run is detection-only (document status `audit_only`, no `page-redact` charges). |

All fields are optional; missing input degrades gracefully (empty URL list produces a zeroed summary, no crash).

### Output Format

**Finding row (one per document/page/category):**

| Field | Type | Description |
|---|---|---|
| `type` | string | Always `"finding"`. |
| `url` | string | Source URL. |
| `filename` | string | Filename derived from the URL. |
| `page` | integer | 1-based page number. |
| `category` | string | Detector category: `email`, `phone`, `iban`, `credit_card`, `ssn`, `nhs_uk`, `ip_address`, `date`/`label_adjacent_name` (strict), or your custom pattern name. |
| `count_on_page` | integer | Validated occurrences on that page. |
| `masked_preview` | string | First character + up to 8 asterisks of the first occurrence; empty when `mask_preview=false`. |
| `redaction_applied` | boolean | Whether black bars were actually applied for this category on this page. |

**Document row (one per URL):** `type`, `url`, `filename`, `pages`, `findings_total`, `findings_by_category`, `kvs_key` (null unless a redacted PDF was stored), `status` (`redacted`, `audit_only`, or `error`), `error` (null or the failure reason: `download failed: ...`, `processing error: ...`, `kvs write failed: ...`).

**Summary row (always last):** `type`, `documents`, `documents_failed`, `pages_scanned`, `total_findings`, `by_category`, `redacted_documents`.

### Redaction Method & Limitations

Read this section before relying on the actor for compliance workflows.

- **Text layer only.** Detection runs on the extracted text layer and redaction uses `search_for` rectangles. Scanned-image PDFs (where text is pixels) are NOT supported — they would need OCR, which is out of scope for v1.
- **No ML NER.** v1 is regex + checksum validators. It will miss PII that does not match the documented shapes (e.g. non-international phone formats, unusual IBAN layouts) and it is not a named-entity recognizer.
- **Images are not redacted.** A PII string baked into an embedded image (a scanned signature block, a screenshot) is invisible to the text-layer scan. The redacted PDF still contains the original image.
- **Strict mode is heuristic.** Date patterns and label-adjacent capitalised sequences produce best-effort findings; review them before acting. They are never checksum-validated.
- **Line-wrap gaps.** A PII string split across a line break in the PDF text layer can be missed by both detection and rectangle search.
- **Encrypted PDFs.** Password-protected PDFs are not supported (v1 accepts no password input); they typically yield zero findings or an error row depending on the encryption.
- **Redaction permanence.** `apply_redactions()` removes the underlying text from the content stream — the black bars are not a visual overlay. Always download and inspect the redacted PDF before distributing it.

### API Usage

Run the actor via the Apify API (replace `example.com` with your Apify API host and `***` with your token):

#### cURL

```bash
## Redact a PDF (black bars + redacted file in the key-value store)
curl -X POST "https://example.com/v2/acts/pdf-pii-redactor/runs" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer ***" \
  -d '{"mode":"redact","urls":["https://example.com/contract.pdf"]}'

## Audit-only: counts and masked previews, no PDF output
curl -X POST "https://example.com/v2/acts/pdf-pii-redactor/runs" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer ***" \
  -d '{"mode":"audit-only","urls":["https://example.com/hr-export.pdf"]}'

## Batch with a custom detector for employee IDs
curl -X POST "https://example.com/v2/acts/pdf-pii-redactor/runs" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer ***" \
  -d '{"mode":"batch","urls":["https://example.com/a.pdf","https://example.com/b.pdf"],"custom_patterns":[{"name":"employee_id","pattern":"EMP-\\d{6}"}]}'
```

#### Python

```python
import requests

API_TOKEN = "<APIFY_TOKEN>"
ACTOR_URL = "https://example.com/v2/acts/pdf-pii-redactor/runs"

headers = {"Content-Type": "application/json", "Authorization": f"Bearer {API_TOKEN}"}

## Launch a redaction run
response = requests.post(ACTOR_URL, headers=headers, json={
    "mode": "redact",
    "urls": ["https://example.com/legal-discovery.pdf"],
})
run_id = response.json()["id"]

## Fetch the audit dataset (masked previews only — raw PII never appears)
dataset = requests.get(
    f"https://example.com/v2/acts/pdf-pii-redactor/runs/{run_id}/dataset/items",
    headers=headers,
).json()
for row in dataset:
    if row["type"] == "finding":
        print(row["category"], row["page"], row["masked_preview"])
```

### Use Cases

1. **GDPR subject access requests (SAR)** — redact third-party PII from documents before responding to a data subject request; the dataset is the audit trail showing what was found and redacted.
2. **Legal discovery** — produce redacted bundles for opposing counsel with a per-page finding record that demonstrates systematic (not ad-hoc) redaction.
3. **HR record sharing** — strip salaries (IBANs), national insurance numbers and personal contact details from personnel files before cross-team or cross-border transfer.
4. **Healthcare document exchange** — redact patient identifiers (NHS numbers, phones, emails) from correspondence shared with insurers or researchers; checksum validation keeps clinical numeric values (doses, readings) out of the black bars.
5. **Vendor / contractor document intake** — scan inbound PDFs for PII before they hit your document management system; audit-only mode gives a cheap triage signal.

### MCP Integration

PDF PII Redactor is available as a remote MCP server. Connect with OAuth using a URL-only configuration — no client ID or secret needed in the client config:

```json
{
  "mcpServers": {
    "apify": {
      "url": "https://mcp.apify.com"
    }
  }
}
```

Alternatively, authenticate with a Bearer token:

```json
{
  "mcpServers": {
    "apify": {
      "url": "https://mcp.apify.com",
      "headers": {
        "Authorization": "Bearer YOUR_APIFY_TOKEN"
      }
    }
  }
}
```

Example prompts:

1. "Audit this PDF for PII and tell me how many emails, credit cards and NHS numbers it contains — don't produce a redacted file"
2. "Redact this contract PDF and give me the download link plus the finding counts per category"

On first connection, your browser opens to sign in to Apify and authorize access.

Learn more: https://mcp.apify.com and https://docs.apify.com/integrations/mcp

### FAQ

**Q: How does the actor avoid redacting ordinary numbers?**
A: Every high-risk category has a mathematical gate. Card numbers must pass the Luhn check, IBANs the mod-97 (ISO 7064) check, UK NHS numbers the weighted 10-2 checksum, IPv4 addresses the octet range check, and IPv6 is parsed by the standard library. A random 16-digit string that fails Luhn is left alone.

**Q: Is the redaction permanent or just a black overlay?**
A: Permanent. PyMuPDF's `apply_redactions()` removes the underlying text from the page content stream; the black bar is the visual result, not a cover-up. Download the redacted PDF and copy-paste from it to verify — the original strings are gone.

**Q: Does the dataset ever contain raw PII?**
A: No. Finding rows carry category, page, occurrence count and a masked preview (first character plus asterisks). Set `mask_preview` to false to drop even the preview. The only full-fidelity artifact is the redacted PDF itself, in the key-value store.

**Q: What happens with scanned/image-only PDFs?**
A: They produce zero or near-zero findings because there is no text layer to scan. v1 does not include OCR — this is a documented limitation, not a silent pass. Run a text-extraction sanity check on a sample page first if you are unsure.

**Q: Which phone formats are detected?**
A: International format with a leading plus and the +852, +44, +1 or +86 country codes, with flexible spacing, dashes and parentheses, gated by an 8–15 digit sanity check. Local formats without a country code are not detected in v1.

**Q: What is the difference between redact, audit-only and batch modes?**
A: `redact` detects and stores a redacted PDF per document. `audit-only` detects and counts without producing PDFs (cheapest — no `page-redact` charges). `batch` behaves like `redact` and simply signals multi-URL intent; all modes process URL lists with concurrency 3 and per-URL error isolation.

**Q: How is billing counted?**
A: One `apify-actor-start` per run, `document-scan` per successfully opened document (any mode), `page-redact` per page with redactions actually applied (redact/batch only), `audit-report` once per audit-only run with findings, and `custom-pattern-pack` once per run when custom patterns are supplied. Errors are free.

**Q: What does the document row status mean?**
A: `redacted` — PDF scanned and redacted file stored (kvs_key set). `audit_only` — scanned but no PDF produced (audit-only mode, or `output_redacted_pdf=false`). `error` — download or processing failure; see the `error` field.

**Q: How do I download a redacted PDF?**
A: The document row's `kvs_key` (e.g. `redacted-contract.pdf`) is the record key in the default key-value store: `https://api.apify.com/v2/key-value-stores/{storeId}/records/{kvs_key}?token={token}`. Keys are collision-safe — duplicate filenames get `-2`, `-3` suffixes.

**Q: Can I add detectors for my own identifier formats?**
A: Yes — `custom_patterns` takes `{name, pattern}` Python regex pairs. Patterns compile at run start; invalid regexes are skipped with a warning and never crash the run. Custom findings are charged under the same rules (they ride on `document-scan`/`page-redact`).

**Q: What does strict mode add?**
A: Date patterns (ISO, US and month-name formats) and label-adjacent capitalised name sequences (e.g. `Date of Birth: John Smith`). These are heuristics without checksums — expect some noise and review findings before downstream use.

**Q: Why was my 30 MB PDF rejected?**
A: The default `max_pdf_mb` cap is 25 MB per file, enforced on the Content-Length header and again on the streamed bytes. Raise it (max 100) or split the document. Oversized files produce an error row and are never charged.

**Q: Does it handle password-protected PDFs?**
A: Not in v1 — there is no password input. Depending on the encryption, such files yield either zero findings or an error row. Remove the password before scanning.

**Q: What resource limits apply?**
A: Default run options are 1024 MB memory and a 300-second timeout. For very large document fleets, split the URLs array across runs.

### SEO Keywords

PDF PII redactor, GDPR PDF redaction, redact PII from PDF online, PDF black bar redaction, IBAN redaction, credit card redaction PDF, NHS number redactor, SSN redaction tool, GDPR SAR document redaction, legal discovery redaction, PDF privacy compliance, audit-only PII scan, Luhn validated card detection, mod-97 IBAN validation, Apify PDF redaction actor.

# Changelog

This Actor's version history is a separate document: https://apify.com/perryay/pdf-pii-redactor/changelog.md

# Actor input Schema

## `mode` (type: `string`):

audit-only: detect without redacting (cheapest). redact: detect and produce a redacted PDF per document. batch: redact all URLs with concurrency 3.

## `urls` (type: `array`):

HTTP(S) URLs of PDF documents to scan. Max 25 MB per file (see max_pdf_mb). Failed downloads are reported as error rows and never charged.

## `redaction_level` (type: `string`):

standard: emails, phones, IBANs, cards, SSNs, NHS numbers, IPs, custom patterns. strict: additionally date patterns and label-adjacent capitalised sequences (best-effort, see README limitations).

## `custom_patterns` (type: `array`):

Additional regex detectors. Each entry needs a name (used as the category) and a Python regex pattern.

## `max_pdf_mb` (type: `number`):

Reject PDFs larger than this many megabytes. Default 25.

## `mask_preview` (type: `boolean`):

Include a masked preview (first character + asterisks) in finding rows. The dataset never contains raw PII; when disabled the preview field is empty.

## `output_redacted_pdf` (type: `boolean`):

Write the redacted PDF to the default key-value store (key: redacted-<filename>) in redact/batch mode. Disable for detection-only runs that still want per-page counts.

## Actor input object example

```json
{
  "mode": "redact",
  "urls": [
    "https://example.com/sample.pdf"
  ],
  "redaction_level": "standard",
  "custom_patterns": [],
  "max_pdf_mb": 25,
  "mask_preview": true,
  "output_redacted_pdf": true
}
```

# Actor output Schema

## `findings` (type: `string`):

One row per document/page/category: type=finding, url, filename, page, category, count_on_page, masked_preview, redaction_applied.

## `documents` (type: `string`):

One row per input URL: type=document with pages, findings_total, findings_by_category, kvs_key, status (redacted/audit_only/error) and error message.

## `summary` (type: `string`):

Single type=summary row: documents, documents_failed, pages_scanned, total_findings, by_category, redacted_documents.

## `redacted_pdfs` (type: `string`):

Redacted PDFs are stored in the default key-value store under keys like redacted-<filename>.pdf with content type application/pdf.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "mode": "redact",
    "urls": [
        "https://example.com/sample.pdf"
    ],
    "redaction_level": "standard",
    "custom_patterns": [],
    "max_pdf_mb": 25,
    "mask_preview": true,
    "output_redacted_pdf": true
};

// Run the Actor and wait for it to finish
const run = await client.actor("perryay/pdf-pii-redactor").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "mode": "redact",
    "urls": ["https://example.com/sample.pdf"],
    "redaction_level": "standard",
    "custom_patterns": [],
    "max_pdf_mb": 25,
    "mask_preview": True,
    "output_redacted_pdf": True,
}

# Run the Actor and wait for it to finish
run = client.actor("perryay/pdf-pii-redactor").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "mode": "redact",
  "urls": [
    "https://example.com/sample.pdf"
  ],
  "redaction_level": "standard",
  "custom_patterns": [],
  "max_pdf_mb": 25,
  "mask_preview": true,
  "output_redacted_pdf": true
}' |
apify call perryay/pdf-pii-redactor --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,perryay/pdf-pii-redactor"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/qOu1k66CuNWO78ZT3/builds/QOqUfJZe5RNmPSPSx/openapi.json
