407 lines
16 KiB
Rust
407 lines
16 KiB
Rust
//! True redaction. Each redacted page is rendered by pdfium, the boxes are painted black into the pixels, and the
|
|
//! page is rebuilt by lopdf as that one image: no text, image, vector, annotation or form content of the old page
|
|
//! survives. The other pages are not touched (their objects are written back byte for byte). The document's
|
|
//! metadata and the places hidden text can live (XMP, /Info, the struct tree's ActualText, bookmarks,
|
|
//! attachments, JavaScript) are removed, every unreferenced object is pruned, and the file is written fresh (no
|
|
//! incremental history).
|
|
//!
|
|
//! The brief's alternative, rewriting the page's content stream to cut out only what lies under the box, is not
|
|
//! used: it needs a full content-stream interpreter (fonts, glyph positions, form XObjects, inline images,
|
|
//! clipping, shadings, Type 3 fonts) and any mistake leaves text behind. The cost of the chosen method: the text of
|
|
//! a redacted page is no longer selectable or searchable. docs/FORMATS.md records this.
|
|
use crate::{Engine, PdfError, ViewRect, lopdf_load, lopdf_save, reader::render_doc_page};
|
|
use lopdf::{Dictionary, Document, Object, ObjectId, Stream, dictionary};
|
|
use serde::{Deserialize, Serialize};
|
|
use std::collections::{BTreeSet, HashSet};
|
|
|
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
pub struct Redaction {
|
|
/// 0-based page index.
|
|
pub page: usize,
|
|
/// Boxes in view space (points, top-left origin of the displayed page).
|
|
pub rects: Vec<ViewRect>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
pub struct RedactOptions {
|
|
/// Resolution of the rebuilt pages.
|
|
pub dpi: u32,
|
|
pub jpeg_quality: u8,
|
|
}
|
|
|
|
impl Default for RedactOptions {
|
|
fn default() -> Self {
|
|
RedactOptions { dpi: 200, jpeg_quality: 90 }
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone)]
|
|
pub struct Redacted {
|
|
/// The new PDF, not encrypted.
|
|
pub bytes: Vec<u8>,
|
|
/// Plain sentences for the user (for example, hidden layers left on pages that were not redacted).
|
|
pub warnings: Vec<String>,
|
|
}
|
|
|
|
const IMAGE_NAME: &[u8] = b"PictorRedacted";
|
|
|
|
pub fn redact(
|
|
engine: &Engine,
|
|
bytes: &[u8],
|
|
password: Option<&str>,
|
|
redactions: &[Redaction],
|
|
opts: &RedactOptions,
|
|
) -> Result<Redacted, PdfError> {
|
|
if redactions.is_empty() || redactions.iter().any(|r| r.rects.is_empty() || r.rects.iter().any(ViewRect::is_empty)) {
|
|
return Err(PdfError::Invalid("Draw at least one box to redact.".into()));
|
|
}
|
|
// 1. Render every redacted page with pdfium (annotations and form fields included) and burn the boxes in.
|
|
let pdfium_doc = engine.open(bytes, password)?;
|
|
let page_count = pdfium_doc.pages().len() as usize;
|
|
let mut images: Vec<(usize, Vec<u8>, u32, u32, f32, f32)> = Vec::new();
|
|
let mut seen = BTreeSet::new();
|
|
for r in redactions {
|
|
if r.page >= page_count {
|
|
return Err(PdfError::NoSuchPage(r.page + 1));
|
|
}
|
|
if !seen.insert(r.page) {
|
|
continue;
|
|
}
|
|
let rects: Vec<ViewRect> = redactions.iter().filter(|x| x.page == r.page).flat_map(|x| x.rects.clone()).collect();
|
|
let page = pdfium_doc.pages().get(r.page as i32).map_err(PdfError::from_pdfium)?;
|
|
let (vw, vh) = (page.width().value, page.height().value);
|
|
drop(page);
|
|
let mut dpi = opts.dpi.clamp(72, 600) as f32;
|
|
while (vw * dpi / 72.0) * (vh * dpi / 72.0) > crate::reader::MAX_RENDER_PIXELS as f32 / 2.0 && dpi > 36.0 {
|
|
dpi *= 0.8;
|
|
}
|
|
let px_w = (vw * dpi / 72.0).round().max(1.0) as u32;
|
|
let mut img = render_doc_page(&pdfium_doc, r.page, px_w, true)?.to_rgb8();
|
|
let scale = img.width() as f32 / vw;
|
|
for rect in &rects {
|
|
let x0 = ((rect.x * scale).floor() as i64 - 1).clamp(0, img.width() as i64) as u32;
|
|
let y0 = ((rect.y * scale).floor() as i64 - 1).clamp(0, img.height() as i64) as u32;
|
|
let x1 = (((rect.x + rect.w) * scale).ceil() as i64 + 1).clamp(0, img.width() as i64) as u32;
|
|
let y1 = (((rect.y + rect.h) * scale).ceil() as i64 + 1).clamp(0, img.height() as i64) as u32;
|
|
for y in y0..y1 {
|
|
for x in x0..x1 {
|
|
img.put_pixel(x, y, image::Rgb([0, 0, 0]));
|
|
}
|
|
}
|
|
}
|
|
let mut jpeg = Vec::new();
|
|
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, opts.jpeg_quality.clamp(50, 100))
|
|
.encode_image(&img)
|
|
.map_err(|e| PdfError::Write(e.to_string()))?;
|
|
images.push((r.page, jpeg, img.width(), img.height(), vw, vh));
|
|
}
|
|
drop(pdfium_doc);
|
|
|
|
// 2. Rebuild those pages with lopdf.
|
|
let mut doc = lopdf_load(bytes, password)?;
|
|
let pages: Vec<ObjectId> = doc.get_pages().values().copied().collect();
|
|
if pages.len() != page_count {
|
|
return Err(PdfError::Damaged(format!(
|
|
"its page tree is inconsistent ({} pages by one reading, {} by another); Pictor will not redact it",
|
|
page_count,
|
|
pages.len()
|
|
)));
|
|
}
|
|
let mut removed_annots: HashSet<ObjectId> = HashSet::new();
|
|
let redacted_pages: HashSet<ObjectId> = images.iter().map(|i| pages[i.0]).collect();
|
|
for (index, jpeg, pw, ph, vw, vh) in images {
|
|
let page_id = pages[index];
|
|
let old = doc.get_dictionary(page_id).map_err(|e| PdfError::Damaged(e.to_string()))?.clone();
|
|
if let Ok(annots) = old.get(b"Annots") {
|
|
let list = match annots {
|
|
Object::Reference(id) => doc.get_object(*id).and_then(Object::as_array).cloned().unwrap_or_default(),
|
|
Object::Array(a) => a.clone(),
|
|
_ => Vec::new(),
|
|
};
|
|
for a in list {
|
|
if let Object::Reference(id) = a {
|
|
removed_annots.insert(id);
|
|
if let Ok(Object::Dictionary(d)) = doc.get_object(id)
|
|
&& let Ok(Object::Reference(popup)) = d.get(b"Popup")
|
|
{
|
|
removed_annots.insert(*popup);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
let mut image = Stream::new(
|
|
dictionary! {
|
|
"Type" => "XObject", "Subtype" => "Image", "Width" => pw as i64, "Height" => ph as i64,
|
|
"ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8, "Filter" => "DCTDecode",
|
|
},
|
|
jpeg,
|
|
);
|
|
image.allows_compression = false;
|
|
let image_id = doc.add_object(image);
|
|
let content = format!("q {vw:.4} 0 0 {vh:.4} 0 0 cm /PictorRedacted Do Q").into_bytes();
|
|
let content_id = doc.add_object(Stream::new(dictionary! {}, content));
|
|
let bbox = vec![0.into(), 0.into(), Object::Real(vw), Object::Real(vh)];
|
|
let mut fresh = dictionary! {
|
|
"Type" => "Page",
|
|
"MediaBox" => bbox.clone(),
|
|
"CropBox" => bbox,
|
|
"Rotate" => 0,
|
|
"Resources" => dictionary! { "XObject" => Dictionary::from_iter([(IMAGE_NAME.to_vec(), Object::Reference(image_id))]) },
|
|
"Contents" => content_id,
|
|
};
|
|
if let Ok(parent) = old.get(b"Parent") {
|
|
fresh.set("Parent", parent.clone());
|
|
}
|
|
doc.objects.insert(page_id, Object::Dictionary(fresh));
|
|
}
|
|
// The annotations of redacted pages go, even if something else still points at them.
|
|
for id in &removed_annots {
|
|
doc.objects.remove(id);
|
|
}
|
|
|
|
// Resources inherited from a Pages node would keep the redacted page's old fonts and images alive: give each
|
|
// remaining page that relied on them its own copy, then remove them from the Pages nodes.
|
|
push_down_resources(&mut doc, &pages, &redacted_pages);
|
|
|
|
// 3. The form: fields whose widgets were all on redacted pages go.
|
|
let mut warnings = Vec::new();
|
|
prune_form(&mut doc, &removed_annots);
|
|
|
|
// 4. Document-level hiding places.
|
|
scrub_document(&mut doc, &redacted_pages, &mut warnings);
|
|
|
|
// 5. Drop everything no longer referenced and write a fresh file.
|
|
doc.prune_objects();
|
|
let out = lopdf_save(&mut doc)?;
|
|
Ok(Redacted { bytes: out, warnings })
|
|
}
|
|
|
|
fn push_down_resources(doc: &mut Document, pages: &[ObjectId], redacted: &HashSet<ObjectId>) {
|
|
let mut nodes = HashSet::new();
|
|
for &page in pages {
|
|
// The nearest ancestor's /Resources, and every Pages node on the way up.
|
|
let mut inherited = None;
|
|
let mut current = doc.get_dictionary(page).ok().and_then(|d| d.get(b"Parent").ok()).and_then(|p| p.as_reference().ok());
|
|
let mut depth = 0;
|
|
while let Some(id) = current {
|
|
if depth > 64 || !nodes.insert(id) && inherited.is_some() {
|
|
break;
|
|
}
|
|
depth += 1;
|
|
let Ok(d) = doc.get_dictionary(id) else { break };
|
|
if inherited.is_none()
|
|
&& let Ok(r) = d.get(b"Resources")
|
|
{
|
|
inherited = Some(r.clone());
|
|
}
|
|
current = d.get(b"Parent").ok().and_then(|p| p.as_reference().ok());
|
|
}
|
|
if redacted.contains(&page) {
|
|
continue;
|
|
}
|
|
if let (Some(r), Ok(d)) = (inherited, doc.get_dictionary_mut(page))
|
|
&& !d.has(b"Resources")
|
|
{
|
|
d.set("Resources", r);
|
|
}
|
|
}
|
|
for id in nodes {
|
|
if let Ok(d) = doc.get_dictionary_mut(id) {
|
|
d.remove(b"Resources");
|
|
}
|
|
}
|
|
}
|
|
|
|
fn prune_form(doc: &mut Document, removed: &HashSet<ObjectId>) {
|
|
let Ok(catalog) = doc.catalog() else { return };
|
|
let acroform = match catalog.get(b"AcroForm") {
|
|
Ok(Object::Reference(id)) => Some(*id),
|
|
_ => None,
|
|
};
|
|
let fields: Vec<Object> = {
|
|
let form = match acroform {
|
|
Some(id) => doc.get_dictionary(id).ok(),
|
|
None => catalog.get(b"AcroForm").and_then(Object::as_dict).ok(),
|
|
};
|
|
match form.and_then(|f| f.get(b"Fields").ok()) {
|
|
Some(Object::Array(a)) => a.clone(),
|
|
Some(Object::Reference(r)) => doc.get_object(*r).and_then(Object::as_array).cloned().unwrap_or_default(),
|
|
_ => Vec::new(),
|
|
}
|
|
};
|
|
fn keep(doc: &mut Document, field: &Object, removed: &HashSet<ObjectId>, depth: u32) -> bool {
|
|
let Object::Reference(id) = field else { return true };
|
|
if removed.contains(id) {
|
|
return false;
|
|
}
|
|
if depth > 32 {
|
|
return true;
|
|
}
|
|
let kids = match doc.get_dictionary(*id).ok().and_then(|d| d.get(b"Kids").ok()) {
|
|
Some(Object::Array(a)) => a.clone(),
|
|
_ => return true,
|
|
};
|
|
if kids.is_empty() {
|
|
return true;
|
|
}
|
|
let kept: Vec<Object> = kids.into_iter().filter(|k| keep(doc, k, removed, depth + 1)).collect();
|
|
if kept.is_empty() {
|
|
return false;
|
|
}
|
|
if let Ok(d) = doc.get_dictionary_mut(*id) {
|
|
d.set("Kids", kept);
|
|
}
|
|
true
|
|
}
|
|
let kept: Vec<Object> = fields.iter().filter(|f| keep(doc, f, removed, 0)).cloned().collect();
|
|
let changed = kept.len() != fields.len();
|
|
let catalog_id = match doc.trailer.get(b"Root") {
|
|
Ok(Object::Reference(id)) => *id,
|
|
_ => return,
|
|
};
|
|
if kept.is_empty() {
|
|
if let Ok(c) = doc.get_dictionary_mut(catalog_id) {
|
|
c.remove(b"AcroForm");
|
|
}
|
|
return;
|
|
}
|
|
if changed {
|
|
let target = match acroform {
|
|
Some(id) => doc.get_dictionary_mut(id).ok(),
|
|
None => doc.get_dictionary_mut(catalog_id).ok().and_then(|c| c.get_mut(b"AcroForm").ok()).and_then(|o| o.as_dict_mut().ok()),
|
|
};
|
|
if let Some(f) = target {
|
|
f.set("Fields", kept);
|
|
f.remove(b"CO");
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Removes the document-level places where text can hide. Shared with [`crate::edit`]'s "remove hidden data".
|
|
pub(crate) fn scrub_document(doc: &mut Document, redacted_pages: &HashSet<ObjectId>, warnings: &mut Vec<String>) {
|
|
doc.trailer.remove(b"Info");
|
|
let catalog_id = match doc.trailer.get(b"Root") {
|
|
Ok(Object::Reference(id)) => *id,
|
|
_ => return,
|
|
};
|
|
// Hidden layers: drop the layer definitions only if no remaining page still uses one (else those pages would
|
|
// suddenly show their hidden content).
|
|
let pages: Vec<ObjectId> = doc.get_pages().values().copied().collect();
|
|
let mut oc_pages = Vec::new();
|
|
for (i, p) in pages.iter().enumerate() {
|
|
if !redacted_pages.contains(p) && uses_optional_content(doc, *p) {
|
|
oc_pages.push(i + 1);
|
|
}
|
|
}
|
|
if let Ok(catalog) = doc.get_dictionary_mut(catalog_id) {
|
|
for key in [
|
|
&b"Metadata"[..],
|
|
b"StructTreeRoot",
|
|
b"MarkInfo",
|
|
b"Outlines",
|
|
b"PieceInfo",
|
|
b"Threads",
|
|
b"AA",
|
|
b"Collection",
|
|
b"AF",
|
|
b"SpiderInfo",
|
|
b"Perms",
|
|
b"Legal",
|
|
] {
|
|
catalog.remove(key);
|
|
}
|
|
if matches!(catalog.get(b"PageMode"), Ok(Object::Name(n)) if n == b"UseOutlines") {
|
|
catalog.remove(b"PageMode");
|
|
}
|
|
if !matches!(catalog.get(b"OpenAction"), Ok(Object::Array(_))) {
|
|
catalog.remove(b"OpenAction");
|
|
}
|
|
if oc_pages.is_empty() {
|
|
catalog.remove(b"OCProperties");
|
|
}
|
|
}
|
|
if !oc_pages.is_empty() {
|
|
warnings.push(format!(
|
|
"Pages {} have hidden layers, which were left as they are. Redact those pages too to remove them.",
|
|
oc_pages.iter().map(|p| p.to_string()).collect::<Vec<_>>().join(", ")
|
|
));
|
|
}
|
|
// Names: attachments and document JavaScript go; destinations stay.
|
|
let names = match doc.get_dictionary(catalog_id).ok().and_then(|c| c.get(b"Names").ok()) {
|
|
Some(Object::Reference(id)) => Some(*id),
|
|
_ => None,
|
|
};
|
|
let strip_names = |d: &mut Dictionary| {
|
|
d.remove(b"EmbeddedFiles");
|
|
d.remove(b"JavaScript");
|
|
};
|
|
match names {
|
|
Some(id) => {
|
|
if let Ok(d) = doc.get_dictionary_mut(id) {
|
|
strip_names(d);
|
|
}
|
|
}
|
|
None => {
|
|
if let Ok(c) = doc.get_dictionary_mut(catalog_id)
|
|
&& let Ok(Object::Dictionary(d)) = c.get_mut(b"Names")
|
|
{
|
|
strip_names(d);
|
|
}
|
|
}
|
|
}
|
|
// Every /Metadata and /PieceInfo on every object.
|
|
for o in doc.objects.values_mut() {
|
|
let d = match o {
|
|
Object::Dictionary(d) => d,
|
|
Object::Stream(s) => &mut s.dict,
|
|
_ => continue,
|
|
};
|
|
d.remove(b"Metadata");
|
|
d.remove(b"PieceInfo");
|
|
}
|
|
}
|
|
|
|
/// Whether a page (its resources, XObjects and annotations, followed by reference) uses optional content.
|
|
fn uses_optional_content(doc: &Document, page: ObjectId) -> bool {
|
|
let mut stack = vec![Object::Reference(page)];
|
|
let mut seen = HashSet::new();
|
|
let mut budget = 20_000u32;
|
|
while let Some(o) = stack.pop() {
|
|
if budget == 0 {
|
|
return true; // too deep to tell: be conservative and keep the layers
|
|
}
|
|
budget -= 1;
|
|
let o = match o {
|
|
Object::Reference(id) => {
|
|
if !seen.insert(id) {
|
|
continue;
|
|
}
|
|
match doc.get_object(id) {
|
|
Ok(o) => o.clone(),
|
|
Err(_) => continue,
|
|
}
|
|
}
|
|
o => o,
|
|
};
|
|
let dict = match &o {
|
|
Object::Dictionary(d) => d,
|
|
Object::Stream(s) => &s.dict,
|
|
Object::Array(a) => {
|
|
stack.extend(a.iter().cloned());
|
|
continue;
|
|
}
|
|
_ => continue,
|
|
};
|
|
if dict.has(b"OC") || dict.has_type(b"OCG") || dict.has_type(b"OCMD") {
|
|
return true;
|
|
}
|
|
for (k, v) in dict.iter() {
|
|
if k == b"Parent" || k == b"P" {
|
|
continue;
|
|
}
|
|
stack.push(v.clone());
|
|
}
|
|
}
|
|
false
|
|
}
|