[pdf] Redaction: rebuild redacted pages as one image, scrub hidden data, prune; reader and AES-256 protect/unlock

This commit is contained in:
2026-11-16 13:26:02 +01:00
parent b554d760e2
commit 2c1611b34a
14 changed files with 1452 additions and 125 deletions
+170
View File
@@ -0,0 +1,170 @@
//! Reading: page sizes, rendering, text, search, outline. All through pdfium (it is what Chrome and Edge use, so a
//! file Edge opens, Pictor opens).
use crate::{Engine, PdfError, ViewRect};
use image::DynamicImage;
use pdfium_render::prelude::*;
use serde::Serialize;
/// Rendering never makes a bitmap larger than this many pixels (about 200 MB of RGBA).
pub const MAX_RENDER_PIXELS: i64 = 50_000_000;
#[derive(Debug, Clone, Serialize)]
pub struct DocInfo {
pub pages: Vec<PageInfo>,
pub outline: Vec<OutlineItem>,
pub has_form: bool,
pub encrypted: bool,
}
#[derive(Debug, Clone, Serialize)]
pub struct PageInfo {
/// Displayed size in points.
pub width: f32,
pub height: f32,
pub label: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct OutlineItem {
pub title: String,
pub page: Option<usize>,
pub depth: u32,
}
#[derive(Debug, Clone, Serialize)]
pub struct SearchHit {
pub page: usize,
/// The hit's boxes in view space.
pub rects: Vec<ViewRect>,
}
pub fn info(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result<DocInfo, PdfError> {
let doc = engine.open(bytes, password)?;
let mut pages = Vec::new();
for page in doc.pages().iter() {
pages.push(PageInfo { width: page.width().value, height: page.height().value, label: page.label().map(Into::into) });
}
let mut outline = Vec::new();
fn walk(b: PdfBookmark, depth: u32, out: &mut Vec<OutlineItem>, budget: &mut u32) {
if *budget == 0 || depth > 32 {
return;
}
*budget -= 1;
let page = b.destination().and_then(|d| d.page_index().ok()).map(|i| i as usize);
out.push(OutlineItem { title: b.title().unwrap_or_default(), page, depth });
if let Some(child) = b.first_child() {
let mut next = Some(child);
while let Some(c) = next {
next = c.next_sibling();
walk(c, depth + 1, out, budget);
}
}
}
let mut budget = 5000;
let mut next = doc.bookmarks().root();
while let Some(b) = next {
next = b.next_sibling();
walk(b, 0, &mut outline, &mut budget);
}
let has_form = doc.form().is_some();
Ok(DocInfo { pages, outline, has_form, encrypted: password.is_some() })
}
/// The displayed size of every page, in points.
pub fn page_sizes(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result<Vec<(f32, f32)>, PdfError> {
let doc = engine.open(bytes, password)?;
Ok(doc.pages().iter().map(|p| (p.width().value, p.height().value)).collect())
}
pub(crate) fn render_doc_page(doc: &PdfDocument, index: usize, width_px: u32, forms: bool) -> Result<DynamicImage, PdfError> {
let page = doc.pages().get(index as i32).map_err(|_| PdfError::NoSuchPage(index + 1))?;
let (w, h) = (page.width().value.max(1.0), page.height().value.max(1.0));
let width = width_px.clamp(1, 20_000) as i64;
let height = ((width as f32) * h / w).ceil().max(1.0) as i64;
if width * height > MAX_RENDER_PIXELS {
return Err(PdfError::TooLarge(format!("page {} would render at {width} × {height} pixels", index + 1)));
}
let cfg = PdfRenderConfig::new()
.set_target_size(width as i32, height as i32)
.render_form_data(forms)
.render_annotations(true)
.set_clear_color(PdfColor::WHITE);
page.render_with_config(&cfg).and_then(|b| b.as_image()).map_err(PdfError::from_pdfium)
}
/// Renders page `index` (0-based) `width_px` pixels wide, with annotations and form fields drawn.
pub fn render_page(
engine: &Engine,
bytes: &[u8],
password: Option<&str>,
index: usize,
width_px: u32,
) -> Result<DynamicImage, PdfError> {
let doc = engine.open(bytes, password)?;
render_doc_page(&doc, index, width_px, true)
}
/// The text of every page, in order.
pub fn extract_text(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result<Vec<String>, PdfError> {
let doc = engine.open(bytes, password)?;
let mut out = Vec::new();
for page in doc.pages().iter() {
out.push(page.text().map(|t| t.all()).map_err(PdfError::from_pdfium)?);
}
Ok(out)
}
/// Case-insensitive search over every page; at most `limit` hits.
pub fn search(
engine: &Engine,
bytes: &[u8],
password: Option<&str>,
query: &str,
limit: usize,
) -> Result<Vec<SearchHit>, PdfError> {
if query.trim().is_empty() {
return Ok(Vec::new());
}
let doc = engine.open(bytes, password)?;
let mut hits = Vec::new();
for (i, page) in doc.pages().iter().enumerate() {
let frame = page_frame(&page);
let text = page.text().map_err(PdfError::from_pdfium)?;
let search = text.search(query, &PdfSearchOptions::new()).map_err(PdfError::from_pdfium)?;
while let Some(segments) = search.find_next() {
let rects = segments.iter().map(|s| frame.user_to_view(s.bounds())).collect();
hits.push(SearchHit { page: i, rects });
if hits.len() >= limit {
return Ok(hits);
}
}
}
Ok(hits)
}
pub(crate) fn page_frame(page: &PdfPage) -> crate::geometry::PageFrame {
let crop = page.boundaries().crop().or_else(|_| page.boundaries().media()).map(|b| b.bounds).unwrap_or(PdfRect::ZERO);
let rotate = match page.rotation() {
Ok(PdfPageRenderRotation::Degrees90) => 90,
Ok(PdfPageRenderRotation::Degrees180) => 180,
Ok(PdfPageRenderRotation::Degrees270) => 270,
_ => 0,
};
let c = [crop.left().value, crop.bottom().value, crop.right().value, crop.top().value];
crate::geometry::PageFrame { crop: [c[0].min(c[2]), c[1].min(c[3]), c[0].max(c[2]), c[1].max(c[3])], rotate }
}
impl crate::geometry::PageFrame {
/// A user-space rectangle → view space.
pub(crate) fn user_to_view(&self, r: PdfRect) -> ViewRect {
let [x0, y0, x1, y1] = self.crop;
let (l, b, rt, t) = (r.left().value, r.bottom().value, r.right().value, r.top().value);
let (vx0, vy0, vx1, vy1) = match self.rotate {
90 => (b - y0, l - x0, t - y0, rt - x0),
180 => (x1 - rt, b - y0, x1 - l, t - y0),
270 => (y1 - t, x1 - rt, y1 - b, x1 - l),
_ => (l - x0, y1 - t, rt - x0, y1 - b),
};
ViewRect { x: vx0.min(vx1), y: vy0.min(vy1), w: (vx1 - vx0).abs(), h: (vy1 - vy0).abs() }
}
}