| 1 |
use lopdf::{Document, Object, ObjectId}; |
| 2 |
use std::collections::{HashMap, HashSet}; |
| 3 |
|
| 4 |
#[cfg(feature = "async")] |
| 5 |
use tokio::runtime::Builder; |
| 6 |
|
| 7 |
#[cfg(not(feature = "async"))] |
| 8 |
fn load_document(path: &str) -> Result<Document, Box<dyn std::error::Error>> { |
| 9 |
Ok(Document::load(path)?) |
| 10 |
} |
| 11 |
|
| 12 |
#[cfg(feature = "async")] |
| 13 |
fn load_document(path: &str) -> Result<Document, Box<dyn std::error::Error>> { |
| 14 |
Ok(Builder::new_current_thread() |
| 15 |
.enable_all() |
| 16 |
.build() |
| 17 |
.unwrap() |
| 18 |
.block_on(async move { |
| 19 |
Document::load(path).await |
| 20 |
})?) |
| 21 |
} |
| 22 |
|
| 23 |
fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 24 |
let pdf_path = "/Users/nicolasdao/Downloads/poor.pdf"; |
| 25 |
|
| 26 |
println!("Testing improved compression algorithm...\n"); |
| 27 |
|
| 28 |
let doc = load_document(pdf_path)?; |
| 29 |
|
| 30 |
// Build complete reference graph |
| 31 |
let (non_compressible, reason_map) = find_all_non_compressible_objects(&doc); |
| 32 |
|
| 33 |
println!("Analysis complete:"); |
| 34 |
println!(" Total objects: {}", doc.objects.len()); |
| 35 |
println!(" Non-compressible: {}", non_compressible.len()); |
| 36 |
println!(" Compressible: {}", doc.objects.len() - non_compressible.len()); |
| 37 |
|
| 38 |
// Show some examples |
| 39 |
println!("\nSample non-compressible objects:"); |
| 40 |
for (id, reason) in reason_map.iter().take(20) { |
| 41 |
println!(" {} {} R: {}", id.0, id.1, reason); |
| 42 |
} |
| 43 |
|
| 44 |
// Count by reason |
| 45 |
let mut reason_counts: HashMap<&str, usize> = HashMap::new(); |
| 46 |
for reason in reason_map.values() { |
| 47 |
*reason_counts.entry(reason.as_str()).or_insert(0) += 1; |
| 48 |
} |
| 49 |
|
| 50 |
println!("\nReasons for non-compressibility:"); |
| 51 |
for (reason, count) in reason_counts { |
| 52 |
println!(" {}: {}", reason, count); |
| 53 |
} |
| 54 |
|
| 55 |
// Simulate compression |
| 56 |
let mut would_compress = Vec::new(); |
| 57 |
for (&id, _obj) in &doc.objects { |
| 58 |
if !non_compressible.contains(&id) { |
| 59 |
would_compress.push(id); |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
println!("\nWould compress {} objects", would_compress.len()); |
| 64 |
|
| 65 |
// Check for orphaned references |
| 66 |
let orphans = check_for_orphans(&doc, &non_compressible, &would_compress); |
| 67 |
|
| 68 |
if orphans.is_empty() { |
| 69 |
println!("\n✓ No orphaned references would be created!"); |
| 70 |
} else { |
| 71 |
println!("\n✗ WARNING: {} orphaned references would be created:", orphans.len()); |
| 72 |
for (compressed_id, referencer_id) in orphans.iter().take(10) { |
| 73 |
println!(" {} {} R would be compressed but is referenced by {} {} R", |
| 74 |
compressed_id.0, compressed_id.1, referencer_id.0, referencer_id.1); |
| 75 |
} |
| 76 |
} |
| 77 |
|
| 78 |
Ok(()) |
| 79 |
} |
| 80 |
|
| 81 |
fn find_all_non_compressible_objects(doc: &Document) -> (HashSet<ObjectId>, HashMap<ObjectId, String>) { |
| 82 |
let mut non_compressible = HashSet::new(); |
| 83 |
let mut reason_map = HashMap::new(); |
| 84 |
|
| 85 |
// Phase 1: Mark inherently non-compressible objects |
| 86 |
for (&id, obj) in &doc.objects { |
| 87 |
let mut reason = None; |
| 88 |
|
| 89 |
// Streams cannot be compressed |
| 90 |
if matches!(obj, Object::Stream(_)) { |
| 91 |
reason = Some("Is a stream object"); |
| 92 |
} |
| 93 |
|
| 94 |
// Check object type |
| 95 |
if let Object::Dictionary(dict) = obj { |
| 96 |
if let Ok(type_obj) = dict.get(b"Type") { |
| 97 |
if let Ok(type_name) = type_obj.as_name() { |
| 98 |
match type_name { |
| 99 |
b"Page" => reason = Some("Is a Page object"), |
| 100 |
b"Pages" => reason = Some("Is a Pages object"), |
| 101 |
b"Catalog" => reason = Some("Is a Catalog object"), |
| 102 |
b"XRef" => reason = Some("Is a cross-reference stream"), |
| 103 |
b"ObjStm" => reason = Some("Is an object stream"), |
| 104 |
_ => {} |
| 105 |
} |
| 106 |
} |
| 107 |
} |
| 108 |
} |
| 109 |
|
| 110 |
// Check if referenced in trailer |
| 111 |
for (_key, value) in doc.trailer.iter() { |
| 112 |
if value == &Object::Reference(id) { |
| 113 |
reason = Some("Referenced in trailer"); |
| 114 |
break; |
| 115 |
} |
| 116 |
} |
| 117 |
|
| 118 |
if let Some(r) = reason { |
| 119 |
non_compressible.insert(id); |
| 120 |
reason_map.insert(id, r.to_string()); |
| 121 |
} |
| 122 |
} |
| 123 |
|
| 124 |
// Phase 2: Iteratively mark objects referenced by non-compressible objects |
| 125 |
let mut changed = true; |
| 126 |
let mut iteration = 0; |
| 127 |
|
| 128 |
while changed { |
| 129 |
changed = false; |
| 130 |
iteration += 1; |
| 131 |
let mut newly_non_compressible = Vec::new(); |
| 132 |
|
| 133 |
for &nc_id in &non_compressible { |
| 134 |
if let Ok(nc_obj) = doc.get_object(nc_id) { |
| 135 |
let refs = collect_all_references(nc_obj); |
| 136 |
|
| 137 |
for ref_id in refs { |
| 138 |
if !non_compressible.contains(&ref_id) && doc.objects.contains_key(&ref_id) { |
| 139 |
newly_non_compressible.push((ref_id, format!("Referenced by non-compressible {} {} R", nc_id.0, nc_id.1))); |
| 140 |
changed = true; |
| 141 |
} |
| 142 |
} |
| 143 |
} |
| 144 |
} |
| 145 |
|
| 146 |
for (id, reason) in newly_non_compressible { |
| 147 |
non_compressible.insert(id); |
| 148 |
reason_map.insert(id, reason); |
| 149 |
} |
| 150 |
} |
| 151 |
|
| 152 |
println!("Transitive closure computed in {} iterations", iteration); |
| 153 |
|
| 154 |
(non_compressible, reason_map) |
| 155 |
} |
| 156 |
|
| 157 |
fn collect_all_references(obj: &Object) -> HashSet<ObjectId> { |
| 158 |
let mut refs = HashSet::new(); |
| 159 |
|
| 160 |
match obj { |
| 161 |
Object::Reference(id) => { |
| 162 |
refs.insert(*id); |
| 163 |
} |
| 164 |
Object::Array(array) => { |
| 165 |
for item in array { |
| 166 |
refs.extend(collect_all_references(item)); |
| 167 |
} |
| 168 |
} |
| 169 |
Object::Dictionary(dict) => { |
| 170 |
for (_key, value) in dict.iter() { |
| 171 |
refs.extend(collect_all_references(value)); |
| 172 |
} |
| 173 |
} |
| 174 |
Object::Stream(stream) => { |
| 175 |
for (_key, value) in stream.dict.iter() { |
| 176 |
refs.extend(collect_all_references(value)); |
| 177 |
} |
| 178 |
} |
| 179 |
_ => {} |
| 180 |
} |
| 181 |
|
| 182 |
refs |
| 183 |
} |
| 184 |
|
| 185 |
fn check_for_orphans(doc: &Document, non_compressible: &HashSet<ObjectId>, would_compress: &[ObjectId]) -> Vec<(ObjectId, ObjectId)> { |
| 186 |
let mut orphans = Vec::new(); |
| 187 |
|
| 188 |
for &nc_id in non_compressible { |
| 189 |
if let Ok(nc_obj) = doc.get_object(nc_id) { |
| 190 |
let refs = collect_all_references(nc_obj); |
| 191 |
|
| 192 |
for ref_id in refs { |
| 193 |
if would_compress.contains(&ref_id) { |
| 194 |
orphans.push((ref_id, nc_id)); |
| 195 |
} |
| 196 |
} |
| 197 |
} |
| 198 |
} |
| 199 |
|
| 200 |
orphans |
| 201 |
} |