1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
//! Region erasure and running-header/footer removal.
//!
//! Split out of the parent's single 18,544-line `impl PdfDocument`, which made
//! `document.rs` 1.2 MiB and tripped the 500 KiB file-safety limit. A child module's
//! `impl` is the same inherent impl and sees the parent's private items unchanged. ~keep
use super::*;
impl PdfDocument {
/// Mark a specific rectangular region on a page for erasure.
///
/// Content in this region will be excluded from all subsequent text extractions.
pub fn erase_region(&self, page_index: usize, rect: crate::geometry::Rect) -> Result<()> {
self.erase_regions
.lock_or_recover()
.entry(page_index)
.or_default()
.push(rect);
// Redaction changes a page's spans; drop the span cache. ~keep
self.page_spans_cache.lock_or_recover().clear();
self.search_index.lock_or_recover().clear();
Ok(())
}
/// Clear all erase regions for a page.
pub fn clear_erase_regions(&self, page_index: usize) -> Result<()> {
self.erase_regions.lock_or_recover().remove(&page_index);
self.page_spans_cache.lock_or_recover().clear();
self.search_index.lock_or_recover().clear();
Ok(())
}
/// Identify and remove headers.
///
/// Uses spec-compliant /Artifact tags when available (100% accuracy), or
/// falls back to heuristic analysis of the top 15% of pages.
pub fn remove_headers(&self, threshold: f32) -> Result<usize> {
if !(0.0..=1.0).contains(&threshold) {
return Err(crate::error::Error::InvalidOperation(
"Threshold must be between 0.0 and 1.0".to_string(),
));
}
self.remove_repeated_text(PageArea::Header, threshold)
}
/// Identify and remove footers.
///
/// Uses spec-compliant /Artifact tags when available (100% accuracy), or
/// falls back to heuristic analysis of the bottom 15% of pages.
pub fn remove_footers(&self, threshold: f32) -> Result<usize> {
if !(0.0..=1.0).contains(&threshold) {
return Err(crate::error::Error::InvalidOperation(
"Threshold must be between 0.0 and 1.0".to_string(),
));
}
self.remove_repeated_text(PageArea::Footer, threshold)
}
/// Identify and remove both headers and footers.
///
/// Prioritizes ISO 32000 spec-compliant /Artifact tags, with a heuristic
/// fallback for untagged PDFs.
///
/// # Arguments
/// * `threshold` - Fraction of pages (0.0-1.0) where text must repeat to be removed (heuristic mode only).
pub fn remove_artifacts(&self, threshold: f32) -> Result<usize> {
if !(0.0..=1.0).contains(&threshold) {
return Err(crate::error::Error::InvalidOperation(
"Threshold must be between 0.0 and 1.0".to_string(),
));
}
let h = self.remove_headers(threshold)?;
let f = self.remove_footers(threshold)?;
Ok(h + f)
}
/// Helper to remove repeated text in a specific page area.
fn remove_repeated_text(&self, area: PageArea, threshold: f32) -> Result<usize> {
use crate::extractors::text::{ArtifactType, PaginationSubtype};
use std::collections::{HashMap, HashSet};
let page_count = self.page_count()?;
if page_count < 1 {
return Ok(0);
}
let mut removed_count = 0;
// 1. Spec-Compliant Removal (Priority)
// If the PDF uses /Artifact tags (Tagged PDF), we use those directly as they are 100% accurate.
// ~keep
for page_idx in 0..page_count {
let spans = self.extract_spans(page_idx)?;
for span in spans {
if let Some(ArtifactType::Pagination(subtype)) = span.artifact_type {
let is_match = match (area, subtype) {
(PageArea::Header, PaginationSubtype::Header) => true,
(PageArea::Footer, PaginationSubtype::Footer) => true,
_ => false,
};
if is_match {
self.erase_region(page_idx, span.bbox)?;
removed_count += 1;
}
}
}
}
if removed_count > 0 {
tracing::info!(target: LOG_TARGET,
count = removed_count,
area = if area == PageArea::Header { "headers" } else { "footers" },
"removed spec-compliant artifacts"
);
return Ok(removed_count);
}
if page_count < 2 {
return Ok(0);
}
// Each entry records the IN-ZONE occurrences of a repeated string as
// (page, bbox). Keeping the bbox (not just the page set) lets us both
// (a) erase only the header/footer occurrence and never an identically
// worded span elsewhere on the page, and (b) require the occurrences to
// share a position before treating the string as chrome. ~keep
let mut occurrences: HashMap<String, Vec<(usize, crate::geometry::Rect)>> = HashMap::new();
// Sanitize threshold to avoid min_occurrences becoming 0 for invalid inputs. ~keep
let clamped_threshold = if threshold.is_finite() {
threshold.clamp(0.0, 1.0)
} else {
1.0
};
let raw_min = (page_count as f32 * clamped_threshold).ceil();
let min_occurrences = if raw_min < 1.0 { 1 } else { raw_min as usize };
for page_idx in 0..page_count {
let height = self.get_page_media_box(page_idx)?.3;
let zone = match area {
PageArea::Header => height * 0.85,
PageArea::Footer => height * 0.15,
};
let spans = self.extract_spans(page_idx)?;
for span in spans.iter() {
let is_in_zone = match area {
PageArea::Header => span.bbox.y > zone,
PageArea::Footer => (span.bbox.y + span.bbox.height) < zone,
};
if is_in_zone {
let text = span.text.trim().to_string();
if text.len() > 3 && !text.chars().all(|c| c.is_numeric()) {
occurrences.entry(text).or_default().push((page_idx, span.bbox));
}
}
}
}
// Genuine running headers/footers are position-locked: the same string
// lands at the same x/y on every page. A form label or instruction that
// merely happens to recur — e.g. "Check if:", "(see instructions)",
// "Name(s) shown on return" on a multi-page tax form — drifts in x or y
// between pages. Requiring positional consistency separates "recurs
// because it is chrome" from "recurs because it is the same real label"
// without deleting content. ~keep
const POS_TOL_X: f32 = 40.0;
const POS_TOL_Y: f32 = 24.0;
for (_text, occs) in occurrences {
let distinct_pages: HashSet<usize> = occs.iter().map(|(p, _)| *p).collect();
if distinct_pages.len() < min_occurrences {
continue;
}
let (mut min_x, mut max_x) = (f32::MAX, f32::MIN);
let (mut min_y, mut max_y) = (f32::MAX, f32::MIN);
for (_, bbox) in &occs {
min_x = min_x.min(bbox.x);
max_x = max_x.max(bbox.x);
min_y = min_y.min(bbox.y);
max_y = max_y.max(bbox.y);
}
if (max_x - min_x) > POS_TOL_X || (max_y - min_y) > POS_TOL_Y {
continue;
}
for (page_idx, bbox) in occs {
self.erase_region(page_idx, bbox)?;
removed_count += 1;
}
}
Ok(removed_count)
}
/// Erase existing header content.
///
/// Identifies existing text in the header area (top 15%) and marks it for erasure.
pub fn erase_header(&self, page_index: usize) -> Result<()> {
self.erase_page_area_content(page_index, PageArea::Header)
}
/// Deprecated: Use `erase_header` instead.
#[deprecated(note = "use erase_header instead")]
pub fn edit_header(&self, page_index: usize) -> Result<()> {
self.erase_header(page_index)
}
/// Erase existing footer content.
///
/// Identifies existing text in the footer area (bottom 15%) and marks it for erasure.
pub fn erase_footer(&self, page_index: usize) -> Result<()> {
self.erase_page_area_content(page_index, PageArea::Footer)
}
/// Deprecated: Use `erase_footer` instead.
#[deprecated(note = "use erase_footer instead")]
pub fn edit_footer(&self, page_index: usize) -> Result<()> {
self.erase_footer(page_index)
}
/// Erase both header and footer content.
///
/// This is a convenience method that calls both erase_header and erase_footer.
pub fn erase_artifacts(&self, page_index: usize) -> Result<()> {
self.erase_header(page_index)?;
self.erase_footer(page_index)?;
Ok(())
}
/// Helper to erase content in a specific page area.
fn erase_page_area_content(&self, page_index: usize, area: PageArea) -> Result<()> {
let height = self.get_page_media_box(page_index)?.3;
let zone = match area {
PageArea::Header => height * 0.85,
PageArea::Footer => height * 0.15,
};
let spans = self.extract_spans(page_index)?;
for span in spans {
let is_in_zone = match area {
PageArea::Header => span.bbox.y > zone,
PageArea::Footer => (span.bbox.y + span.bbox.height) < zone,
};
if is_in_zone {
self.erase_region(page_index, span.bbox)?;
}
}
Ok(())
}
/// Determine if a space should be inserted between two text spans.
///
/// According to PDF spec (ISO 32000-1:2008 Section 9.3.3), word spacing
/// only applies to actual space characters (0x20). Many PDFs (especially
/// academic papers) use precise positioning instead of space characters.
/// This function detects such gaps and inserts spaces heuristically.
///
/// # Algorithm
/// 1. Check if spans are on the same line (Y positions similar)
/// 2. Calculate horizontal gap between end of prev span and start of current span
/// 3. Insert space if gap exceeds threshold (0.25 × font size)
///
/// # Arguments
/// * `prev` - Previous text span
/// * `current` - Current text span
///
/// Filter leaked PDF internal metadata from extracted text.
///
/// Some PDFs embed inline ColorSpace definitions (CalRGB, CalGray, Lab) that
/// get parsed as text content. This removes known metadata patterns like
/// "WhitePoint [ ... ]", "BlackPoint [ ... ]", "Gamma [ ... ]", "Matrix [ ... ]".
pub(super) fn filter_leaked_metadata(text: &str) -> String {
// Known PDF metadata keys that should never appear in extracted text.
// These come from CalRGB/CalGray/Lab color space dictionaries. ~keep
const METADATA_PATTERNS: &[&str] = &["WhitePoint", "BlackPoint", "Gamma", "Matrix", "CalRGB", "CalGray"];
if !METADATA_PATTERNS.iter().any(|p| text.contains(p)) {
return text.to_string();
}
let mut result = String::with_capacity(text.len());
for line in text.lines() {
let trimmed = line.trim();
let is_metadata = METADATA_PATTERNS.iter().any(|pattern| {
if let Some(rest) = trimmed.strip_prefix(pattern) {
let rest = rest.trim_start();
rest.is_empty() || rest.starts_with('[') || rest.starts_with('/') || rest.starts_with('<')
} else {
false
}
});
if !is_metadata {
if !result.is_empty() {
result.push('\n');
}
result.push_str(line);
}
}
result
}
}