use crate::content_stream::{ContentStreamParser, ContentToken};
use crate::filters::decode_stream_data;
use crate::ref_chain::{resolve_ref_chain, terminal_ref_of_chain};
use crate::{Dictionary, Error, Object, ObjectRef, Pdf, Result};
use std::collections::{BTreeMap, BTreeSet};
use std::io::{Read, Seek};
type UsedNames = BTreeMap<Vec<u8>, BTreeSet<Vec<u8>>>;
type CatRefKey = (Vec<u8>, ObjectRef);
struct CatRefInfo {
group_count: usize,
used_union: BTreeSet<Vec<u8>>,
protected: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum ResGroupKey {
Indirect(ObjectRef),
AncestorInline(ObjectRef),
PageInline(ObjectRef),
}
fn res_group_key(loc: &ResourcesLoc, page_ref: ObjectRef) -> Option<ResGroupKey> {
match loc {
ResourcesLoc::Indirect(r) => Some(ResGroupKey::Indirect(*r)),
ResourcesLoc::AncestorInline(a) => Some(ResGroupKey::AncestorInline(*a)),
ResourcesLoc::PageInline => Some(ResGroupKey::PageInline(page_ref)),
ResourcesLoc::None => None,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum ResourcesLoc {
None,
PageInline,
AncestorInline(ObjectRef),
Indirect(ObjectRef),
}
const RESOURCE_CATEGORIES: &[&str] = &[
"Font",
"XObject",
"ColorSpace",
"Pattern",
"Shading",
"ExtGState",
"Properties",
];
fn is_builtin_color_space_cs_op(name: &[u8]) -> bool {
matches!(
name,
b"DeviceGray" | b"DeviceRGB" | b"DeviceCMYK" | b"Pattern"
)
}
fn is_builtin_inline_image_cs(name: &[u8]) -> bool {
matches!(
name,
b"DeviceGray"
| b"DeviceRGB"
| b"DeviceCMYK"
| b"Pattern"
| b"G"
| b"RGB"
| b"CMYK"
| b"I"
)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum RemoveUnreferencedResources {
#[default]
Auto,
Yes,
No,
}
pub fn remove_unreferenced_resources<R: Read + Seek>(
pdf: &mut Pdf<R>,
mode: RemoveUnreferencedResources,
) -> Result<()> {
if mode == RemoveUnreferencedResources::No {
return Ok(());
}
let page_refs = crate::pages::page_refs(pdf)?;
let mut page_res_loc: Vec<ResourcesLoc> = Vec::with_capacity(page_refs.len());
for &pr in &page_refs {
page_res_loc.push(resources_location(pdf, pr)?);
}
let mut ref_count: BTreeMap<ObjectRef, usize> = BTreeMap::new();
let mut ancestor_count: BTreeMap<ObjectRef, usize> = BTreeMap::new();
for loc in &page_res_loc {
match loc {
ResourcesLoc::Indirect(r) => {
*ref_count.entry(*r).or_insert(0) += 1;
}
ResourcesLoc::AncestorInline(a) => {
*ancestor_count.entry(*a).or_insert(0) += 1;
}
_ => {}
}
}
let mut ref_used: BTreeMap<ObjectRef, UsedNames> = BTreeMap::new();
let mut ancestor_inline_used: BTreeMap<ObjectRef, UsedNames> = BTreeMap::new();
let mut inline_used: Vec<Option<UsedNames>> = vec![None; page_refs.len()];
let mut protected_groups: BTreeSet<ResGroupKey> = BTreeSet::new();
for (i, &page_ref) in page_refs.iter().enumerate() {
let is_shared = match &page_res_loc[i] {
ResourcesLoc::Indirect(r) => ref_count.get(r).copied().unwrap_or(0) > 1,
ResourcesLoc::AncestorInline(a) => ancestor_count.get(a).copied().unwrap_or(0) > 1,
_ => false, };
if mode == RemoveUnreferencedResources::Auto && is_shared {
continue;
}
let used = match collect_used_names_for_page(pdf, page_ref)? {
Some(used) => used,
None => {
if let Some(key) = res_group_key(&page_res_loc[i], page_ref) {
protected_groups.insert(key);
}
continue;
}
};
match &page_res_loc[i] {
ResourcesLoc::Indirect(r) => {
let entry = ref_used.entry(*r).or_default();
for (cat, names) in used {
entry.entry(cat).or_default().extend(names);
}
}
ResourcesLoc::AncestorInline(a) => {
let entry = ancestor_inline_used.entry(*a).or_default();
for (cat, names) in used {
entry.entry(cat).or_default().extend(names);
}
}
ResourcesLoc::PageInline => {
inline_used[i] = Some(used);
}
ResourcesLoc::None => {}
}
}
let mut cat_ref_map: BTreeMap<CatRefKey, CatRefInfo> = BTreeMap::new();
let mut cat_ref_seen_groups: BTreeMap<CatRefKey, BTreeSet<ResGroupKey>> = BTreeMap::new();
for (i, loc) in page_res_loc.iter().enumerate() {
let res_dict_opt: Option<Dictionary> = match loc {
ResourcesLoc::Indirect(r) => match pdf.resolve_borrowed(*r) {
Ok(Object::Dictionary(d)) => Some(d.clone()),
_ => None,
},
ResourcesLoc::PageInline => {
match pdf.resolve_borrowed(page_refs[i]) {
Ok(Object::Dictionary(page_dict)) => {
match page_dict.get("Resources").cloned() {
Some(Object::Dictionary(d)) => Some(d),
_ => None,
}
}
_ => None,
}
}
ResourcesLoc::AncestorInline(a) => match pdf.resolve_borrowed(*a) {
Ok(Object::Dictionary(anc_dict)) => match anc_dict.get("Resources").cloned() {
Some(Object::Dictionary(d)) => Some(d),
_ => None,
},
_ => None,
},
ResourcesLoc::None => None,
};
let Some(res_dict) = res_dict_opt else {
continue;
};
let group_key: ResGroupKey = res_group_key(loc, page_refs[i])
.unwrap_or_else(|| unreachable!("None loc filtered above by res_dict_opt"));
let group_protected = protected_groups.contains(&group_key);
let group_used: Option<&UsedNames> = match loc {
ResourcesLoc::Indirect(r) => ref_used.get(r),
ResourcesLoc::AncestorInline(a) => ancestor_inline_used.get(a),
ResourcesLoc::PageInline => inline_used[i].as_ref(),
ResourcesLoc::None => None,
};
for &category in RESOURCE_CATEGORIES {
let cat_key = category.as_bytes();
if let Some(cat_ref) = res_dict.get(category).and_then(Object::as_ref_id) {
let key: CatRefKey = (cat_key.to_vec(), cat_ref);
let seen = cat_ref_seen_groups.entry(key.clone()).or_default();
if seen.insert(group_key) {
let info = cat_ref_map
.entry(key.clone())
.or_insert_with(|| CatRefInfo {
group_count: 0,
used_union: BTreeSet::new(),
protected: false,
});
info.group_count += 1;
info.protected |= group_protected;
if let Some(used_map) = group_used {
if let Some(names) = used_map.get(cat_key) {
info.used_union.extend(names.iter().cloned());
}
}
}
}
}
}
for (res_ref, used) in &ref_used {
if protected_groups.contains(&ResGroupKey::Indirect(*res_ref)) {
continue;
}
prune_resources_object(pdf, *res_ref, used, &cat_ref_map, mode)?;
}
for (ancestor_ref, used) in &ancestor_inline_used {
if protected_groups.contains(&ResGroupKey::AncestorInline(*ancestor_ref)) {
continue;
}
prune_ancestor_inline_resources(pdf, *ancestor_ref, used, &cat_ref_map, mode)?;
}
for (i, used_opt) in inline_used.iter().enumerate() {
let Some(used) = used_opt else { continue };
let page_ref = page_refs[i];
prune_inline_resources(pdf, page_ref, used, &cat_ref_map, mode)?;
}
Ok(())
}
fn resources_location<R: Read + Seek>(
pdf: &mut Pdf<R>,
page_ref: ObjectRef,
) -> Result<ResourcesLoc> {
let mut current = page_ref;
let mut seen: BTreeSet<ObjectRef> = BTreeSet::new();
let mut depth = 0usize;
const MAX_DEPTH: usize = 100;
loop {
if depth >= MAX_DEPTH {
return Ok(ResourcesLoc::None);
}
if !seen.insert(current) {
return Ok(ResourcesLoc::None); }
depth += 1;
let node_obj = pdf.resolve_borrowed(current)?;
let Some(dict) = node_obj.as_dict() else {
return Ok(ResourcesLoc::None);
};
enum ResKind {
Ref(ObjectRef),
Inline,
Absent,
Other,
}
let res_kind = match dict.get("Resources") {
Some(Object::Reference(r)) => ResKind::Ref(*r),
Some(Object::Dictionary(_)) => ResKind::Inline,
Some(Object::Null) | None => ResKind::Absent,
_ => ResKind::Other,
};
let parent_ref: Option<ObjectRef> = match dict.get("Parent") {
Some(Object::Reference(p)) => Some(*p),
_ => None,
};
match res_kind {
ResKind::Ref(r) => {
let terminal_ref = terminal_ref_of_chain(pdf, r)?;
match pdf.resolve_borrowed(terminal_ref)? {
Object::Null => match parent_ref {
Some(parent) => current = parent,
None => return Ok(ResourcesLoc::None),
},
Object::Dictionary(_) => return Ok(ResourcesLoc::Indirect(terminal_ref)),
_ => return Ok(ResourcesLoc::None),
}
}
ResKind::Inline => {
if current == page_ref {
return Ok(ResourcesLoc::PageInline);
} else {
return Ok(ResourcesLoc::AncestorInline(current));
}
}
ResKind::Absent => match parent_ref {
Some(parent) => current = parent,
None => return Ok(ResourcesLoc::None),
},
ResKind::Other => return Ok(ResourcesLoc::None),
}
}
}
fn collect_used_names_for_page<R: Read + Seek>(
pdf: &mut Pdf<R>,
page_ref: ObjectRef,
) -> Result<Option<UsedNames>> {
let content_bytes = match crate::pages::page_content_bytes(pdf, page_ref) {
Ok(bytes) => bytes,
Err(_) => return Ok(None),
};
let page_resources = crate::pages::resolve_inherited_resources(pdf, page_ref)?;
let mut used: UsedNames = BTreeMap::new();
let mut visited_forms: BTreeSet<(ObjectRef, ObjectRef)> = BTreeSet::new();
let complete = {
let mut ctx = CollectCtx {
pdf,
used: &mut used,
visited: &mut visited_forms,
};
let page_scope = Scope {
resources: page_resources.as_ref(),
record_direct: true,
owner: page_ref,
};
collect_from_stream(&mut ctx, &content_bytes, page_scope, 0)?
};
Ok(complete.then_some(used))
}
const MAX_FORM_DEPTH: usize = 64;
struct CollectCtx<'a, R: Read + Seek> {
pdf: &'a mut Pdf<R>,
used: &'a mut UsedNames,
visited: &'a mut BTreeSet<(ObjectRef, ObjectRef)>,
}
#[derive(Clone, Copy)]
struct Scope<'a> {
resources: Option<&'a Dictionary>,
record_direct: bool,
owner: ObjectRef,
}
fn collect_from_stream<R: Read + Seek>(
ctx: &mut CollectCtx<'_, R>,
stream_bytes: &[u8],
scope: Scope<'_>,
depth: usize,
) -> Result<bool> {
let parser = ContentStreamParser::new(stream_bytes);
for token_result in parser {
let Ok(token) = token_result else {
return Ok(false);
};
match token {
ContentToken::Op { operands, operator } => {
if !process_operator(ctx, &operator, &operands, scope, depth)? {
return Ok(false);
}
}
ContentToken::InlineImage { dict, .. } if scope.record_direct => {
let cs_val = dict.get("CS").or_else(|| dict.get("ColorSpace")).cloned();
if let Some(name) = cs_val.and_then(Object::into_name) {
if !is_builtin_inline_image_cs(&name) {
ctx.used
.entry(b"ColorSpace".to_vec())
.or_default()
.insert(name);
}
}
}
ContentToken::InlineImage { .. } | ContentToken::Comment(_) => {}
}
}
Ok(true)
}
fn process_operator<R: Read + Seek>(
ctx: &mut CollectCtx<'_, R>,
operator: &[u8],
operands: &[Object],
scope: Scope<'_>,
depth: usize,
) -> Result<bool> {
if operator == b"Do" {
if let Some(name) = operands.first().and_then(Object::as_name) {
if scope.record_direct {
ctx.used
.entry(b"XObject".to_vec())
.or_default()
.insert(name.to_vec());
}
return recurse_form_xobject(ctx, name, scope, depth);
}
return Ok(true);
}
if !scope.record_direct {
return Ok(true);
}
let recorded: Option<(&[u8], &[u8])> = match operator {
b"Tf" => operands
.first()
.and_then(Object::as_name)
.map(|n| (&b"Font"[..], n)),
b"gs" => operands
.first()
.and_then(Object::as_name)
.map(|n| (&b"ExtGState"[..], n)),
b"cs" | b"CS" => operands
.first()
.and_then(Object::as_name)
.filter(|n| !is_builtin_color_space_cs_op(n))
.map(|n| (&b"ColorSpace"[..], n)),
b"scn" | b"SCN" => operands
.last()
.and_then(Object::as_name)
.map(|n| (&b"Pattern"[..], n)),
b"sh" => operands
.first()
.and_then(Object::as_name)
.map(|n| (&b"Shading"[..], n)),
b"BDC" | b"DP" => operands
.get(1)
.and_then(Object::as_name)
.map(|n| (&b"Properties"[..], n)),
_ => None,
};
if let Some((category, name)) = recorded {
ctx.used
.entry(category.to_vec())
.or_default()
.insert(name.to_vec());
}
Ok(true)
}
fn is_form_xobject(dict: &Dictionary) -> bool {
matches!(dict.get("Subtype"), Some(Object::Name(n)) if n.as_slice() == b"Form")
}
fn recurse_form_xobject<R: Read + Seek>(
ctx: &mut CollectCtx<'_, R>,
xobject_name: &[u8],
caller: Scope<'_>,
depth: usize,
) -> Result<bool> {
if depth >= MAX_FORM_DEPTH {
return Ok(false);
}
let xobj_val: Option<Object> = match caller.resources.and_then(|res| res.get("XObject")) {
Some(Object::Dictionary(xobj_dict)) => xobj_dict.get(xobject_name).cloned(),
Some(cat_ref @ Object::Reference(_)) => resolve_ref_chain(ctx.pdf, cat_ref)?
.0
.into_dict()
.and_then(|xobj_dict| xobj_dict.get(xobject_name).cloned()),
_ => None,
};
let Some(xobj_val) = xobj_val else {
return Ok(true);
};
let (stream, xobj_ref) = match xobj_val {
Object::Reference(r) => {
let (resolved, terminal) = resolve_ref_chain(ctx.pdf, &Object::Reference(r))?;
match resolved.into_stream() {
Some(s) => (s, terminal.unwrap_or(r)),
None => return Ok(true), }
}
Object::Stream(s) => {
return Ok(!is_form_xobject(&s.dict));
}
_ => return Ok(true), };
if !is_form_xobject(&stream.dict) {
return Ok(true);
}
let form_resources: Option<Dictionary> = match stream.dict.get("Resources") {
Some(Object::Dictionary(d)) => Some(d.clone()),
Some(res_ref @ Object::Reference(_)) => resolve_ref_chain(ctx.pdf, res_ref)?.0.into_dict(),
_ => None,
};
let form_has_own_resources = form_resources.is_some();
let scope_owner = if form_has_own_resources {
xobj_ref
} else {
caller.owner
};
if !ctx.visited.insert((xobj_ref, scope_owner)) {
return Ok(true); }
let form_bytes = match decode_stream_data(&stream.dict, &stream.data) {
Ok(b) => b,
Err(_) => return Ok(false),
};
let child = if form_has_own_resources {
Scope {
resources: form_resources.as_ref(),
record_direct: false,
owner: scope_owner,
}
} else {
Scope {
resources: caller.resources,
record_direct: true,
owner: scope_owner,
}
};
collect_from_stream(ctx, &form_bytes, child, depth + 1)
}
fn prune_resources_object<R: Read + Seek>(
pdf: &mut Pdf<R>,
res_ref: ObjectRef,
used: &UsedNames,
cat_ref_map: &BTreeMap<CatRefKey, CatRefInfo>,
mode: RemoveUnreferencedResources,
) -> Result<()> {
let obj = pdf.resolve_borrowed(res_ref)?;
let Some(mut res_dict) = obj.as_dict().cloned() else {
return Ok(()); };
apply_pruning(pdf, &mut res_dict, used, cat_ref_map, mode)?;
pdf.set_object(res_ref, Object::Dictionary(res_dict));
Ok(())
}
fn prune_inline_resources<R: Read + Seek>(
pdf: &mut Pdf<R>,
page_ref: ObjectRef,
used: &UsedNames,
cat_ref_map: &BTreeMap<CatRefKey, CatRefInfo>,
mode: RemoveUnreferencedResources,
) -> Result<()> {
let page_obj = pdf.resolve_borrowed(page_ref)?;
let Some(mut page_dict) = page_obj.as_dict().cloned() else {
return Err(Error::Unsupported(format!(
"page {page_ref} resolved to non-dictionary"
)));
};
let resources_val = page_dict.get("Resources").cloned();
match resources_val {
Some(Object::Dictionary(mut res_dict)) => {
apply_pruning(pdf, &mut res_dict, used, cat_ref_map, mode)?;
page_dict.insert("Resources", Object::Dictionary(res_dict));
}
_ => return Ok(()), }
pdf.set_object(page_ref, Object::Dictionary(page_dict));
Ok(())
}
fn prune_ancestor_inline_resources<R: Read + Seek>(
pdf: &mut Pdf<R>,
ancestor_ref: ObjectRef,
used: &UsedNames,
cat_ref_map: &BTreeMap<CatRefKey, CatRefInfo>,
mode: RemoveUnreferencedResources,
) -> Result<()> {
let ancestor_obj = pdf.resolve_borrowed(ancestor_ref)?;
let Some(mut ancestor_dict) = ancestor_obj.as_dict().cloned() else {
return Ok(()); };
let resources_val = ancestor_dict.get("Resources").cloned();
match resources_val {
Some(Object::Dictionary(mut res_dict)) => {
apply_pruning(pdf, &mut res_dict, used, cat_ref_map, mode)?;
ancestor_dict.insert("Resources", Object::Dictionary(res_dict));
}
_ => return Ok(()), }
pdf.set_object(ancestor_ref, Object::Dictionary(ancestor_dict));
Ok(())
}
fn apply_pruning<R: Read + Seek>(
pdf: &mut Pdf<R>,
res_dict: &mut Dictionary,
used: &UsedNames,
cat_ref_map: &BTreeMap<CatRefKey, CatRefInfo>,
mode: RemoveUnreferencedResources,
) -> Result<()> {
for &category in RESOURCE_CATEGORIES {
let cat_key = category.as_bytes();
let cat_val = res_dict.get(category).cloned();
match cat_val {
Some(Object::Dictionary(mut cat_dict)) => {
let empty_set = BTreeSet::new();
let used_names = used.get(cat_key).unwrap_or(&empty_set);
let to_remove: Vec<Vec<u8>> = cat_dict
.iter()
.filter(|(k, _)| !used_names.contains(*k))
.map(|(k, _)| k.to_vec())
.collect();
for key in to_remove {
cat_dict.remove(&key);
}
if cat_dict.iter().next().is_none() {
res_dict.remove(category);
} else {
res_dict.insert(category, Object::Dictionary(cat_dict));
}
}
Some(Object::Reference(cat_ref)) => {
let map_key: CatRefKey = (cat_key.to_vec(), cat_ref);
if let Some(info) = cat_ref_map.get(&map_key) {
if info.protected {
continue;
}
if mode == RemoveUnreferencedResources::Auto && info.group_count > 1 {
continue;
}
let resolved = pdf.resolve_borrowed(cat_ref)?;
let Some(mut cat_dict) = resolved.as_dict().cloned() else {
continue; };
let to_remove: Vec<Vec<u8>> = cat_dict
.iter()
.filter(|(k, _)| !info.used_union.contains(*k))
.map(|(k, _)| k.to_vec())
.collect();
for key in to_remove {
cat_dict.remove(&key);
}
if cat_dict.iter().next().is_none() {
res_dict.remove(category);
} else {
pdf.set_object(cat_ref, Object::Dictionary(cat_dict));
}
} else {
let resolved = pdf.resolve_borrowed(cat_ref)?;
let Some(mut cat_dict) = resolved.as_dict().cloned() else {
continue;
};
let empty_set = BTreeSet::new();
let used_names = used.get(cat_key).unwrap_or(&empty_set);
let to_remove: Vec<Vec<u8>> = cat_dict
.iter()
.filter(|(k, _)| !used_names.contains(*k))
.map(|(k, _)| k.to_vec())
.collect();
for key in to_remove {
cat_dict.remove(&key);
}
if cat_dict.iter().next().is_none() {
res_dict.remove(category);
} else {
pdf.set_object(cat_ref, Object::Dictionary(cat_dict));
}
}
}
_ => {
continue;
}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Cursor;
fn build_inherited_indirect_resources_pdf(resources_ref: u32, obj4_body: &str) -> Vec<u8> {
let content = b"BT /F1 12 Tf 10 10 Td (hi) Tj ET";
let mut out: Vec<u8> = b"%PDF-1.4\n".to_vec();
let mut offs: BTreeMap<u32, u64> = BTreeMap::new();
let dicts: Vec<(u32, String)> = vec![
(1, "<< /Type /Catalog /Pages 2 0 R >>".into()),
(
2,
format!("<< /Type /Pages /Kids [3 0 R] /Count 1 /Resources {resources_ref} 0 R >>"),
),
(
3,
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 6 0 R >>".into(),
),
(4, obj4_body.into()),
(
5,
"<< /Font << \
/F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> \
/F2 << /Type /Font /Subtype /Type1 /BaseFont /Courier >> \
>> >>"
.into(),
),
];
for (n, s) in &dicts {
offs.insert(*n, out.len() as u64);
out.extend_from_slice(format!("{n} 0 obj\n{s}\nendobj\n").as_bytes());
}
offs.insert(6, out.len() as u64);
out.extend_from_slice(
format!("6 0 obj\n<< /Length {} >>\nstream\n", content.len()).as_bytes(),
);
out.extend_from_slice(content);
out.extend_from_slice(b"\nendstream\nendobj\n");
let xref_start = out.len() as u64;
let total = 7u32;
out.extend_from_slice(format!("xref\n0 {total}\n0000000000 65535 f \n").as_bytes());
for i in 1..total {
out.extend_from_slice(format!("{:010} 00000 n \n", offs[&i]).as_bytes());
}
out.extend_from_slice(
format!("trailer\n<< /Size {total} /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n")
.as_bytes(),
);
out
}
fn font_keys_after_prune(
bytes: Vec<u8>,
mode: RemoveUnreferencedResources,
terminal_obj: u32,
carriers: &[(u32, u32)],
) -> Vec<String> {
let mut pdf = Pdf::open(Cursor::new(bytes)).expect("PDF should parse");
for &(from, to) in carriers {
pdf.set_object(
ObjectRef::new(from, 0),
Object::Reference(ObjectRef::new(to, 0)),
);
}
remove_unreferenced_resources(&mut pdf, mode).expect("prune should succeed");
let obj = pdf
.resolve_borrowed(ObjectRef::new(terminal_obj, 0))
.expect("terminal obj resolves");
let res_dict = obj.as_dict().expect("terminal obj is the /Resources dict");
let font = res_dict
.get("Font")
.and_then(Object::as_dict)
.expect("/Font present");
font.iter()
.map(|(k, _)| String::from_utf8(k.to_vec()).unwrap())
.collect()
}
#[test]
fn prune_follows_holder_chain_to_terminal_inherited_resources() {
let keys = font_keys_after_prune(
build_inherited_indirect_resources_pdf(4, "5 0 R"),
RemoveUnreferencedResources::Auto,
5,
&[(4, 5)],
);
assert!(
keys.contains(&"F1".to_string()),
"F1 (used) must remain: {keys:?}"
);
assert!(
!keys.contains(&"F2".to_string()),
"F2 (unused) must be pruned from the terminal dict: {keys:?}"
);
}
#[test]
fn prune_single_hop_indirect_inherited_resources_unaffected() {
let keys = font_keys_after_prune(
build_inherited_indirect_resources_pdf(5, "<< >>"),
RemoveUnreferencedResources::Auto,
5,
&[],
);
assert!(
keys.contains(&"F1".to_string()),
"F1 (used) must remain: {keys:?}"
);
assert!(
!keys.contains(&"F2".to_string()),
"F2 (unused) must be pruned: {keys:?}"
);
}
fn build_shared_terminal_distinct_carriers_pdf() -> Vec<u8> {
let content_a = b"BT /F1 12 Tf 10 10 Td (A) Tj ET";
let content_b = b"BT /F2 12 Tf 10 10 Td (B) Tj ET";
let mut out: Vec<u8> = b"%PDF-1.4\n".to_vec();
let mut offs: BTreeMap<u32, u64> = BTreeMap::new();
let dicts: Vec<(u32, String)> = vec![
(1, "<< /Type /Catalog /Pages 2 0 R >>".into()),
(2, "<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>".into()),
(
3,
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 5 0 R \
/Resources 7 0 R >>"
.into(),
),
(
4,
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 6 0 R \
/Resources 9 0 R >>"
.into(),
),
(7, "8 0 R".into()), (
8,
"<< /Font << \
/F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> \
/F2 << /Type /Font /Subtype /Type1 /BaseFont /Courier >> \
>> >>"
.into(),
),
(9, "8 0 R".into()), ];
for (n, s) in &dicts {
offs.insert(*n, out.len() as u64);
out.extend_from_slice(format!("{n} 0 obj\n{s}\nendobj\n").as_bytes());
}
for (n, content) in [(5u32, &content_a[..]), (6u32, &content_b[..])] {
offs.insert(n, out.len() as u64);
out.extend_from_slice(
format!("{n} 0 obj\n<< /Length {} >>\nstream\n", content.len()).as_bytes(),
);
out.extend_from_slice(content);
out.extend_from_slice(b"\nendstream\nendobj\n");
}
let xref_start = out.len() as u64;
let total = 10u32;
out.extend_from_slice(format!("xref\n0 {total}\n0000000000 65535 f \n").as_bytes());
for i in 1..total {
out.extend_from_slice(format!("{:010} 00000 n \n", offs[&i]).as_bytes());
}
out.extend_from_slice(
format!("trailer\n<< /Size {total} /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n")
.as_bytes(),
);
out
}
#[test]
fn shared_terminal_via_distinct_carriers_not_over_pruned() {
for mode in [
RemoveUnreferencedResources::Auto,
RemoveUnreferencedResources::Yes,
] {
let keys = font_keys_after_prune(
build_shared_terminal_distinct_carriers_pdf(),
mode,
8,
&[(7, 8), (9, 8)],
);
assert!(
keys.contains(&"F1".to_string()) && keys.contains(&"F2".to_string()),
"shared terminal must keep both fonts in {mode:?} mode: {keys:?}"
);
}
}
fn build_null_chain_resources_pdf() -> Vec<u8> {
let content_a = b"BT /F1 12 Tf 10 10 Td (A) Tj ET";
let content_b = b"BT /F2 12 Tf 10 10 Td (B) Tj ET";
let mut out: Vec<u8> = b"%PDF-1.4\n".to_vec();
let mut offs: BTreeMap<u32, u64> = BTreeMap::new();
let dicts: Vec<(u32, String)> = vec![
(1, "<< /Type /Catalog /Pages 2 0 R >>".into()),
(
2,
"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /Resources 8 0 R >>".into(),
),
(
3,
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 5 0 R >>".into(),
),
(
4,
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 6 0 R \
/Resources 7 0 R >>"
.into(),
),
(7, "null".into()), (
8,
"<< /Font << \
/F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> \
/F2 << /Type /Font /Subtype /Type1 /BaseFont /Courier >> \
>> >>"
.into(),
),
];
for (n, s) in &dicts {
offs.insert(*n, out.len() as u64);
out.extend_from_slice(format!("{n} 0 obj\n{s}\nendobj\n").as_bytes());
}
for (n, content) in [(5u32, &content_a[..]), (6u32, &content_b[..])] {
offs.insert(n, out.len() as u64);
out.extend_from_slice(
format!("{n} 0 obj\n<< /Length {} >>\nstream\n", content.len()).as_bytes(),
);
out.extend_from_slice(content);
out.extend_from_slice(b"\nendstream\nendobj\n");
}
let xref_start = out.len() as u64;
let total = 9u32;
out.extend_from_slice(format!("xref\n0 {total}\n0000000000 65535 f \n").as_bytes());
for i in 1..total {
out.extend_from_slice(format!("{:010} 00000 n \n", offs[&i]).as_bytes());
}
out.extend_from_slice(
format!("trailer\n<< /Size {total} /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n")
.as_bytes(),
);
out
}
#[test]
fn null_chain_resources_falls_through_to_parent_no_corruption() {
for mode in [
RemoveUnreferencedResources::Auto,
RemoveUnreferencedResources::Yes,
] {
let keys = font_keys_after_prune(build_null_chain_resources_pdf(), mode, 8, &[]);
assert!(
keys.contains(&"F1".to_string()) && keys.contains(&"F2".to_string()),
"inherited parent dict must keep both fonts in {mode:?} mode: {keys:?}"
);
}
}
fn build_page_with_resources_carrier_pdf(page_body: &str, obj4_body: &str) -> Vec<u8> {
let mut out: Vec<u8> = b"%PDF-1.4\n".to_vec();
let mut offs: BTreeMap<u32, u64> = BTreeMap::new();
let dicts: [(u32, &str); 4] = [
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>"),
(3, page_body),
(4, obj4_body),
];
for (n, s) in dicts {
offs.insert(n, out.len() as u64);
out.extend_from_slice(format!("{n} 0 obj\n{s}\nendobj\n").as_bytes());
}
let xref_start = out.len() as u64;
let total = 5u32;
out.extend_from_slice(format!("xref\n0 {total}\n0000000000 65535 f \n").as_bytes());
for i in 1..total {
out.extend_from_slice(format!("{:010} 00000 n \n", offs[&i]).as_bytes());
}
out.extend_from_slice(
format!("trailer\n<< /Size {total} /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n")
.as_bytes(),
);
out
}
#[test]
fn resources_location_null_chain_without_parent_is_none() {
let bytes = build_page_with_resources_carrier_pdf(
"<< /Type /Page /MediaBox [0 0 612 792] /Resources 4 0 R >>",
"null",
);
let mut pdf = Pdf::open(Cursor::new(bytes)).expect("PDF should parse");
let loc = resources_location(&mut pdf, ObjectRef::new(3, 0)).expect("ok");
assert_eq!(loc, ResourcesLoc::None);
}
#[test]
fn resources_location_chain_to_non_dict_is_none() {
let bytes = build_page_with_resources_carrier_pdf(
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources 4 0 R >>",
"42",
);
let mut pdf = Pdf::open(Cursor::new(bytes)).expect("PDF should parse");
let loc = resources_location(&mut pdf, ObjectRef::new(3, 0)).expect("ok");
assert_eq!(loc, ResourcesLoc::None);
}
#[test]
fn resources_location_direct_non_dict_is_none() {
let bytes = build_page_with_resources_carrier_pdf(
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources 42 >>",
"null",
);
let mut pdf = Pdf::open(Cursor::new(bytes)).expect("PDF should parse");
let loc = resources_location(&mut pdf, ObjectRef::new(3, 0)).expect("ok");
assert_eq!(loc, ResourcesLoc::None);
}
#[test]
fn resources_location_absent_without_parent_is_none() {
let bytes = build_page_with_resources_carrier_pdf(
"<< /Type /Page /MediaBox [0 0 612 792] >>",
"null",
);
let mut pdf = Pdf::open(Cursor::new(bytes)).expect("PDF should parse");
let loc = resources_location(&mut pdf, ObjectRef::new(3, 0)).expect("ok");
assert_eq!(loc, ResourcesLoc::None);
}
}