1use crate::Result;
2use crate::{Dictionary, Document, Object, ObjectId, Stream, FontData};
3
4impl Document {
5 pub fn with_version<S: Into<String>>(version: S) -> Document {
7 let mut document = Self::new();
8 document.version = version.into();
9 document
10 }
11
12 pub fn new_object_id(&mut self) -> ObjectId {
14 self.max_id += 1;
15 (self.max_id, 0)
16 }
17
18 pub fn add_object<T: Into<Object>>(&mut self, object: T) -> ObjectId {
20 self.max_id += 1;
21 let id = (self.max_id, 0);
22 self.objects.insert(id, object.into());
23 id
24 }
25
26 pub fn set_object<T: Into<Object>>(&mut self, id: ObjectId, object: T) {
27 self.objects.insert(id, object.into());
28 }
29
30 pub fn remove_object(&mut self, object_id: &ObjectId) -> Result<()> {
35 self.objects.remove(object_id);
36 Ok(())
37 }
38
39 pub fn remove_annot(&mut self, object_id: &ObjectId) -> Result<()> {
44 for (_, page_id) in self.get_pages() {
45 let page = self.get_object_mut(page_id)?.as_dict_mut()?;
46 let annots = page.get_mut(b"Annots")?.as_array_mut()?;
47
48 annots.retain(|object| {
49 if let Ok(id) = object.as_reference() {
50 return id != *object_id;
51 }
52
53 true
54 });
55 }
56
57 self.remove_object(object_id)?;
58
59 Ok(())
60 }
61
62 pub fn get_or_create_resources(&mut self, page_id: ObjectId) -> Result<&mut Object> {
66 let resources_id = {
67 let page = self.get_object(page_id).and_then(Object::as_dict)?;
68 if page.has(b"Resources") {
69 page.get(b"Resources").and_then(Object::as_reference).ok()
70 } else {
71 None
72 }
73 };
74 if let Some(res_id) = resources_id {
75 return self.get_object_mut(res_id);
76 }
77 let page = self.get_object_mut(page_id).and_then(Object::as_dict_mut)?;
78 if !page.has(b"Resources") {
79 page.set(b"Resources", Dictionary::new());
80 }
81 page.get_mut(b"Resources")
82 }
83
84 pub fn add_xobject<N: Into<Vec<u8>>>(
88 &mut self, page_id: ObjectId, xobject_name: N, xobject_id: ObjectId,
89 ) -> Result<()> {
90 if let Ok(resources) = self.get_or_create_resources(page_id).and_then(Object::as_dict_mut) {
91 if !resources.has(b"XObject") {
92 resources.set("XObject", Dictionary::new());
93 }
94 let mut xobjects = resources.get_mut(b"XObject")?;
95 if let Object::Reference(xobjects_ref_id) = xobjects {
96 let mut xobjects_id = *xobjects_ref_id;
97 while let Object::Reference(id) = self.get_object(xobjects_id)? {
98 xobjects_id = *id;
99 }
100 xobjects = self.get_object_mut(xobjects_id)?;
101 }
102 let xobjects = Object::as_dict_mut(xobjects)?;
103 xobjects.set(xobject_name, Object::Reference(xobject_id));
104 }
105 Ok(())
106 }
107
108 pub fn add_graphics_state<N: Into<Vec<u8>>>(
112 &mut self, page_id: ObjectId, gs_name: N, gs_id: ObjectId,
113 ) -> Result<()> {
114 if let Ok(resources) = self.get_or_create_resources(page_id).and_then(Object::as_dict_mut) {
115 if !resources.has(b"ExtGState") {
116 resources.set("ExtGState", Dictionary::new());
117 }
118 let states = resources.get_mut(b"ExtGState").and_then(Object::as_dict_mut)?;
119 states.set(gs_name, Object::Reference(gs_id));
120 }
121 Ok(())
122 }
123
124 pub fn add_font(&mut self, font_data: FontData) -> Result<ObjectId> {
158 let font_stream = Stream::new(
160 dictionary! {
161 "Length1" => Object::Integer(font_data.bytes().len() as i64),
162 },
163 font_data.bytes(),
164 );
165 let font_file_id = self.add_object(font_stream);
166 let font_name = font_data.font_name.clone();
167
168 let font_descriptor_id = self.add_object(dictionary! {
170 "Type" => "FontDescriptor",
171 "FontName" => Object::Name(font_name.clone().into_bytes()),
172 "Flags" => Object::Integer(font_data.flags),
173 "FontBBox" => Object::Array(vec![
174 Object::Integer(font_data.font_bbox.0),
175 Object::Integer(font_data.font_bbox.1),
176 Object::Integer(font_data.font_bbox.2),
177 Object::Integer(font_data.font_bbox.3),
178 ]),
179 "ItalicAngle" => Object::Integer(font_data.italic_angle),
180 "Ascent" => Object::Integer(font_data.ascent),
181 "Descent" => Object::Integer(font_data.descent),
182 "CapHeight" => Object::Integer(font_data.cap_height),
183 "StemV" => Object::Integer(font_data.stem_v),
184 "FontFile2" => Object::Reference(font_file_id),
185 });
186
187 let font_id = self.add_object(dictionary! {
189 "Type" => "Font",
190 "Subtype" => "TrueType",
191 "BaseFont" => Object::Name(font_name.clone().into_bytes()),
192 "FontDescriptor" => Object::Reference(font_descriptor_id),
193 "Encoding" => Object::Name(font_data.encoding.into_bytes()),
194 });
195
196 Ok(font_id)
197 }
198}
199
200#[cfg(test)]
201pub mod tests {
202 use std::path::PathBuf;
203
204 use crate::content::*;
205 use crate::{Document, FontData, Object, Stream};
206
207 #[cfg(not(feature = "time"))]
208 pub fn get_timestamp() -> Object {
209 Object::string_literal("D:19700101000000Z")
210 }
211
212 #[cfg(feature = "time")]
213 pub fn get_timestamp() -> Object {
214 time::OffsetDateTime::now_utc().into()
215 }
216
217 pub fn create_document() -> Document {
219 create_document_with_texts(&["Hello World!"])
220 }
221
222 pub fn create_document_with_texts(texts_for_pages: &[&str]) -> Document {
223 let mut doc = Document::with_version("1.5");
224 let info_id = doc.add_object(dictionary! {
225 "Title" => Object::string_literal("Create PDF document example"),
226 "Creator" => Object::string_literal("https://crates.io/crates/lopdf"),
227 "CreationDate" => get_timestamp(),
228 });
229 let pages_id = doc.new_object_id();
230 let font_id = doc.add_object(dictionary! {
231 "Type" => "Font",
232 "Subtype" => "Type1",
233 "BaseFont" => "Courier",
234 });
235 let resources_id = doc.add_object(dictionary! {
236 "Font" => dictionary! {
237 "F1" => font_id,
238 },
239 });
240 let contents = texts_for_pages.iter().map(|text| Content {
241 operations: vec![
242 Operation::new("BT", vec![]),
243 Operation::new("Tf", vec!["F1".into(), 48.into()]),
244 Operation::new("Td", vec![100.into(), 600.into()]),
245 Operation::new("Tj", vec![Object::string_literal(*text)]),
246 Operation::new("ET", vec![]),
247 ],
248 });
249
250 let pages = contents.map(|content| {
251 let content_id = doc.add_object(Stream::new(dictionary! {}, content.encode().unwrap()));
252 let page = doc.add_object(dictionary! {
253 "Type" => "Page",
254 "Parent" => pages_id,
255 "Contents" => content_id,
256 });
257 page.into()
258 });
259
260 let pages = dictionary! {
261 "Type" => "Pages",
262 "Kids" => pages.collect::<Vec<Object>>(),
263 "Count" => 1,
264 "Resources" => resources_id,
265 "MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()],
266 };
267 doc.objects.insert(pages_id, Object::Dictionary(pages));
268 let catalog_id = doc.add_object(dictionary! {
269 "Type" => "Catalog",
270 "Pages" => pages_id,
271 });
272 doc.trailer.set("Root", catalog_id);
273 doc.trailer.set("Info", info_id);
274 doc.trailer.set("ID", Object::Array(vec![
275 Object::string_literal(b"ABC"),
276 Object::string_literal(b"DEF"),
277 ]));
278 doc.compress();
279 doc
280 }
281
282 pub fn save_document(file_path: &PathBuf, doc: &mut Document) {
284 let res = doc.save(file_path);
285
286 assert!(match res {
287 Ok(_file) => true,
288 Err(_e) => false,
289 });
290 }
291
292 #[test]
293 fn save_created_document() {
294 let temp_dir = tempfile::tempdir().unwrap();
296 let file_path = temp_dir.path().join("test_1_create.pdf");
297
298 let mut doc = create_document();
299 save_document(&file_path, &mut doc);
301 assert!(file_path.exists());
302 }
303
304 #[test]
305 fn test_add_font_embeds_font_correctly() {
306 let font_file = std::fs::read("./tests/resources/fonts/Montserrat-Regular.ttf").unwrap();
308
309 let mut font_data = FontData::new(&font_file, "MyFont".to_string());
311 font_data
312 .set_flags(32)
313 .set_font_bbox((0, -200, 1000, 800))
314 .set_italic_angle(0)
315 .set_ascent(750)
316 .set_descent(-250)
317 .set_cap_height(700)
318 .set_stem_v(80)
319 .set_encoding("WinAnsiEncoding".to_string());
320
321 let mut doc = Document::with_version("1.5");
323
324 let page_id = doc.new_object_id();
326 doc.set_object(page_id, dictionary! {});
327
328 let font_id = doc.add_font(font_data.clone()).unwrap();
330
331 let font_obj = doc.get_object(font_id).unwrap();
333 let font_dict = font_obj.as_dict().unwrap();
334
335 assert_eq!(font_dict.get(b"BaseFont").unwrap(), &Object::Name(b"MyFont".to_vec()));
337
338 assert_eq!(
340 font_dict.get(b"Encoding").unwrap(),
341 &Object::Name(b"WinAnsiEncoding".to_vec())
342 );
343
344 let descriptor_ref = font_dict.get(b"FontDescriptor").unwrap().as_reference().unwrap();
346 let descriptor_obj = doc.get_object(descriptor_ref).unwrap().as_dict().unwrap();
347 assert_eq!(
348 descriptor_obj.get(b"FontName").unwrap(),
349 &Object::Name(b"MyFont".to_vec())
350 );
351
352 let font_file_ref = descriptor_obj.get(b"FontFile2").unwrap().as_reference().unwrap();
354 let font_stream = doc.get_object(font_file_ref).unwrap().as_stream().unwrap();
355 assert_eq!(font_stream.content, font_file);
356 }
357}