| 1 |
use lopdf::{Document, Object, SaveOptions, ObjectStream}; |
| 2 |
use std::collections::HashMap; |
| 3 |
use std::env; |
| 4 |
use std::fs::File; |
| 5 |
use std::io::Write; |
| 6 |
|
| 7 |
#[cfg(feature = "async")] |
| 8 |
use tokio::runtime::Builder; |
| 9 |
|
| 10 |
#[cfg(not(feature = "async"))] |
| 11 |
fn load_document(path: &str) -> Result<Document, Box<dyn std::error::Error>> { |
| 12 |
Ok(Document::load(path)?) |
| 13 |
} |
| 14 |
|
| 15 |
#[cfg(feature = "async")] |
| 16 |
fn load_document(path: &str) -> Result<Document, Box<dyn std::error::Error>> { |
| 17 |
Ok(Builder::new_current_thread() |
| 18 |
.enable_all() |
| 19 |
.build() |
| 20 |
.unwrap() |
| 21 |
.block_on(async move { |
| 22 |
Document::load(path).await |
| 23 |
})?) |
| 24 |
} |
| 25 |
|
| 26 |
fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 27 |
let args: Vec<String> = env::args().collect(); |
| 28 |
let input_file = if args.len() > 1 { |
| 29 |
&args[1] |
| 30 |
} else { |
| 31 |
eprintln!("Usage: cargo run --example debug_compression_full <pdf_file>"); |
| 32 |
std::process::exit(1); |
| 33 |
}; |
| 34 |
|
| 35 |
println!("=== COMPREHENSIVE PDF COMPRESSION DEBUG ===\n"); |
| 36 |
|
| 37 |
// Load original PDF |
| 38 |
println!("1. Loading original PDF: {}", input_file); |
| 39 |
let mut doc = load_document(input_file)?; |
| 40 |
let _original_objects = doc.objects.len(); |
| 41 |
|
| 42 |
// Analyze original structure |
| 43 |
println!("\n2. Analyzing original PDF structure:"); |
| 44 |
let original_analysis = analyze_document(&doc); |
| 45 |
print_analysis(&original_analysis); |
| 46 |
|
| 47 |
// Create debug log file |
| 48 |
let debug_log_path = format!("{}_debug_log.txt", input_file.trim_end_matches(".pdf")); |
| 49 |
let mut debug_log = File::create(&debug_log_path)?; |
| 50 |
writeln!(debug_log, "PDF Compression Debug Log for: {}", input_file)?; |
| 51 |
writeln!(debug_log, "{}", "=".repeat(80))?; |
| 52 |
|
| 53 |
// Save with object streams - with detailed logging |
| 54 |
println!("\n3. Saving with object streams (with detailed logging)..."); |
| 55 |
let options = SaveOptions { |
| 56 |
use_object_streams: true, |
| 57 |
use_xref_streams: true, |
| 58 |
..Default::default() |
| 59 |
}; |
| 60 |
|
| 61 |
// Simulate the compression process to log what would happen |
| 62 |
let mut compressible_objects = Vec::new(); |
| 63 |
let mut non_compressible_objects = Vec::new(); |
| 64 |
|
| 65 |
for (&id, obj) in &doc.objects { |
| 66 |
let can_compress = ObjectStream::can_be_compressed(id, obj, &doc); |
| 67 |
let obj_info = format!("{} {} R: {} - {}", |
| 68 |
id.0, id.1, |
| 69 |
obj.type_name().map(|n| String::from_utf8_lossy(n).to_string()).unwrap_or("Unknown".to_string()), |
| 70 |
describe_object(obj) |
| 71 |
); |
| 72 |
|
| 73 |
if can_compress { |
| 74 |
compressible_objects.push(obj_info.clone()); |
| 75 |
writeln!(debug_log, "✓ COMPRESSIBLE: {}", obj_info)?; |
| 76 |
} else { |
| 77 |
non_compressible_objects.push(obj_info.clone()); |
| 78 |
writeln!(debug_log, "✗ NOT COMPRESSIBLE: {}", obj_info)?; |
| 79 |
|
| 80 |
// Log why it's not compressible |
| 81 |
if matches!(obj, Object::Stream(_)) { |
| 82 |
writeln!(debug_log, " Reason: Is a stream object")?; |
| 83 |
} else if let Object::Dictionary(dict) = obj { |
| 84 |
if let Ok(type_obj) = dict.get(b"Type") { |
| 85 |
if let Ok(type_name) = type_obj.as_name() { |
| 86 |
if type_name == b"Page" || type_name == b"Pages" { |
| 87 |
writeln!(debug_log, " Reason: Is a Page/Pages object")?; |
| 88 |
} |
| 89 |
} |
| 90 |
} |
| 91 |
} |
| 92 |
|
| 93 |
// Check if in trailer |
| 94 |
for (key, value) in doc.trailer.iter() { |
| 95 |
if value == &Object::Reference(id) { |
| 96 |
writeln!(debug_log, " Reason: Referenced in trailer[{}]", String::from_utf8_lossy(key))?; |
| 97 |
} |
| 98 |
} |
| 99 |
} |
| 100 |
} |
| 101 |
|
| 102 |
writeln!(debug_log, "\nSummary:")?; |
| 103 |
writeln!(debug_log, " Compressible objects: {}", compressible_objects.len())?; |
| 104 |
writeln!(debug_log, " Non-compressible objects: {}", non_compressible_objects.len())?; |
| 105 |
|
| 106 |
// Actually save |
| 107 |
let output_file = format!("{}_compressed.pdf", input_file.trim_end_matches(".pdf")); |
| 108 |
let mut buffer = Vec::new(); |
| 109 |
doc.save_with_options(&mut buffer, options)?; |
| 110 |
std::fs::write(&output_file, &buffer)?; |
| 111 |
|
| 112 |
println!("Saved compressed PDF: {} ({} bytes)", output_file, buffer.len()); |
| 113 |
|
| 114 |
// Load compressed PDF back |
| 115 |
println!("\n4. Loading compressed PDF back for analysis..."); |
| 116 |
match Document::load_mem(&buffer) { |
| 117 |
Ok(compressed_doc) => { |
| 118 |
let compressed_analysis = analyze_document(&compressed_doc); |
| 119 |
|
| 120 |
println!("\n5. Compressed PDF structure:"); |
| 121 |
print_analysis(&compressed_analysis); |
| 122 |
|
| 123 |
// Compare structures |
| 124 |
println!("\n6. Comparing structures:"); |
| 125 |
compare_analyses(&original_analysis, &compressed_analysis, &mut debug_log)?; |
| 126 |
|
| 127 |
// Verify critical objects |
| 128 |
println!("\n7. Verifying critical objects in compressed PDF:"); |
| 129 |
verify_critical_objects(&compressed_doc, &mut debug_log)?; |
| 130 |
|
| 131 |
// Check for orphaned references |
| 132 |
println!("\n8. Checking for orphaned references:"); |
| 133 |
check_orphaned_references(&compressed_doc, &mut debug_log)?; |
| 134 |
} |
| 135 |
Err(e) => { |
| 136 |
eprintln!("ERROR: Failed to load compressed PDF: {}", e); |
| 137 |
writeln!(debug_log, "\nERROR: Failed to load compressed PDF: {}", e)?; |
| 138 |
} |
| 139 |
} |
| 140 |
|
| 141 |
println!("\n9. Debug log written to: {}", debug_log_path); |
| 142 |
|
| 143 |
// Try to use external PDF validator if available |
| 144 |
println!("\n10. Attempting external validation..."); |
| 145 |
validate_with_external_tools(&output_file); |
| 146 |
|
| 147 |
Ok(()) |
| 148 |
} |
| 149 |
|
| 150 |
#[derive(Debug)] |
| 151 |
struct DocumentAnalysis { |
| 152 |
total_objects: usize, |
| 153 |
pages: usize, |
| 154 |
streams: usize, |
| 155 |
dictionaries: usize, |
| 156 |
arrays: usize, |
| 157 |
object_streams: usize, |
| 158 |
compressed_objects: usize, |
| 159 |
page_objects: Vec<(u32, u16)>, |
| 160 |
content_streams: Vec<(u32, u16)>, |
| 161 |
fonts: Vec<(u32, u16)>, |
| 162 |
} |
| 163 |
|
| 164 |
fn analyze_document(doc: &Document) -> DocumentAnalysis { |
| 165 |
let mut analysis = DocumentAnalysis { |
| 166 |
total_objects: doc.objects.len(), |
| 167 |
pages: doc.get_pages().len(), |
| 168 |
streams: 0, |
| 169 |
dictionaries: 0, |
| 170 |
arrays: 0, |
| 171 |
object_streams: 0, |
| 172 |
compressed_objects: 0, |
| 173 |
page_objects: Vec::new(), |
| 174 |
content_streams: Vec::new(), |
| 175 |
fonts: Vec::new(), |
| 176 |
}; |
| 177 |
|
| 178 |
// Count compressed objects |
| 179 |
for (_id, xref_entry) in &doc.reference_table.entries { |
| 180 |
if let lopdf::xref::XrefEntry::Compressed { .. } = xref_entry { |
| 181 |
analysis.compressed_objects += 1; |
| 182 |
} |
| 183 |
} |
| 184 |
|
| 185 |
// Analyze objects |
| 186 |
for (&id, obj) in &doc.objects { |
| 187 |
match obj { |
| 188 |
Object::Stream(stream) => { |
| 189 |
analysis.streams += 1; |
| 190 |
if let Ok(type_obj) = stream.dict.get(b"Type") { |
| 191 |
if let Ok(type_name) = type_obj.as_name() { |
| 192 |
if type_name == b"ObjStm" { |
| 193 |
analysis.object_streams += 1; |
| 194 |
} |
| 195 |
} |
| 196 |
} |
| 197 |
} |
| 198 |
Object::Dictionary(dict) => { |
| 199 |
analysis.dictionaries += 1; |
| 200 |
if let Ok(type_obj) = dict.get(b"Type") { |
| 201 |
if let Ok(type_name) = type_obj.as_name() { |
| 202 |
match type_name { |
| 203 |
b"Page" => analysis.page_objects.push(id), |
| 204 |
b"Font" => analysis.fonts.push(id), |
| 205 |
_ => {} |
| 206 |
} |
| 207 |
} |
| 208 |
} |
| 209 |
} |
| 210 |
Object::Array(_) => analysis.arrays += 1, |
| 211 |
_ => {} |
| 212 |
} |
| 213 |
} |
| 214 |
|
| 215 |
// Find content streams |
| 216 |
for &page_id in &analysis.page_objects { |
| 217 |
if let Ok(page_obj) = doc.get_object(page_id) { |
| 218 |
if let Object::Dictionary(page_dict) = page_obj { |
| 219 |
match page_dict.get(b"Contents") { |
| 220 |
Ok(Object::Reference(content_id)) => { |
| 221 |
analysis.content_streams.push(*content_id); |
| 222 |
} |
| 223 |
Ok(Object::Array(contents)) => { |
| 224 |
for content_ref in contents { |
| 225 |
if let Object::Reference(content_id) = content_ref { |
| 226 |
analysis.content_streams.push(*content_id); |
| 227 |
} |
| 228 |
} |
| 229 |
} |
| 230 |
_ => {} |
| 231 |
} |
| 232 |
} |
| 233 |
} |
| 234 |
} |
| 235 |
|
| 236 |
analysis |
| 237 |
} |
| 238 |
|
| 239 |
fn print_analysis(analysis: &DocumentAnalysis) { |
| 240 |
println!(" Total objects: {}", analysis.total_objects); |
| 241 |
println!(" Pages: {}", analysis.pages); |
| 242 |
println!(" Streams: {}", analysis.streams); |
| 243 |
println!(" Dictionaries: {}", analysis.dictionaries); |
| 244 |
println!(" Arrays: {}", analysis.arrays); |
| 245 |
println!(" Object streams: {}", analysis.object_streams); |
| 246 |
println!(" Compressed objects: {}", analysis.compressed_objects); |
| 247 |
println!(" Page objects: {:?}", analysis.page_objects); |
| 248 |
println!(" Content streams: {} found", analysis.content_streams.len()); |
| 249 |
println!(" Fonts: {} found", analysis.fonts.len()); |
| 250 |
} |
| 251 |
|
| 252 |
fn describe_object(obj: &Object) -> String { |
| 253 |
match obj { |
| 254 |
Object::Null => "Null".to_string(), |
| 255 |
Object::Boolean(b) => format!("Boolean({})", b), |
| 256 |
Object::Integer(i) => format!("Integer({})", i), |
| 257 |
Object::Real(r) => format!("Real({})", r), |
| 258 |
Object::Name(n) => format!("Name({})", String::from_utf8_lossy(n)), |
| 259 |
Object::String(_, _) => "String".to_string(), |
| 260 |
Object::Array(a) => format!("Array[{}]", a.len()), |
| 261 |
Object::Dictionary(d) => { |
| 262 |
let keys: Vec<_> = d.iter().take(3).map(|(k, _)| String::from_utf8_lossy(k)).collect(); |
| 263 |
format!("Dict{{{}...}}", keys.join(", ")) |
| 264 |
} |
| 265 |
Object::Stream(s) => { |
| 266 |
let keys: Vec<_> = s.dict.iter().take(3).map(|(k, _)| String::from_utf8_lossy(k)).collect(); |
| 267 |
format!("Stream{{dict: {{{}...}}, len: {}}}", keys.join(", "), s.content.len()) |
| 268 |
} |
| 269 |
Object::Reference(id) => format!("Ref({} {} R)", id.0, id.1), |
| 270 |
} |
| 271 |
} |
| 272 |
|
| 273 |
fn compare_analyses(original: &DocumentAnalysis, compressed: &DocumentAnalysis, log: &mut File) -> std::io::Result<()> { |
| 274 |
writeln!(log, "\n=== STRUCTURE COMPARISON ===")?; |
| 275 |
|
| 276 |
if original.pages != compressed.pages { |
| 277 |
writeln!(log, "WARNING: Page count changed! {} -> {}", original.pages, compressed.pages)?; |
| 278 |
} |
| 279 |
|
| 280 |
if original.page_objects.len() != compressed.page_objects.len() { |
| 281 |
writeln!(log, "WARNING: Page object count changed! {} -> {}", |
| 282 |
original.page_objects.len(), compressed.page_objects.len())?; |
| 283 |
} |
| 284 |
|
| 285 |
if original.content_streams.len() != compressed.content_streams.len() { |
| 286 |
writeln!(log, "WARNING: Content stream count changed! {} -> {}", |
| 287 |
original.content_streams.len(), compressed.content_streams.len())?; |
| 288 |
} |
| 289 |
|
| 290 |
writeln!(log, "Object count: {} -> {} (compressed {} objects)", |
| 291 |
original.total_objects, compressed.total_objects, compressed.compressed_objects)?; |
| 292 |
|
| 293 |
writeln!(log, "Object streams created: {}", compressed.object_streams)?; |
| 294 |
|
| 295 |
Ok(()) |
| 296 |
} |
| 297 |
|
| 298 |
fn verify_critical_objects(doc: &Document, log: &mut File) -> std::io::Result<()> { |
| 299 |
writeln!(log, "\n=== CRITICAL OBJECT VERIFICATION ===")?; |
| 300 |
|
| 301 |
// Check all page objects |
| 302 |
let pages = doc.get_pages(); |
| 303 |
for (num, &page_id) in pages.iter() { |
| 304 |
match doc.get_object(page_id) { |
| 305 |
Ok(obj) => { |
| 306 |
writeln!(log, "Page {} ({} {} R): OK - {}", num, page_id.0, page_id.1, describe_object(obj))?; |
| 307 |
|
| 308 |
// Check if it's compressed |
| 309 |
if let Some(xref) = doc.reference_table.get(page_id.0) { |
| 310 |
if let lopdf::xref::XrefEntry::Compressed { container, index } = xref { |
| 311 |
writeln!(log, " ERROR: Page is compressed in stream {} at index {}!", container, index)?; |
| 312 |
} |
| 313 |
} |
| 314 |
|
| 315 |
// Check page contents |
| 316 |
if let Object::Dictionary(page_dict) = obj { |
| 317 |
match page_dict.get(b"Contents") { |
| 318 |
Ok(Object::Reference(content_id)) => { |
| 319 |
match doc.get_object(*content_id) { |
| 320 |
Ok(_) => writeln!(log, " Contents {} {} R: OK", content_id.0, content_id.1)?, |
| 321 |
Err(e) => writeln!(log, " Contents {} {} R: ERROR - {}", content_id.0, content_id.1, e)?, |
| 322 |
} |
| 323 |
} |
| 324 |
Ok(Object::Array(contents)) => { |
| 325 |
writeln!(log, " Contents array with {} elements", contents.len())?; |
| 326 |
for (i, content_ref) in contents.iter().enumerate() { |
| 327 |
if let Object::Reference(content_id) = content_ref { |
| 328 |
match doc.get_object(*content_id) { |
| 329 |
Ok(_) => writeln!(log, " [{}] {} {} R: OK", i, content_id.0, content_id.1)?, |
| 330 |
Err(e) => writeln!(log, " [{}] {} {} R: ERROR - {}", i, content_id.0, content_id.1, e)?, |
| 331 |
} |
| 332 |
} |
| 333 |
} |
| 334 |
} |
| 335 |
_ => writeln!(log, " Contents: Unexpected type")?, |
| 336 |
} |
| 337 |
} |
| 338 |
} |
| 339 |
Err(e) => { |
| 340 |
writeln!(log, "Page {} ({} {} R): ERROR - {}", num, page_id.0, page_id.1, e)?; |
| 341 |
} |
| 342 |
} |
| 343 |
} |
| 344 |
|
| 345 |
Ok(()) |
| 346 |
} |
| 347 |
|
| 348 |
fn check_orphaned_references(doc: &Document, log: &mut File) -> std::io::Result<()> { |
| 349 |
writeln!(log, "\n=== ORPHANED REFERENCE CHECK ===")?; |
| 350 |
|
| 351 |
let mut all_references = HashMap::new(); |
| 352 |
|
| 353 |
// Collect all references |
| 354 |
for (id, obj) in &doc.objects { |
| 355 |
collect_references(obj, &mut all_references, *id); |
| 356 |
} |
| 357 |
|
| 358 |
// Check trailer references |
| 359 |
for (_key, value) in doc.trailer.iter() { |
| 360 |
if let Object::Reference(ref_id) = value { |
| 361 |
all_references.insert(*ref_id, ("trailer".to_string(), (0, 0))); |
| 362 |
} |
| 363 |
} |
| 364 |
|
| 365 |
// Check if all referenced objects exist |
| 366 |
let mut orphaned_count = 0; |
| 367 |
for (ref_id, (location, from_id)) in &all_references { |
| 368 |
match doc.get_object(*ref_id) { |
| 369 |
Ok(_) => { |
| 370 |
// Check if it's in a compressed stream |
| 371 |
if let Some(xref) = doc.reference_table.get(ref_id.0) { |
| 372 |
if let lopdf::xref::XrefEntry::Compressed { container, .. } = xref { |
| 373 |
// Make sure the container exists |
| 374 |
if doc.get_object((*container, 0)).is_err() { |
| 375 |
writeln!(log, "ERROR: Reference {} {} R from {} ({} {} R) points to compressed object in non-existent stream {}!", |
| 376 |
ref_id.0, ref_id.1, location, from_id.0, from_id.1, container)?; |
| 377 |
orphaned_count += 1; |
| 378 |
} |
| 379 |
} |
| 380 |
} |
| 381 |
} |
| 382 |
Err(_) => { |
| 383 |
writeln!(log, "ERROR: Orphaned reference {} {} R from {} ({} {} R)", |
| 384 |
ref_id.0, ref_id.1, location, from_id.0, from_id.1)?; |
| 385 |
orphaned_count += 1; |
| 386 |
} |
| 387 |
} |
| 388 |
} |
| 389 |
|
| 390 |
writeln!(log, "\nTotal references checked: {}", all_references.len())?; |
| 391 |
writeln!(log, "Orphaned references: {}", orphaned_count)?; |
| 392 |
|
| 393 |
Ok(()) |
| 394 |
} |
| 395 |
|
| 396 |
fn collect_references(obj: &Object, refs: &mut HashMap<(u32, u16), (String, (u32, u16))>, from_id: (u32, u16)) { |
| 397 |
match obj { |
| 398 |
Object::Reference(ref_id) => { |
| 399 |
refs.insert(*ref_id, ("direct".to_string(), from_id)); |
| 400 |
} |
| 401 |
Object::Array(array) => { |
| 402 |
for (i, item) in array.iter().enumerate() { |
| 403 |
if let Object::Reference(ref_id) = item { |
| 404 |
refs.insert(*ref_id, (format!("array[{}]", i), from_id)); |
| 405 |
} |
| 406 |
collect_references(item, refs, from_id); |
| 407 |
} |
| 408 |
} |
| 409 |
Object::Dictionary(dict) => { |
| 410 |
for (key, value) in dict.iter() { |
| 411 |
if let Object::Reference(ref_id) = value { |
| 412 |
refs.insert(*ref_id, (format!("dict[{}]", String::from_utf8_lossy(key)), from_id)); |
| 413 |
} |
| 414 |
collect_references(value, refs, from_id); |
| 415 |
} |
| 416 |
} |
| 417 |
Object::Stream(stream) => { |
| 418 |
for (key, value) in stream.dict.iter() { |
| 419 |
if let Object::Reference(ref_id) = value { |
| 420 |
refs.insert(*ref_id, (format!("stream.dict[{}]", String::from_utf8_lossy(key)), from_id)); |
| 421 |
} |
| 422 |
collect_references(value, refs, from_id); |
| 423 |
} |
| 424 |
} |
| 425 |
_ => {} |
| 426 |
} |
| 427 |
} |
| 428 |
|
| 429 |
fn validate_with_external_tools(pdf_path: &str) { |
| 430 |
// Try to use pdfinfo if available |
| 431 |
println!("Trying pdfinfo..."); |
| 432 |
match std::process::Command::new("pdfinfo") |
| 433 |
.arg(pdf_path) |
| 434 |
.output() |
| 435 |
{ |
| 436 |
Ok(output) => { |
| 437 |
if output.status.success() { |
| 438 |
println!("✓ pdfinfo validation passed"); |
| 439 |
} else { |
| 440 |
println!("✗ pdfinfo validation failed:"); |
| 441 |
println!("{}", String::from_utf8_lossy(&output.stderr)); |
| 442 |
} |
| 443 |
} |
| 444 |
Err(_) => { |
| 445 |
println!(" pdfinfo not available"); |
| 446 |
} |
| 447 |
} |
| 448 |
|
| 449 |
// Try to use qpdf if available |
| 450 |
println!("\nTrying qpdf --check..."); |
| 451 |
match std::process::Command::new("qpdf") |
| 452 |
.args(&["--check", pdf_path]) |
| 453 |
.output() |
| 454 |
{ |
| 455 |
Ok(output) => { |
| 456 |
if output.status.success() { |
| 457 |
println!("✓ qpdf validation passed"); |
| 458 |
} else { |
| 459 |
println!("✗ qpdf validation failed:"); |
| 460 |
println!("{}", String::from_utf8_lossy(&output.stderr)); |
| 461 |
} |
| 462 |
} |
| 463 |
Err(_) => { |
| 464 |
println!(" qpdf not available"); |
| 465 |
} |
| 466 |
} |
| 467 |
|
| 468 |
// Try to use mutool if available |
| 469 |
println!("\nTrying mutool info..."); |
| 470 |
match std::process::Command::new("mutool") |
| 471 |
.args(&["info", pdf_path]) |
| 472 |
.output() |
| 473 |
{ |
| 474 |
Ok(output) => { |
| 475 |
if output.status.success() { |
| 476 |
println!("✓ mutool validation passed"); |
| 477 |
} else { |
| 478 |
println!("✗ mutool validation failed:"); |
| 479 |
println!("{}", String::from_utf8_lossy(&output.stderr)); |
| 480 |
} |
| 481 |
} |
| 482 |
Err(_) => { |
| 483 |
println!(" mutool not available"); |
| 484 |
} |
| 485 |
} |
| 486 |
} |