oxidize-pdf 2.5.0

A pure Rust PDF generation and manipulation library with zero external dependencies
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//! PDF Trailer Parser
//!
//! Parses PDF trailer according to ISO 32000-1 Section 7.5.5

use super::objects::{PdfDictionary, PdfObject};
use super::{ParseError, ParseResult};

/// PDF Trailer information
#[derive(Debug, Clone)]
pub struct PdfTrailer {
    /// The trailer dictionary
    pub dict: PdfDictionary,
    /// Byte offset of previous xref section (if any)
    pub prev: Option<u64>,
    /// Byte offset of this xref section
    pub xref_offset: u64,
}

impl PdfTrailer {
    /// Parse trailer from a dictionary
    pub fn from_dict(dict: PdfDictionary, xref_offset: u64) -> ParseResult<Self> {
        // Extract previous xref offset if present
        let prev = dict
            .get("Prev")
            .and_then(|obj| obj.as_integer())
            .map(|i| i as u64);

        Ok(PdfTrailer {
            dict,
            prev,
            xref_offset,
        })
    }

    /// Get the size (number of entries in xref table)
    pub fn size(&self) -> ParseResult<u32> {
        self.dict
            .get("Size")
            .and_then(|obj| obj.as_integer())
            .map(|i| i as u32)
            .ok_or_else(|| ParseError::MissingKey("Size".to_string()))
    }

    /// Get the root object reference (document catalog)
    pub fn root(&self) -> ParseResult<(u32, u16)> {
        self.dict
            .get("Root")
            .and_then(|obj| obj.as_reference())
            .ok_or_else(|| ParseError::MissingKey("Root".to_string()))
    }

    /// Try to find root by scanning for Catalog object
    pub fn find_root_fallback(&self) -> Option<(u32, u16)> {
        // This is a placeholder - actual implementation would scan objects
        // For now, try common object numbers for catalog
        if let Some(obj_num) = [1, 2, 3, 4, 5].into_iter().next() {
            // Would need to check if object exists and is a Catalog
            // For now, return first attempt as a guess
            return Some((obj_num, 0));
        }
        None
    }

    /// Get the info object reference (document information dictionary)
    pub fn info(&self) -> Option<(u32, u16)> {
        self.dict.get("Info").and_then(|obj| obj.as_reference())
    }

    /// Get the ID array (file identifiers)
    pub fn id(&self) -> Option<&PdfObject> {
        self.dict.get("ID")
    }

    /// Check if this PDF is encrypted
    pub fn is_encrypted(&self) -> bool {
        self.dict.contains_key("Encrypt")
    }

    /// Get the encryption dictionary reference
    pub fn encrypt(&self) -> ParseResult<Option<(u32, u16)>> {
        Ok(self.dict.get("Encrypt").and_then(|obj| obj.as_reference()))
    }

    /// Validate the trailer dictionary
    pub fn validate(&self) -> ParseResult<()> {
        // Required entries
        self.size()?;
        self.root()?;

        // Note: Encryption is now handled by the reader, not rejected here

        Ok(())
    }

    /// Get access to the trailer dictionary
    pub fn dict(&self) -> &PdfDictionary {
        &self.dict
    }
}

/// Represents the complete trailer chain for PDFs with updates
#[derive(Debug)]
pub struct TrailerChain {
    /// List of trailers from newest to oldest
    trailers: Vec<PdfTrailer>,
}

impl TrailerChain {
    /// Create a new trailer chain with a single trailer
    pub fn new(trailer: PdfTrailer) -> Self {
        Self {
            trailers: vec![trailer],
        }
    }

    /// Add an older trailer to the chain
    pub fn add_previous(&mut self, trailer: PdfTrailer) {
        self.trailers.push(trailer);
    }

    /// Get the most recent trailer
    pub fn current(&self) -> &PdfTrailer {
        &self.trailers[0]
    }

    /// Get all trailers in the chain
    pub fn all(&self) -> &[PdfTrailer] {
        &self.trailers
    }

    /// Check if there are previous versions
    pub fn has_previous(&self) -> bool {
        self.trailers.len() > 1
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::objects::{PdfArray, PdfObject, PdfString};

    #[test]
    fn test_trailer_basic() {
        let mut dict = PdfDictionary::new();
        dict.insert("Size".to_string(), PdfObject::Integer(100));
        dict.insert("Root".to_string(), PdfObject::Reference(1, 0));

        let trailer = PdfTrailer::from_dict(dict, 12345).unwrap();

        assert_eq!(trailer.size().unwrap(), 100);
        assert_eq!(trailer.root().unwrap(), (1, 0));
        assert!(trailer.info().is_none());
        assert!(!trailer.is_encrypted());
    }

    #[test]
    fn test_trailer_with_prev() {
        let mut dict = PdfDictionary::new();
        dict.insert("Size".to_string(), PdfObject::Integer(200));
        dict.insert("Root".to_string(), PdfObject::Reference(1, 0));
        dict.insert("Prev".to_string(), PdfObject::Integer(5000));

        let trailer = PdfTrailer::from_dict(dict, 20000).unwrap();

        assert_eq!(trailer.prev, Some(5000));
        assert_eq!(trailer.xref_offset, 20000);
    }

    #[test]
    fn test_trailer_validation() {
        // Missing Size
        let mut dict = PdfDictionary::new();
        dict.insert("Root".to_string(), PdfObject::Reference(1, 0));

        let trailer = PdfTrailer::from_dict(dict, 12345).unwrap();
        assert!(trailer.validate().is_err());

        // Missing Root
        let mut dict = PdfDictionary::new();
        dict.insert("Size".to_string(), PdfObject::Integer(100));

        let trailer = PdfTrailer::from_dict(dict, 12345).unwrap();
        assert!(trailer.validate().is_err());

        // Encrypted
        let mut dict = PdfDictionary::new();
        dict.insert("Size".to_string(), PdfObject::Integer(100));
        dict.insert("Root".to_string(), PdfObject::Reference(1, 0));
        dict.insert("Encrypt".to_string(), PdfObject::Reference(10, 0));

        let trailer = PdfTrailer::from_dict(dict, 12345).unwrap();
        // Encryption is now handled by the reader, not rejected at trailer level
        assert!(trailer.validate().is_ok());
        // But we can still detect that encryption is present
        assert!(trailer.encrypt().unwrap().is_some());
    }

    #[test]
    fn test_trailer_with_info() {
        let mut dict = PdfDictionary::new();
        dict.insert("Size".to_string(), PdfObject::Integer(150));
        dict.insert("Root".to_string(), PdfObject::Reference(1, 0));
        dict.insert("Info".to_string(), PdfObject::Reference(2, 0));

        let trailer = PdfTrailer::from_dict(dict, 15000).unwrap();

        assert_eq!(trailer.info(), Some((2, 0)));
        assert_eq!(trailer.size().unwrap(), 150);
    }

    #[test]
    fn test_trailer_with_id() {
        let mut dict = PdfDictionary::new();
        dict.insert("Size".to_string(), PdfObject::Integer(100));
        dict.insert("Root".to_string(), PdfObject::Reference(1, 0));

        let mut id_array = PdfArray::new();
        id_array.push(PdfObject::String(PdfString(b"ID1".to_vec())));
        id_array.push(PdfObject::String(PdfString(b"ID2".to_vec())));
        dict.insert("ID".to_string(), PdfObject::Array(id_array));

        let trailer = PdfTrailer::from_dict(dict, 10000).unwrap();

        assert!(trailer.id().is_some());
        assert!(matches!(trailer.id().unwrap(), PdfObject::Array(_)));
    }

    #[test]
    fn test_trailer_size_missing() {
        let mut dict = PdfDictionary::new();
        dict.insert("Root".to_string(), PdfObject::Reference(1, 0));

        let trailer = PdfTrailer::from_dict(dict, 1000).unwrap();

        match trailer.size() {
            Err(ParseError::MissingKey(key)) => assert_eq!(key, "Size"),
            _ => panic!("Expected MissingKey error for Size"),
        }
    }

    #[test]
    fn test_trailer_root_missing() {
        let mut dict = PdfDictionary::new();
        dict.insert("Size".to_string(), PdfObject::Integer(100));

        let trailer = PdfTrailer::from_dict(dict, 1000).unwrap();

        match trailer.root() {
            Err(ParseError::MissingKey(key)) => assert_eq!(key, "Root"),
            _ => panic!("Expected MissingKey error for Root"),
        }
    }

    #[test]
    fn test_trailer_invalid_size_type() {
        let mut dict = PdfDictionary::new();
        dict.insert(
            "Size".to_string(),
            PdfObject::String(PdfString(b"not a number".to_vec())),
        );
        dict.insert("Root".to_string(), PdfObject::Reference(1, 0));

        let trailer = PdfTrailer::from_dict(dict, 1000).unwrap();

        assert!(trailer.size().is_err());
    }

    #[test]
    fn test_trailer_invalid_root_type() {
        let mut dict = PdfDictionary::new();
        dict.insert("Size".to_string(), PdfObject::Integer(100));
        dict.insert(
            "Root".to_string(),
            PdfObject::String(PdfString(b"not a reference".to_vec())),
        );

        let trailer = PdfTrailer::from_dict(dict, 1000).unwrap();

        assert!(trailer.root().is_err());
    }

    #[test]
    fn test_trailer_encrypt_reference() {
        let mut dict = PdfDictionary::new();
        dict.insert("Size".to_string(), PdfObject::Integer(100));
        dict.insert("Root".to_string(), PdfObject::Reference(1, 0));
        dict.insert("Encrypt".to_string(), PdfObject::Reference(5, 0));

        let trailer = PdfTrailer::from_dict(dict, 1000).unwrap();

        assert!(trailer.is_encrypted());
        assert_eq!(trailer.encrypt().unwrap(), Some((5, 0)));
    }

    #[test]
    fn test_trailer_chain_single() {
        let mut dict = PdfDictionary::new();
        dict.insert("Size".to_string(), PdfObject::Integer(100));
        dict.insert("Root".to_string(), PdfObject::Reference(1, 0));

        let trailer = PdfTrailer::from_dict(dict, 1000).unwrap();
        let chain = TrailerChain::new(trailer);

        assert!(!chain.has_previous());
        assert_eq!(chain.all().len(), 1);
        assert_eq!(chain.current().xref_offset, 1000);
    }

    #[test]
    fn test_trailer_chain_multiple() {
        let mut dict1 = PdfDictionary::new();
        dict1.insert("Size".to_string(), PdfObject::Integer(100));
        dict1.insert("Root".to_string(), PdfObject::Reference(1, 0));
        dict1.insert("Prev".to_string(), PdfObject::Integer(500));
        let trailer1 = PdfTrailer::from_dict(dict1, 1000).unwrap();

        let mut dict2 = PdfDictionary::new();
        dict2.insert("Size".to_string(), PdfObject::Integer(80));
        dict2.insert("Root".to_string(), PdfObject::Reference(1, 0));
        let trailer2 = PdfTrailer::from_dict(dict2, 500).unwrap();

        let mut chain = TrailerChain::new(trailer1);
        chain.add_previous(trailer2);

        assert!(chain.has_previous());
        assert_eq!(chain.all().len(), 2);
        assert_eq!(chain.current().xref_offset, 1000);
        assert_eq!(chain.all()[1].xref_offset, 500);
    }

    #[test]
    fn test_trailer_prev_as_float() {
        let mut dict = PdfDictionary::new();
        dict.insert("Size".to_string(), PdfObject::Integer(100));
        dict.insert("Root".to_string(), PdfObject::Reference(1, 0));
        dict.insert("Prev".to_string(), PdfObject::Real(5000.0));

        let trailer = PdfTrailer::from_dict(dict, 10000).unwrap();

        // Real numbers should not be converted to prev offset
        assert_eq!(trailer.prev, None);
    }

    #[test]
    fn test_trailer_large_values() {
        let mut dict = PdfDictionary::new();
        dict.insert("Size".to_string(), PdfObject::Integer(i64::MAX));
        dict.insert("Root".to_string(), PdfObject::Reference(u32::MAX, u16::MAX));
        dict.insert("Prev".to_string(), PdfObject::Integer(i64::MAX));

        let trailer = PdfTrailer::from_dict(dict, u64::MAX).unwrap();

        assert_eq!(trailer.size().unwrap(), u32::MAX);
        assert_eq!(trailer.root().unwrap(), (u32::MAX, u16::MAX));
        assert_eq!(trailer.prev, Some(i64::MAX as u64));
        assert_eq!(trailer.xref_offset, u64::MAX);
    }

    #[test]
    fn test_trailer_all_optional_fields() {
        let mut dict = PdfDictionary::new();
        dict.insert("Size".to_string(), PdfObject::Integer(200));
        dict.insert("Root".to_string(), PdfObject::Reference(1, 0));
        dict.insert("Info".to_string(), PdfObject::Reference(2, 0));
        dict.insert("Prev".to_string(), PdfObject::Integer(1000));

        let mut id_array = PdfArray::new();
        id_array.push(PdfObject::String(PdfString(b"FirstID".to_vec())));
        id_array.push(PdfObject::String(PdfString(b"SecondID".to_vec())));
        dict.insert("ID".to_string(), PdfObject::Array(id_array));

        let trailer = PdfTrailer::from_dict(dict.clone(), 5000).unwrap();

        assert_eq!(trailer.size().unwrap(), 200);
        assert_eq!(trailer.root().unwrap(), (1, 0));
        assert_eq!(trailer.info(), Some((2, 0)));
        assert_eq!(trailer.prev, Some(1000));
        assert!(trailer.id().is_some());
        assert!(!trailer.is_encrypted());
        assert_eq!(trailer.xref_offset, 5000);

        // Verify validation passes
        assert!(trailer.validate().is_ok());
    }

    #[test]
    fn test_trailer_chain_ordering() {
        let trailers: Vec<PdfTrailer> = (0..5)
            .map(|i| {
                let mut dict = PdfDictionary::new();
                dict.insert("Size".to_string(), PdfObject::Integer(100 + i));
                dict.insert("Root".to_string(), PdfObject::Reference(1, 0));
                if i > 0 {
                    dict.insert("Prev".to_string(), PdfObject::Integer(i * 1000));
                }
                PdfTrailer::from_dict(dict, ((i + 1) * 1000) as u64).unwrap()
            })
            .collect();

        let mut chain = TrailerChain::new(trailers[0].clone());
        for trailer in trailers.iter().skip(1) {
            chain.add_previous(trailer.clone());
        }

        assert_eq!(chain.all().len(), 5);
        assert!(chain.has_previous());

        // Verify ordering (newest first)
        assert_eq!(chain.current().xref_offset, 1000);
        assert_eq!(chain.all()[0].xref_offset, 1000);
        assert_eq!(chain.all()[4].xref_offset, 5000);
    }
}