Debian Codegraph @

debian/missing-sources/lopdf/examples/compress_existing_pdf.rs

raw
1 use lopdf::{Document, SaveOptions};
2 use std::env;
3 use std::path::Path;
4
5 #[cfg(feature = "async")]
6 use tokio::runtime::Builder;
7
8 #[cfg(not(feature = "async"))]
9 fn load_document(path: &str) -> Result<Document, Box<dyn std::error::Error>> {
10 Ok(Document::load(path)?)
11 }
12
13 #[cfg(feature = "async")]
14 fn load_document(path: &str) -> Result<Document, Box<dyn std::error::Error>> {
15 Ok(Builder::new_current_thread()
16 .enable_all()
17 .build()
18 .unwrap()
19 .block_on(async move {
20 Document::load(path).await
21 })?)
22 }
23
24 fn main() -> Result<(), Box<dyn std::error::Error>> {
25 // Get filename from command line or use default
26 let args: Vec<String> = env::args().collect();
27 let input_file = if args.len() > 1 {
28 &args[1]
29 } else {
30 "assets/example.pdf"
31 };
32
33 // Check if file exists
34 if !Path::new(input_file).exists() {
35 eprintln!("Error: File '{}' not found", input_file);
36 eprintln!("Usage: cargo run --example compress_existing_pdf [path/to/pdf]");
37 return Ok(());
38 }
39
40 println!("Loading PDF: {}", input_file);
41
42 // Load the PDF
43 let mut doc = load_document(input_file)?;
44 println!("PDF version: {}", doc.version);
45 println!("Number of objects: {}", doc.objects.len());
46 println!("Number of pages: {}", doc.get_pages().len());
47
48 // Get original file size
49 let original_size = std::fs::metadata(input_file)?.len();
50 println!("\nOriginal file size: {} bytes ({:.1} KB)", original_size, original_size as f64 / 1024.0);
51
52 // Save without object streams (traditional format)
53 let output_traditional = format!("{}_traditional.pdf", input_file.trim_end_matches(".pdf"));
54 doc.save(&output_traditional)?;
55 let traditional_size = std::fs::metadata(&output_traditional)?.len();
56 println!("\nTraditional save: {} bytes ({:.1} KB)", traditional_size, traditional_size as f64 / 1024.0);
57
58 // Save with object streams (modern format)
59 let output_modern = format!("{}_compressed.pdf", input_file.trim_end_matches(".pdf"));
60 let mut modern_file = std::fs::File::create(&output_modern)?;
61 doc.save_modern(&mut modern_file)?;
62 drop(modern_file); // Ensure file is closed before reading metadata
63 let modern_size = std::fs::metadata(&output_modern)?.len();
64 println!("Object streams save: {} bytes ({:.1} KB)", modern_size, modern_size as f64 / 1024.0);
65
66 // Save with custom compression settings
67 let output_custom = format!("{}_max_compressed.pdf", input_file.trim_end_matches(".pdf"));
68 let mut custom_file = std::fs::File::create(&output_custom)?;
69 let options = SaveOptions::builder()
70 .use_object_streams(true)
71 .use_xref_streams(true)
72 .max_objects_per_stream(200) // More objects per stream
73 .compression_level(9) // Maximum compression
74 .build();
75 doc.save_with_options(&mut custom_file, options)?;
76 drop(custom_file);
77 let custom_size = std::fs::metadata(&output_custom)?.len();
78 println!("Max compression save: {} bytes ({:.1} KB)", custom_size, custom_size as f64 / 1024.0);
79
80 // Calculate savings
81 println!("\n--- Compression Results ---");
82 let modern_reduction = 100.0 - (modern_size as f64 / original_size as f64 * 100.0);
83 let custom_reduction = 100.0 - (custom_size as f64 / original_size as f64 * 100.0);
84 println!("Object streams reduction: {:.1}%", modern_reduction);
85 println!("Max compression reduction: {:.1}%", custom_reduction);
86
87 // Compare with traditional save
88 let modern_vs_trad = 100.0 - (modern_size as f64 / traditional_size as f64 * 100.0);
89 println!("\nVs traditional re-save: {:.1}% smaller", modern_vs_trad);
90
91 println!("\nOutput files created:");
92 println!(" - {}", output_traditional);
93 println!(" - {}", output_modern);
94 println!(" - {}", output_custom);
95
96 Ok(())
97 }