Debian Codegraph @

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

raw
1 use lopdf::dictionary;
2 use lopdf::{Document, Object, Stream};
3 use lopdf::content::{Content, Operation};
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 println!("Creating a text-heavy PDF with many objects...");
26
27 let mut doc = Document::with_version("1.5");
28 let pages_id = doc.new_object_id();
29
30 // Create many font objects
31 let mut font_ids = Vec::new();
32 for i in 0..20 {
33 let font_id = doc.add_object(dictionary! {
34 "Type" => "Font",
35 "Subtype" => "Type1",
36 "BaseFont" => format!("Font{}", i),
37 "Encoding" => "WinAnsiEncoding"
38 });
39 font_ids.push(font_id);
40 }
41
42 // Create many metadata objects
43 for i in 0..50 {
44 doc.add_object(dictionary! {
45 "Type" => "Metadata",
46 "Version" => i,
47 "Author" => format!("Author {}", i),
48 "Title" => format!("Document Section {}", i),
49 "Subject" => format!("This is metadata object number {} with some additional text to make it larger", i),
50 "Keywords" => format!("keyword{}, test{}, pdf{}, compression{}", i, i, i, i),
51 "Creator" => "lopdf object streams demo",
52 "Producer" => "lopdf library with object stream support",
53 "CreationDate" => format!("D:2024010{}120000", i % 10)
54 });
55 }
56
57 // Create annotation objects
58 for i in 0..30 {
59 doc.add_object(dictionary! {
60 "Type" => "Annot",
61 "Subtype" => "Text",
62 "Rect" => vec![100.into(), (100 + i * 20).into(), 200.into(), (120 + i * 20).into()],
63 "Contents" => format!("This is annotation number {} with some descriptive text", i),
64 "Open" => false,
65 "Name" => "Comment",
66 "C" => vec![1.0.into(), 0.0.into(), 0.0.into()]
67 });
68 }
69
70 // Create outline objects (bookmarks)
71 for i in 0..25 {
72 doc.add_object(dictionary! {
73 "Title" => format!("Chapter {}: Introduction to Section {}", i, i),
74 "Count" => 0,
75 "Dest" => format!("section_{}", i)
76 });
77 }
78
79 let resources_id = doc.add_object(dictionary! {
80 "Font" => dictionary! {
81 "F1" => font_ids[0],
82 },
83 });
84
85 // Create page content with lots of text
86 let mut operations = vec![
87 Operation::new("BT", vec![]),
88 Operation::new("Tf", vec!["F1".into(), 12.into()]),
89 Operation::new("Td", vec![50.into(), 750.into()]),
90 Operation::new("Tj", vec![Object::string_literal("Text-Heavy PDF Compression Demo")]),
91 Operation::new("ET", vec![]),
92 ];
93
94 // Add many text operations
95 for i in 0..50 {
96 operations.extend(vec![
97 Operation::new("BT", vec![]),
98 Operation::new("Tf", vec!["F1".into(), 10.into()]),
99 Operation::new("Td", vec![50.into(), (700 - i * 10).into()]),
100 Operation::new("Tj", vec![Object::string_literal(format!("Line {}: This is a sample text line to demonstrate compression", i))]),
101 Operation::new("ET", vec![]),
102 ]);
103 }
104
105 let content = Content { operations };
106 let content_id = doc.add_object(Stream::new(dictionary! {}, content.encode()?));
107
108 let page_id = doc.add_object(dictionary! {
109 "Type" => "Page",
110 "Parent" => pages_id,
111 "Contents" => content_id,
112 "Resources" => resources_id,
113 "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
114 });
115
116 doc.objects.insert(pages_id, Object::Dictionary(dictionary! {
117 "Type" => "Pages",
118 "Kids" => vec![page_id.into()],
119 "Count" => 1,
120 }));
121
122 let catalog_id = doc.add_object(dictionary! {
123 "Type" => "Catalog",
124 "Pages" => pages_id,
125 });
126
127 doc.trailer.set("Root", catalog_id);
128
129 // Save and compare
130 doc.save("text_heavy_traditional.pdf")?;
131 let traditional_size = std::fs::metadata("text_heavy_traditional.pdf")?.len();
132
133 let mut modern_file = std::fs::File::create("text_heavy_compressed.pdf")?;
134 doc.save_modern(&mut modern_file)?;
135 drop(modern_file);
136 let modern_size = std::fs::metadata("text_heavy_compressed.pdf")?.len();
137
138 println!("\nCreated PDF with {} objects", doc.objects.len());
139 println!("\nFile sizes:");
140 println!("Traditional format: {} bytes ({:.1} KB)", traditional_size, traditional_size as f64 / 1024.0);
141 println!("With object streams: {} bytes ({:.1} KB)", modern_size, modern_size as f64 / 1024.0);
142
143 let reduction = 100.0 - (modern_size as f64 / traditional_size as f64 * 100.0);
144 println!("\nCompression achieved: {:.1}%", reduction);
145
146 println!("\nFiles created:");
147 println!(" - text_heavy_traditional.pdf");
148 println!(" - text_heavy_compressed.pdf");
149
150 // Analyze the compressed PDF
151 println!("\nAnalyzing compressed PDF:");
152 let compressed_doc = load_document("text_heavy_compressed.pdf")?;
153 let has_objstm = compressed_doc.objects.values().any(|obj| {
154 if let Object::Dictionary(dict) = obj {
155 if let Ok(Object::Name(name)) = dict.get(b"Type") {
156 return name == b"ObjStm";
157 }
158 }
159 false
160 });
161 println!("Uses object streams: {}", has_objstm);
162
163 Ok(())
164 }