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
use crate::{Dictionary, Document, Object, ObjectId};
use crate::{Error, Result};

impl Document {
    /// Create new PDF document with version.
    pub fn with_version<S: Into<String>>(version: S) -> Document {
        let mut document = Self::new();
        document.version = version.into();
        document
    }

    /// Create an object ID.
    pub fn new_object_id(&mut self) -> ObjectId {
        self.max_id += 1;
        (self.max_id, 0)
    }

    /// Add PDF object into document's object list.
    pub fn add_object<T: Into<Object>>(&mut self, object: T) -> ObjectId {
        self.max_id += 1;
        let id = (self.max_id, 0);
        self.objects.insert(id, object.into());
        id
    }

    /// Remove PDF object from document's object list.
    pub fn remove_object(&mut self, object_id: &ObjectId) -> Result<()> {
        for (_, page_id) in self.get_pages() {
            let page = self.get_object_mut(page_id)?.as_dict_mut()?;
            let annots = page.get_mut(b"Annots")?.as_array_mut()?;

            annots.retain(|object| {
                if let Ok(id) = object.as_reference() {
                    return id != *object_id;
                }

                true
            });
        }

        Ok(())
    }

    fn get_or_create_resources_mut(&mut self, page_id: ObjectId) -> Result<&mut Object> {
        let page = self.get_object_mut(page_id).and_then(Object::as_dict_mut)?;
        if page.has(b"Resources") {
            if let Ok(_res_id) = page.get(b"Resources").and_then(Object::as_reference) {
                // self.get_object_mut(res_id)
                Err(Error::ObjectNotFound)
            } else {
                page.get_mut(b"Resources")
            }
        } else {
            page.set("Resources", Dictionary::new());
            page.get_mut(b"Resources")
        }
    }

    pub fn get_or_create_resources(&mut self, page_id: ObjectId) -> Result<&mut Object> {
        let mut resources_id = None;
        {
            let page = self.get_object(page_id).and_then(Object::as_dict)?;
            if page.has(b"Resources") {
                resources_id = page.get(b"Resources").and_then(Object::as_reference).ok();
            }
        }
        match resources_id {
            Some(res_id) => self.get_object_mut(res_id),
            None => self.get_or_create_resources_mut(page_id),
        }
    }

    pub fn add_xobject<N: Into<Vec<u8>>>(
        &mut self,
        page_id: ObjectId,
        xobject_name: N,
        xobject_id: ObjectId,
    ) -> Result<()> {
        if let Ok(resources) = self
            .get_or_create_resources(page_id)
            .and_then(Object::as_dict_mut)
        {
            if !resources.has(b"XObject") {
                resources.set("XObject", Dictionary::new());
            }
            let xobjects = resources
                .get_mut(b"XObject")
                .and_then(Object::as_dict_mut)?;
            xobjects.set(xobject_name, Object::Reference(xobject_id));
        }
        Ok(())
    }

    pub fn add_graphics_state<N: Into<Vec<u8>>>(
        &mut self,
        page_id: ObjectId,
        gs_name: N,
        gs_id: ObjectId,
    ) -> Result<()> {
        if let Ok(resources) = self
            .get_or_create_resources(page_id)
            .and_then(Object::as_dict_mut)
        {
            if !resources.has(b"ExtGState") {
                resources.set("ExtGState", Dictionary::new());
            }
            let states = resources
                .get_mut(b"ExtGState")
                .and_then(Object::as_dict_mut)?;
            states.set(gs_name, Object::Reference(gs_id));
        }
        Ok(())
    }
}

#[cfg(test)]
pub mod tests {
    use std::fs::remove_file;
    use std::path::Path;
    use std::sync::Mutex;

    use crate::content::*;
    use crate::{Document, Object, Stream};
    use lazy_static::lazy_static;

    lazy_static! {
        /// Tests that save and share files are vulnerable to race conditions
        /// Use a mutex so only one test at a time has access to update it
        /// The lock will last for the length of the let block in the tests
        static ref DOC_FILE_MUTEX: Mutex<()> = Mutex::new(());
    }

    /// Create and return a document for testing
    pub fn create_document() -> Document {
        let mut doc = Document::with_version("1.5");
        let info_id = doc.add_object(dictionary! {
            "Title" => Object::string_literal("Create PDF document example"),
            "Creator" => Object::string_literal("https://crates.io/crates/lopdf"),
            "CreationDate" => time::OffsetDateTime::now_utc(),
        });
        let pages_id = doc.new_object_id();
        let font_id = doc.add_object(dictionary! {
            "Type" => "Font",
            "Subtype" => "Type1",
            "BaseFont" => "Courier",
        });
        let resources_id = doc.add_object(dictionary! {
            "Font" => dictionary! {
                "F1" => font_id,
            },
        });
        let content = Content {
            operations: vec![
                Operation::new("BT", vec![]),
                Operation::new("Tf", vec!["F1".into(), 48.into()]),
                Operation::new("Td", vec![100.into(), 600.into()]),
                Operation::new("Tj", vec![Object::string_literal("Hello World!")]),
                Operation::new("ET", vec![]),
            ],
        };
        let content_id = doc.add_object(Stream::new(dictionary! {}, content.encode().unwrap()));
        let page_id = doc.add_object(dictionary! {
            "Type" => "Page",
            "Parent" => pages_id,
            "Contents" => content_id,
        });
        let pages = dictionary! {
            "Type" => "Pages",
            "Kids" => vec![page_id.into()],
            "Count" => 1,
            "Resources" => resources_id,
            "MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()],
        };
        doc.objects.insert(pages_id, Object::Dictionary(pages));
        let catalog_id = doc.add_object(dictionary! {
            "Type" => "Catalog",
            "Pages" => pages_id,
        });
        doc.trailer.set("Root", catalog_id);
        doc.trailer.set("Info", info_id);
        doc.compress();

        doc
    }

    /// Save a document
    pub fn save_document(filename: &String, doc: &mut Document) {
        let res = doc.save(filename);

        assert!(match res {
            Ok(_file) => true,
            Err(_e) => false,
        });
    }

    /// Remove a document
    pub fn remove_document(filename: &String) {
        let path = Path::new(&filename);

        assert_ne!(path.as_os_str(), "");
        assert_ne!(path.as_os_str(), "/");

        let exists = path.exists();
        assert!(exists);

        if exists {
            remove_file(path).unwrap();
        }
    }

    #[test]
    fn create_document_creates_document() {
        let filename = String::from("test_1_create.pdf");
        let path = Path::new(&filename);
        let mut doc = create_document();

        {
            let _m = DOC_FILE_MUTEX.lock().unwrap();
            save_document(&filename, &mut doc);
            assert!(path.exists());
            remove_document(&filename);
        }
    }

    #[test]
    fn remove_document_removes_document() {
        let filename = String::from("test_1_create.pdf");

        let path = Path::new(&filename);

        let mut doc = create_document();

        {
            let _m = DOC_FILE_MUTEX.lock().unwrap();
            save_document(&filename, &mut doc);
            assert!(path.exists());
            remove_document(&filename);
            assert!(!path.exists());
        }
    }
}