Check what a file hides
You’ll check a PDF for what its reader can’t see before you publish it, send it or accept it as redacted. A PDF keeps more than its pages show: every earlier revision’s text, who made it, attached files, scripts, and text drawn invisible or under a black box.
This example lists what each file holds, and every redaction that only covered its text:
//! Check what a PDF holds beyond its visible pages before you publish or send it: earlier//! revisions, metadata, attachments, scripts, form values and hidden text, and redactions that//! only covered text instead of removing it.//!//! ```sh//! cargo run -p laminapdf --features extract --example check_what_a_file_hides -- <file.pdf>…//! ```
use std::error::Error;
use laminapdf::reveal::Category;use laminapdf::{CancelToken, Document, OpenOptions};
fn main() -> Result<(), Box<dyn Error>> { let paths: Vec<String> = std::env::args().skip(1).collect(); if paths.is_empty() { return Err("usage: check_what_a_file_hides <file.pdf>…".into()); } for path in &paths { print!("{}", report(path, &what_it_hides(std::fs::read(path)?)?)); } Ok(())}
/// What a file holds beyond its visible pages.#[derive(Debug, PartialEq, Eq)]pub(crate) struct Hidden { /// The kinds of thing it holds, such as `history` or `hidden-content`, in report order. pub(crate) categories: Vec<&'static str>, /// Each place text was hidden rather than removed. pub(crate) redactions: Vec<FailedRedaction>,}
/// A warning that text was hidden rather than removed: a redaction that only covered it, or text an/// earlier revision still holds.#[derive(Debug, PartialEq, Eq)]pub(crate) struct FailedRedaction { /// Its warning code, such as `redaction-not-applied`. pub(crate) code: &'static str, /// The 0-based page it is on, when it is on one. pub(crate) page: Option<u64>,}
/// Opens `bytes` and lists what they hold beyond the visible pages.pub(crate) fn what_it_hides(bytes: Vec<u8>) -> Result<Hidden, laminapdf::Error> { let options = OpenOptions::new(); let doc = Document::open_bytes(bytes, options.clone())?; // `reveal` reads every page and every earlier revision; a server would cancel it on a // deadline through this token. let reveal = doc.reveal(&options, &CancelToken::new())?; Ok(Hidden { categories: reveal.found().into_iter().map(Category::as_str).collect(), // The same warnings `Document::redaction_warnings` gives, read from what `reveal` found. redactions: reveal .redaction_warnings() .iter() .map(|warning| FailedRedaction { code: warning.code(), page: warning.location().page_index, }) .collect(), })}
/// One line for each thing `found` holds, or one saying there is nothing.pub(crate) fn report(path: &str, found: &Hidden) -> String { let mut lines: Vec<String> = found.categories.iter().map(|c| format!("{path}: {c}\n")).collect(); for FailedRedaction { code, page } in &found.redactions { let place = page.map_or_else(String::new, |page| format!(" on page {}", page + 1)); lines.push(format!("{path}: {code}{place}\n")); } if lines.is_empty() { lines.push(format!("{path}: nothing beyond its pages\n")); } lines.concat()}letter.pdf: history letter.pdf: text-in-earlier-revision brochure.pdf: metadata brochure.pdf: hidden-content
The letter’s latest revision deleted a word, but its first revision still holds it, and anyone can read that revision. The brochure has metadata and invisible text on its first page.
What reveal looks for
Section titled “What reveal looks for”Document::reveal reads every object once and sorts what it finds into seven categories. Reveal::found lists the ones the file has:
| Category | What it means |
|---|---|
history |
Earlier revisions, and objects nothing refers to any more |
metadata |
The title, author and dates in the file’s two metadata stores (its document information and its XMP metadata), and metadata on single objects |
attachments |
Embedded files |
active-content |
JavaScript, actions that run on a trigger, and XFA forms |
annotations |
Comments and markup, with their authors |
forms |
Form fields that hold values |
hidden-content |
Hidden text, layers turned off, redaction marks never applied, and annotations that lie wholly off their page |
The Reveal it returns also holds the details: each Info entry, each attachment’s name and size, and each run of hidden text. For each earlier revision, it counts the words that revision holds and the latest one lost, and names the pages they were on.
Forms that use scripts
Section titled “Forms that use scripts”A form’s scripts are hidden from the person filling it in. Lamina PDF never runs them, whether in the library, the reader or the command line. Most form scripts only call Acrobat’s built-in helpers, which format a number as $1,234.50, check a date, or add up a column. Lamina PDF recognises those calls as data and does their work itself, so such forms fill, format and add up as they do in Acrobat. Any other script is skipped: you can still fill the field, but the script doesn’t run.
Document::form_scripts lists every script in a file without returning its text. Each entry says where the script is, how long it is, and whether Lamina PDF handles it: handled for a helper call, not handled for any other script, xfa for a script in an XFA form (Adobe’s older XML form format).
Redactions that didn’t remove the text
Section titled “Redactions that didn’t remove the text”A black rectangle over a name hides it on screen and in print, but the name is still in the file, and copying the text brings it back. Document::redaction_warnings finds three ways a redaction fails:
| Warning | What it found |
|---|---|
covered-text |
Text under an opaque box on the page |
redaction-not-applied |
Redaction marks that were drawn but never applied |
text-in-earlier-revision |
Words an earlier revision holds that the latest doesn’t |
The example reads these warnings from the Reveal with Reveal::redaction_warnings, which gives the same warnings without reading the file again. Document::redaction_warnings would read every page and every earlier revision a second time, so call it only when the warnings are all you need.
Each warning names its page when it has one. Remove the text itself with a tool that deletes what a redaction covers, then save a full rewrite, so no earlier revision keeps it.
Remove what a file hides
Section titled “Remove what a file hides”Once you know what a file holds, you can take it out. Sanitise removes the categories you name, or all of them with Sanitise::all(), and reports each item it removed by the object number reveal lists:
| Category | What goes |
|---|---|
metadata |
The document information, the XMP metadata, metadata on single objects, application data, modification dates and page thumbnails |
attachments |
Embedded files and the comments that hold them |
active-content |
Scripts, actions that run on their own, actions that launch a program, submit a form, import data or open a link outside the file, XFA forms, rich media, named renditions, and references to another file or the web: a reference XObject’s /Ref, a stream’s external data, a movie stored elsewhere, a colour profile an output intent names by reference and an image’s print-shop (OPI) reference |
annotations |
Comments and markup; links, form fields and redaction marks never applied stay |
hidden-content |
Layers that are turned off (their text, images and comments, wherever they are drawn, and the layers themselves), content, comments and links wholly outside the page, and text drawn white on nothing, under 1 point or under something painted over it |
history |
Earlier revisions and objects nothing refers to |
reveal lists plain links (URI to a web address, GoToR to another file) without counting them as active content, since a person follows them only by choosing to; the sanitiser removes them all the same. Other actions whose target is another file or the web, such as an embedded-file jump, a thread or a rendition reading a file from elsewhere, do count.
Form values stay. Hidden content goes without turning a page into a picture: text stays text, and where hidden words sat inside a line, the words after them stay where they were. Some hidden things stay on purpose, and the report lists each in hidden_kept (hiddenKept in TypeScript):
- Invisible text. A scanned page carries the words its OCR found as invisible text, so search and copy work; removing it would break that.
- Text hidden by its clip, form fields wholly outside the page, and redaction marks never applied. Apply the redactions first, then sanitise.
- Hidden text inside a form (a drawing that pages can share) that some place shows. One page may draw white text where it can’t be seen, and another over a dark box, where it can. The text also stays when more than page content can draw the form, such as a comment’s appearance or a pattern.
- Text under an annotation’s appearance, such as a comment’s box or an unapplied redaction, which a reader can move or remove. Text drawn with a blend mode, whose colour on the page can’t be told. Content outside the page whose ink may still reach onto it, and comments a viewer may draw onto the page from beside it: a note’s icon, or markup drawn from points that reach the page.
- Content whose layer Lamina PDF can’t decide, and content it can’t take out, such as a shape that clips what follows. A layer that something kept still names stays turned off.
- Replacement text that the file also uses for content that stays. Screen readers and copy and paste take such text in place of what is drawn. Replacement text that only removed content used goes with it.
A font a page embeds keeps every glyph it was made with, so the shapes of removed characters can stay in the font after a sanitise, though no page draws them.
So reveal can still list hidden content on a sanitised file: the invisible text, and whatever the report says was kept.
To decide what to take, a sanitise reads every page, form, pattern and Type 3 glyph, and the work it does is bounded at 64 million steps. Reading a page costs a step for each content operator it runs, its forms’ included, and for each glyph it shows; reading any of the others costs a step for each operator.
A page with nothing hidden is read once. A page with hidden content is read up to three times as the sanitise takes it out, and once more by the check that follows. So a file of about 20 million operators and glyphs, most of them on pages with hidden content, is about the largest a sanitise takes on; a file with fewer such pages can be larger.
When a form holds hidden text, every page is read again to see where the form is drawn, and once more after a form is edited. Such a file reaches the limit at less than half that size. Past the limit, a sanitise fails with sanitise-limit and changes nothing.
Removing hidden content edits what pages draw. In TypeScript that needs the extract or text module: load one with init({ extract: true }) before you open the file. In the base module a sanitise leaves hidden content out and warns hidden-content-kept, and asking for hidden-content there fails with extract-module-not-loaded.
This example removes every category and prints how many items went from each:
// Remove what a PDF hides before you share it: metadata, attachments, scripts, comments and hidden// content (layers that are off, text no one can see), with a report of every item removed. Hidden// content needs the extract or text module, which `init({ extract: true })` loads. The save rewrites the whole file, so no earlier revision keeps what// was removed.import { Document } from "@laminapdf/sdk";
/** What removing every category took out of `bytes`, as text, and the file as it saves. */export function sanitiseAFile(bytes: Uint8Array): { report: string; clean: Uint8Array<ArrayBuffer> } { using doc = Document.open(bytes); const { sanitised } = doc.sanitise(); if (sanitised === undefined) throw new Error("a sanitise always reports"); const lines = [ `metadata: ${sanitised.metadata.length} removed`, `attachments: ${sanitised.attachments.length} removed`, `active-content: ${sanitised.activeContent.length} removed`, `annotations: ${sanitised.annotations.length} removed`, `hidden-content: ${sanitised.hiddenContent.length} removed`, `history: ${sanitised.history.length} removed`, `hidden content kept: ${sanitised.hiddenKept.length}`, ...sanitised.warnings.map((w) => `warning: ${w.code}`), ]; return { report: `${lines.join("\n")}\n`, clean: doc.save() };}//! Remove what a PDF hides before you share it: metadata, attachments, scripts, comments and//! hidden content (layers that are off, text no one can see), with a report of every item removed. The save rewrites the whole file, so no earlier//! revision keeps what was removed.//!//! ```sh//! cargo run -p laminapdf --example sanitise_a_file -- file.pdf [out-dir]//! ```
use std::error::Error;use std::fmt::Write as _;use std::path::PathBuf;
use laminapdf::{Document, Op, OpenOptions, Sanitise, SaveOptions};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let usage = "usage: sanitise_a_file file.pdf [out-dir]"; let file = PathBuf::from(args.next().ok_or(usage)?); let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let (report, clean) = sanitise(std::fs::read(file)?)?; print!("{report}"); std::fs::write(out.join("sanitise_a_file.pdf"), clean)?; Ok(())}
/// What removing every category took out of `bytes`, as text, and the file as it saves.pub(crate) fn sanitise(bytes: Vec<u8>) -> Result<(String, Vec<u8>), Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?; let edited = doc.apply(vec![Op::from(Sanitise::all())])?; let report = edited.sanitised.ok_or("a sanitise always reports")?; let mut text = String::new(); for (category, items) in [ ("metadata", &report.metadata), ("attachments", &report.attachments), ("active-content", &report.active_content), ("annotations", &report.annotations), ("hidden-content", &report.hidden_content), ("history", &report.history), ] { writeln!(text, "{category}: {} removed", items.len())?; } writeln!(text, "hidden content kept: {}", report.hidden_kept.len())?; for warning in &report.warnings { writeln!(text, "warning: {}", warning.code())?; } Ok((text, doc.save(&SaveOptions::new())?.bytes))}metadata: 5 removed attachments: 5 removed active-content: 18 removed annotations: 4 removed hidden-content: 8 removed history: 7 removed hidden content kept: 1 warning: field-formatting-removed
The save after it always rewrites the whole file, so a sanitised file is one revision and nothing removed survives in it. If the file is protected, it stays protected. On a signed file the rewrite invalidates every signature, so the save refuses unless you allow that.
Each category also has its own edit: StripMetadata, StripAnnotations, StripAttachments, StripActiveContent and StripHiddenContent. The report’s warnings say what else changed. Form fields can lose their number and date formatting with their scripts, an XFA form may not show as it did, and a PDF/A or PDF/UA claim goes with the metadata. Redaction marks that were never applied stay.
Undo puts back what a sanitise removed. A sanitise that found nothing to remove leaves no step to undo, but the next save still rewrites the file; cancel_rewrite (cancelRewrite() in TypeScript) drops that.
The rewrite keeps the first half of the file’s ID (/ID), which stays the same across saves so signatures and caches can recognise the file. It also links the sanitised file to the original, so anyone holding both can tell they are one document.
Mark what must go
Section titled “Mark what must go”A box drawn over text doesn’t remove it. Real redaction starts with marks: each one is a Redact annotation over text or an area, and it holds only where it is and how the box will look, never the words under it. mark_redaction (markRedaction in TypeScript) marks the lines a selection gives, and mark_redaction_area (markRedactionArea) marks an area. A mark is a comment as far as signatures are concerned, so it saves as an update that approval signatures allow.
Review the marks before anything goes. redaction_marks (redactionMarks()) lists each mark with its review state and the text under it now; SetReviewState (setReviewState) accepts or rejects one. redaction_selection (redactionSelection()) says exactly what a set of marks takes: every glyph a mark touches, the whole word around it, and invisible text within a point of it. It also gives the words to look for elsewhere in the file. A preview draws from it, and applying will remove the same glyphs.
This example marks an area of the first page, accepts the mark and counts what it takes:
// Mark an area of a PDF for redaction, accept the mark, and see what applying it would take.// A mark is an annotation: it holds the area and how the box will look, never the text under it,// and nothing is removed until the marks are applied. The selection says exactly which glyphs go,// whole words with them, so a preview and the removal can't disagree. Needs `init({ extract: true })`.import { Document } from "@laminapdf/sdk";
/** * `bytes` with `area` (`[x0, y0, x1, y1]` of its first page, in points from the top left) marked * and accepted, saved incrementally, and what each mark would take: counts, never the words. */export function markForRedaction( bytes: Uint8Array, area: readonly [number, number, number, number],): { report: string; marked: Uint8Array<ArrayBuffer> } { using doc = Document.open(bytes); const args = doc.markRedactionArea(0, area); const [id] = doc.apply([{ op: "markRedaction", args }]).createdAnnotations; if (id === undefined) throw new Error("a mark is always created"); doc.apply([{ op: "setReviewState", args: { target: id, state: "accepted" } }]); const lines = doc.redactionMarks().map((mark) => { const taken = doc.redactionSelection(mark.page, [mark.mark.area]); const state = mark.review === "accepted" ? "accepted" : "to review"; return `page ${mark.page + 1}: ${state}; glyphs ${taken.glyphs.length}, stretches ${taken.stretches.length}, terms ${taken.terms.length}`; }); // Marks are annotations, so they save as an update the file's signatures allow. return { report: `${lines.join("\n")}\n`, marked: doc.save({ mode: "incremental" }) };}//! Mark an area of a PDF for redaction, accept the mark, and see what applying it would take.//!//! A mark is an annotation: it holds the area and how the box will look, never the text under//! it, and nothing is removed until the marks are applied. The selection says exactly which//! glyphs go, whole words with them, so a preview and the removal can't disagree.//!//! ```sh//! cargo run -p laminapdf --example mark_for_redaction -- file.pdf <x0> <y0> <x1> <y1> [out-dir] # an area of page 1, in points from the top left//! ```
use std::error::Error;use std::fmt::Write as _;use std::path::PathBuf;
use laminapdf::{Document, MarkReview, Op, OpenOptions, RectPt, ReviewState, SaveMode, SaveOptions, SetReviewState};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let usage = "usage: mark_for_redaction file.pdf <x0> <y0> <x1> <y1> [out-dir]"; let file = PathBuf::from(args.next().ok_or(usage)?); let mut corner = || -> Result<f64, Box<dyn Error>> { Ok(args.next().ok_or(usage)?.parse()?) }; let (x0, y0, x1, y1) = (corner()?, corner()?, corner()?, corner()?); let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let (report, marked) = mark(std::fs::read(file)?, RectPt::from_points(x0, y0, x1 - x0, y1 - y0))?; print!("{report}"); std::fs::write(out.join("mark_for_redaction.pdf"), marked)?; Ok(())}
/// `bytes` with `area` of its first page marked and accepted, saved incrementally, and what each/// mark would take: counts, never the words themselves.pub(crate) fn mark(bytes: Vec<u8>, area: RectPt) -> Result<(String, Vec<u8>), Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?; let mark = doc.mark_redaction_area(0, area)?; let id = doc.apply(vec![Op::from(mark)])?.created_annotations.remove(0); doc.apply(vec![Op::from(SetReviewState::new(id, ReviewState::Accepted))])?; let mut report = String::new(); for mark in doc.redaction_marks()? { let taken = doc.redaction_selection(mark.page, std::slice::from_ref(&mark.mark.area))?; let state = if mark.review == MarkReview::Accepted { "accepted" } else { "to review" }; writeln!( report, "page {}: {state}; glyphs {}, stretches {}, terms {}", mark.page + 1, taken.glyphs.len(), taken.stretches.len(), taken.terms.len() )?; } // Marks are annotations, so they save as an update the file's signatures allow. let options = SaveOptions::new().with_mode(SaveMode::Incremental); Ok((report, doc.save(&options)?.bytes))}page 1: accepted; glyphs 19, stretches 1, terms 4
Marking removes nothing yet: applying the marks comes in a later release.
From TypeScript and the command line
Section titled “From TypeScript and the command line”@laminapdf/sdk doesn’t have reveal or the redaction warnings yet, though it can sanitise. The command line runs the same checks: laminapdf reveal reports each category, and laminapdf check reports failed redactions with its other warnings. Inspect and check PDFs shows both.
Next: open files you don’t trust, with limits on the work an uploaded file can make Lamina PDF do.