Skip to main content

pivot_pdf/
objects.rs

1/// Object identifier: (object_number, generation_number).
2/// Generation is always 0 for new documents.
3#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4pub struct ObjId(pub u32, pub u16);
5
6/// Represents PDF object types per PDF 32000-1:2008 Section 7.3.
7#[derive(Debug, Clone)]
8pub enum PdfObject {
9    /// PDF null object.
10    Null,
11    /// PDF boolean object.
12    Boolean(bool),
13    /// PDF integer object.
14    Integer(i64),
15    /// PDF real (floating-point) object.
16    Real(f64),
17    /// PDF name object (stored without the leading `/`).
18    Name(String),
19    /// PDF literal string (stored without the enclosing parens).
20    LiteralString(String),
21    /// PDF array object.
22    Array(Vec<PdfObject>),
23    /// Key-value pairs. Uses Vec for deterministic output order.
24    Dictionary(Vec<(String, PdfObject)>),
25    /// PDF stream object: a dictionary plus a byte sequence.
26    Stream {
27        /// Stream dictionary entries (excluding `/Length`, which is added on write).
28        dict: Vec<(String, PdfObject)>,
29        /// Raw stream bytes.
30        data: Vec<u8>,
31    },
32    /// Indirect object reference (`N G R`).
33    Reference(ObjId),
34}
35
36impl PdfObject {
37    /// Construct a `Name` object from a string slice (without the leading `/`).
38    pub fn name(s: &str) -> Self {
39        PdfObject::Name(s.to_string())
40    }
41
42    /// Construct a `LiteralString` object from a string slice.
43    pub fn literal_string(s: &str) -> Self {
44        PdfObject::LiteralString(s.to_string())
45    }
46
47    /// Construct a `Reference` object from an object number and generation number.
48    pub fn reference(obj_num: u32, gen: u16) -> Self {
49        PdfObject::Reference(ObjId(obj_num, gen))
50    }
51
52    /// Construct an `Array` object from a vector of items.
53    pub fn array(items: Vec<PdfObject>) -> Self {
54        PdfObject::Array(items)
55    }
56
57    /// Construct a `Dictionary` object from a slice of `(key, value)` pairs.
58    pub fn dict(entries: Vec<(&str, PdfObject)>) -> Self {
59        PdfObject::Dictionary(
60            entries
61                .into_iter()
62                .map(|(k, v)| (k.to_string(), v))
63                .collect(),
64        )
65    }
66
67    /// Construct a `Stream` object from a dictionary and raw byte data.
68    pub fn stream(dict_entries: Vec<(&str, PdfObject)>, data: Vec<u8>) -> Self {
69        PdfObject::Stream {
70            dict: dict_entries
71                .into_iter()
72                .map(|(k, v)| (k.to_string(), v))
73                .collect(),
74            data,
75        }
76    }
77}