Skip to main content

pdf_forms/
object.rs

1use crate::encodings;
2use crate::encodings::cmap::ToUnicodeCMap;
3use crate::encodings::{Differences, Encoding, Glyph};
4use crate::lopdf_error::DecompressError;
5use crate::{Document, Error, Result};
6use indexmap::IndexMap;
7use log::warn;
8use std::cmp::max;
9use std::collections::HashSet;
10use std::fmt;
11use std::str;
12
13/// Object identifier consists of two parts: object number and generation number.
14pub type ObjectId = (u32, u16);
15
16/// Dictionary object.
17#[derive(Clone, Default, PartialEq)]
18pub struct Dictionary(IndexMap<Vec<u8>, Object>);
19
20/// Stream object
21/// Warning - all streams must be indirect objects, while
22/// the stream dictionary may be a direct object
23#[derive(Debug, Clone, PartialEq)]
24pub struct Stream {
25    /// Associated stream dictionary
26    pub dict: Dictionary,
27    /// Contents of the stream in bytes
28    pub content: Vec<u8>,
29    /// Can the stream be compressed by the `Document::compress()` function?
30    /// Font streams may not be compressed, for example
31    pub allows_compression: bool,
32    /// Stream data's position in PDF file.
33    pub start_position: Option<usize>,
34}
35
36/// Basic PDF object types defined in an enum.
37#[derive(Clone, PartialEq)]
38pub enum Object {
39    Null,
40    Boolean(bool),
41    Integer(i64),
42    Real(f32),
43    Name(Vec<u8>),
44    String(Vec<u8>, StringFormat),
45    Array(Vec<Object>),
46    Dictionary(Dictionary),
47    Stream(Stream),
48    Reference(ObjectId),
49}
50
51/// String objects can be written in two formats.
52#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
53pub enum StringFormat {
54    #[default]
55    Literal,
56    Hexadecimal,
57}
58
59impl From<bool> for Object {
60    fn from(value: bool) -> Self {
61        Object::Boolean(value)
62    }
63}
64
65impl From<i64> for Object {
66    fn from(number: i64) -> Self {
67        Object::Integer(number)
68    }
69}
70
71macro_rules! from_smaller_ints {
72	($( $Int: ty )+) => {
73		$(
74			impl From<$Int> for Object {
75				fn from(number: $Int) -> Self {
76					Object::Integer(i64::from(number))
77				}
78			}
79		)+
80	}
81}
82
83from_smaller_ints! {
84    i8 i16 i32
85    u8 u16 u32
86}
87
88impl From<f64> for Object {
89    fn from(number: f64) -> Self {
90        Object::Real(number as f32)
91    }
92}
93
94impl From<f32> for Object {
95    fn from(number: f32) -> Self {
96        Object::Real(number)
97    }
98}
99
100impl From<String> for Object {
101    fn from(name: String) -> Self {
102        Object::Name(name.into_bytes())
103    }
104}
105
106impl<'a> From<&'a str> for Object {
107    fn from(name: &'a str) -> Self {
108        Object::Name(name.as_bytes().to_vec())
109    }
110}
111
112impl From<Vec<Object>> for Object {
113    fn from(array: Vec<Object>) -> Self {
114        Object::Array(array)
115    }
116}
117
118impl From<Dictionary> for Object {
119    fn from(dict: Dictionary) -> Self {
120        Object::Dictionary(dict)
121    }
122}
123
124impl From<Stream> for Object {
125    fn from(stream: Stream) -> Self {
126        Object::Stream(stream)
127    }
128}
129
130impl From<ObjectId> for Object {
131    fn from(id: ObjectId) -> Self {
132        Object::Reference(id)
133    }
134}
135
136impl Object {
137    pub fn string_literal<S: Into<Vec<u8>>>(s: S) -> Self {
138        Object::String(s.into(), StringFormat::Literal)
139    }
140
141    pub fn is_null(&self) -> bool {
142        matches!(*self, Object::Null)
143    }
144
145    pub fn as_bool(&self) -> Result<bool> {
146        match self {
147            Object::Boolean(value) => Ok(*value),
148            _ => Err(Error::ObjectType {
149                expected: "Boolean",
150                found: self.enum_variant(),
151            }),
152        }
153    }
154
155    pub fn as_i64(&self) -> Result<i64> {
156        match self {
157            Object::Integer(value) => Ok(*value),
158            _ => Err(Error::ObjectType {
159                expected: "Integer",
160                found: self.enum_variant(),
161            }),
162        }
163    }
164
165    pub fn as_f32(&self) -> Result<f32> {
166        match self {
167            Object::Real(value) => Ok(*value),
168            _ => Err(Error::ObjectType {
169                expected: "Real",
170                found: self.enum_variant(),
171            }),
172        }
173    }
174
175    /// Get the object value as a float.
176    /// Unlike [`Object::as_f32`] this will also cast an Integer to a Real.
177    pub fn as_float(&self) -> Result<f32> {
178        match self {
179            Object::Integer(value) => Ok(*value as f32),
180            Object::Real(value) => Ok(*value),
181            _ => Err(Error::ObjectType {
182                expected: "Integer or Real",
183                found: self.enum_variant(),
184            }),
185        }
186    }
187
188    pub fn as_name(&self) -> Result<&[u8]> {
189        match self {
190            Object::Name(name) => Ok(name),
191            _ => Err(Error::ObjectType {
192                expected: "Name",
193                found: self.enum_variant(),
194            }),
195        }
196    }
197
198    pub fn as_str(&self) -> Result<&[u8]> {
199        match self {
200            Object::String(string, _) => Ok(string),
201            _ => Err(Error::ObjectType {
202                expected: "String",
203                found: self.enum_variant(),
204            }),
205        }
206    }
207
208    pub fn as_str_mut(&mut self) -> Result<&mut Vec<u8>> {
209        match self {
210            Object::String(string, _) => Ok(string),
211            _ => Err(Error::ObjectType {
212                expected: "String",
213                found: self.enum_variant(),
214            }),
215        }
216    }
217
218    pub fn as_reference(&self) -> Result<ObjectId> {
219        match self {
220            Object::Reference(id) => Ok(*id),
221            _ => Err(Error::ObjectType {
222                expected: "Reference",
223                found: self.enum_variant(),
224            }),
225        }
226    }
227
228    pub fn as_array(&self) -> Result<&Vec<Object>> {
229        match self {
230            Object::Array(arr) => Ok(arr),
231            _ => Err(Error::ObjectType {
232                expected: "Array",
233                found: self.enum_variant(),
234            }),
235        }
236    }
237
238    pub fn as_array_mut(&mut self) -> Result<&mut Vec<Object>> {
239        match self {
240            Object::Array(arr) => Ok(arr),
241            _ => Err(Error::ObjectType {
242                expected: "Array",
243                found: self.enum_variant(),
244            }),
245        }
246    }
247
248    pub fn as_dict(&self) -> Result<&Dictionary> {
249        match self {
250            Object::Dictionary(dict) => Ok(dict),
251            _ => Err(Error::ObjectType {
252                expected: "Dictionary",
253                found: self.enum_variant(),
254            }),
255        }
256    }
257
258    pub fn as_dict_mut(&mut self) -> Result<&mut Dictionary> {
259        match self {
260            Object::Dictionary(dict) => Ok(dict),
261            _ => Err(Error::ObjectType {
262                expected: "Dictionary",
263                found: self.enum_variant(),
264            }),
265        }
266    }
267
268    pub fn as_stream(&self) -> Result<&Stream> {
269        match self {
270            Object::Stream(stream) => Ok(stream),
271            _ => Err(Error::ObjectType {
272                expected: "Stream",
273                found: self.enum_variant(),
274            }),
275        }
276    }
277
278    pub fn as_stream_mut(&mut self) -> Result<&mut Stream> {
279        match self {
280            Object::Stream(stream) => Ok(stream),
281            _ => Err(Error::ObjectType {
282                expected: "Stream",
283                found: self.enum_variant(),
284            }),
285        }
286    }
287
288    // TODO: maybe remove
289    pub fn type_name(&self) -> Result<&[u8]> {
290        match self {
291            Object::Dictionary(dict) => dict.get_type(),
292            Object::Stream(stream) => stream.dict.get_type(),
293            obj => Err(Error::ObjectType {
294                expected: "Dictionary or Stream",
295                found: obj.enum_variant(),
296            }),
297        }
298    }
299
300    pub fn enum_variant(&self) -> &'static str {
301        match self {
302            Object::Null => "Null",
303            Object::Boolean(_) => "Boolean",
304            Object::Integer(_) => "Integer",
305            Object::Real(_) => "Real",
306            Object::Name(_) => "Name",
307            Object::String(_, _) => "String",
308            Object::Array(_) => "Array",
309            Object::Dictionary(_) => "Dictionary",
310            Object::Stream(_) => "Stream",
311            Object::Reference(_) => "Reference",
312        }
313    }
314}
315
316impl fmt::Debug for Object {
317    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
318        match self {
319            Object::Null => write!(f, "Null"),
320            Object::Boolean(value) => write!(f, "{value}"),
321            Object::Integer(value) => write!(f, "{value}"),
322            Object::Real(value) => write!(f, "{value}"),
323            Object::Name(name) => write!(f, "/{}", String::from_utf8_lossy(name)),
324            Object::String(text, StringFormat::Literal) => {
325                write!(f, "({})", String::from_utf8_lossy(text))
326            }
327            Object::String(text, StringFormat::Hexadecimal) => {
328                write!(f, "<")?;
329                for b in text {
330                    write!(f, "{b:02x}")?
331                }
332                write!(f, ">")
333            }
334            Object::Array(array) => {
335                let items = array
336                    .iter()
337                    .map(|item| format!("{item:?}"))
338                    .collect::<Vec<String>>();
339                write!(f, "[{}]", items.join(" "))
340            }
341            Object::Dictionary(dict) => write!(f, "{dict:?}"),
342            Object::Stream(stream) => write!(f, "{:?}stream...endstream", stream.dict),
343            Object::Reference(id) => write!(f, "{} {} R", id.0, id.1),
344        }
345    }
346}
347
348impl Dictionary {
349    pub fn new() -> Dictionary {
350        Dictionary(IndexMap::new())
351    }
352
353    pub fn has(&self, key: &[u8]) -> bool {
354        self.0.contains_key(key)
355    }
356
357    pub fn get(&self, key: &[u8]) -> Result<&Object> {
358        self.0
359            .get(key)
360            .ok_or(Error::DictKey(String::from_utf8_lossy(key).to_string()))
361    }
362
363    /// Extract object from dictionary, dereferencing
364    /// the object if it is a reference.
365    pub fn get_deref<'a>(&'a self, key: &[u8], doc: &'a Document) -> Result<&'a Object> {
366        doc.dereference(self.get(key)?).map(|(_, object)| object)
367    }
368
369    pub fn get_mut(&mut self, key: &[u8]) -> Result<&mut Object> {
370        self.0
371            .get_mut(key)
372            .ok_or(Error::DictKey(String::from_utf8_lossy(key).to_string()))
373    }
374
375    pub fn set<K, V>(&mut self, key: K, value: V)
376    where
377        K: Into<Vec<u8>>,
378        V: Into<Object>,
379    {
380        self.0.insert(key.into(), value.into());
381    }
382
383    pub fn len(&self) -> usize {
384        self.0.len()
385    }
386
387    pub fn is_empty(&self) -> bool {
388        self.0.len() == 0
389    }
390
391    pub fn remove(&mut self, key: &[u8]) -> Option<Object> {
392        self.0.swap_remove(key)
393    }
394
395    pub fn has_type(&self, type_name: &[u8]) -> bool {
396        self.get(b"Type").and_then(|s| s.as_name()).ok() == Some(type_name)
397    }
398
399    pub fn get_type(&self) -> Result<&[u8]> {
400        self.get(b"Type")
401            .and_then(Object::as_name)
402            .or_else(|_| self.get(b"Linearized").and(Ok(b"Linearized")))
403    }
404
405    pub fn iter(&'_ self) -> indexmap::map::Iter<'_, Vec<u8>, Object> {
406        self.0.iter()
407    }
408
409    pub fn iter_mut(&'_ mut self) -> indexmap::map::IterMut<'_, Vec<u8>, Object> {
410        self.0.iter_mut()
411    }
412
413    pub fn get_font_encoding<'a>(&'a self, doc: &'a Document) -> Result<Encoding<'a>> {
414        if !self.has_type(b"Font") {
415            return Err(Error::DictType {
416                expected: "Font",
417                found: String::from_utf8_lossy(self.get_type().unwrap_or(b"None")).to_string(),
418            });
419        }
420
421        // Note: currently not all encodings are handled, not implemented:
422        // - TrueType cmap tables
423        // - DescendantFonts in CID-Keyed fonts
424        // - Predefined CJK CMAP other than indicated in SimpleEncoding
425        // - Deciding what should be the fallback font if no such encoding is defined in difference encoding (see Table
426        //   114 in 9.6.6.1 General under `BaseEncoding`).
427        let result = (|| {
428            if let Ok(object) = self.get(b"Encoding") {
429                return self.get_base_encoding(object, doc);
430            }
431
432            if let Ok(stream) = self
433                .get_deref(b"ToUnicode", doc)
434                .and_then(Object::as_stream)
435            {
436                return self.get_to_unicode_encoding(stream);
437            }
438
439            Ok(Encoding::OneByteEncoding(&encodings::STANDARD_ENCODING))
440        })();
441
442        match result {
443            Ok(encoding) => Ok(encoding),
444            Err(err) => {
445                warn!(
446                    "Could not parse the encoding, error: {err:#?}\nFont: {self:#?}. Using standard encoding as a fallback!"
447                );
448                Ok(Encoding::OneByteEncoding(&encodings::STANDARD_ENCODING))
449            }
450        }
451    }
452
453    /// Get a simple encoding from the /Encoding entry of a font dictionary.
454    fn get_base_encoding<'a>(
455        &'a self,
456        mut object: &'a Object,
457        doc: &'a Document,
458    ) -> Result<Encoding<'a>> {
459        // Set of visited to detect circular references.
460        let mut visited = HashSet::new();
461
462        loop {
463            match *object {
464                Object::Name(ref name) => {
465                    return self.base_encoding(doc, name);
466                }
467                Object::Reference(id) => {
468                    if !visited.insert(id) {
469                        return Err(Error::ReferenceCycle(id));
470                    }
471
472                    let Ok(o) = doc.get_object(id) else {
473                        return Err(Error::ObjectNotFound(id));
474                    };
475
476                    object = o;
477                }
478                Object::Dictionary(ref dict) => {
479                    let ty = dict.get(b"Type")?.as_name()?;
480
481                    match ty {
482                        b"Encoding" => {
483                            let mut base = None;
484
485                            if let Ok(base_encoding) = dict.get(b"BaseEncoding")
486                                && let Ok(name) = base_encoding.as_name()
487                            {
488                                base = Some(self.base_encoding(doc, name)?);
489                            }
490
491                            let base = match base {
492                                Some(base) => base,
493                                None => Encoding::OneByteEncoding(&encodings::STANDARD_ENCODING),
494                            };
495
496                            let differences = dict.get(b"Differences")?.as_array()?;
497                            let differences = self.differences(base, differences)?;
498                            return Ok(Encoding::Differences(differences));
499                        }
500                        _ => {
501                            return Err(Error::ObjectType {
502                                expected: "Encoding Dictionary",
503                                found: "Dictionary with Type other than /Encoding",
504                            });
505                        }
506                    }
507                }
508                ref object => {
509                    return Err(Error::ObjectType {
510                        expected: "Name or Reference or Dictionary",
511                        found: object.enum_variant(),
512                    });
513                }
514            }
515        }
516    }
517
518    fn base_encoding<'a>(&'a self, doc: &'a Document, name: &'a [u8]) -> Result<Encoding<'a>> {
519        match name {
520            b"StandardEncoding" => Ok(Encoding::OneByteEncoding(&encodings::STANDARD_ENCODING)),
521            b"MacRomanEncoding" => Ok(Encoding::OneByteEncoding(&encodings::MAC_ROMAN_ENCODING)),
522            b"MacExpertEncoding" => Ok(Encoding::OneByteEncoding(&encodings::MAC_EXPERT_ENCODING)),
523            b"WinAnsiEncoding" => Ok(Encoding::OneByteEncoding(&encodings::WIN_ANSI_ENCODING)),
524            b"PDFDocEncoding" => {
525                log::warn!("PDFDocEncoding is not a valid character encoding for a font");
526                Ok(Encoding::OneByteEncoding(&encodings::PDF_DOC_ENCODING))
527            }
528            b"Identity-H" | b"Identity-V" => {
529                let stream = self.get_deref(b"ToUnicode", doc)?.as_stream()?;
530                self.get_to_unicode_encoding(stream)
531            }
532            name => Ok(Encoding::SimpleEncoding(name)),
533        }
534    }
535
536    fn differences<'a>(&'a self, base: Encoding<'a>, array: &[Object]) -> Result<Differences<'a>> {
537        let mut map = IndexMap::new();
538        let mut inverse = IndexMap::new();
539        let mut current_code = 0;
540
541        for obj in array {
542            match *obj {
543                Object::Integer(code) => {
544                    if !(0..=255).contains(&code) {
545                        return Err(Error::InvalidEncodingDifferenceCode { code });
546                    }
547
548                    current_code = code as u8;
549                }
550                Object::Name(ref name) => {
551                    let Some(glyph) = Glyph::from_name(name) else {
552                        return Err(Error::InvalidEncodingDifferenceGlyph {
553                            name: String::from_utf8_lossy(name).into_owned(),
554                        });
555                    };
556
557                    map.insert(current_code, glyph);
558                    inverse.insert(glyph, current_code);
559                    current_code = current_code.wrapping_add(1);
560                }
561                _ => {
562                    return Err(Error::ObjectType {
563                        expected: "Integer or Name",
564                        found: obj.enum_variant(),
565                    });
566                }
567            }
568        }
569
570        Ok(Differences {
571            base: Box::new(base),
572            map,
573            inverse,
574        })
575    }
576
577    fn get_to_unicode_encoding(&'_ self, stream: &Stream) -> Result<Encoding<'_>> {
578        let content = stream.get_plain_content()?;
579        let cmap = ToUnicodeCMap::parse(content)?;
580        Ok(Encoding::UnicodeMapEncoding(cmap))
581    }
582
583    pub fn extend(&mut self, other: &Dictionary) {
584        let keep_both_objects = |new_dict: &mut IndexMap<Vec<u8>, Object>,
585                                 key: &Vec<u8>,
586                                 value: &Object,
587                                 old_value: Object| {
588            let mut final_array;
589
590            match value {
591                Object::Array(array) => {
592                    final_array = Vec::with_capacity(array.len() + 1);
593                    final_array.push(old_value);
594                    final_array.extend(array.to_owned());
595                }
596                _ => {
597                    final_array = vec![value.to_owned(), old_value];
598                }
599            }
600
601            new_dict.insert(key.to_owned(), Object::Array(final_array));
602        };
603
604        let mut new_dict = std::mem::take(&mut self.0);
605        new_dict.reserve_exact(other.0.len());
606
607        for (key, value) in other.0.iter() {
608            if let Some(old_value) = new_dict.get(key) {
609                let old_value = old_value.to_owned();
610                match (&old_value, value) {
611                    (Object::Dictionary(old_dict), Object::Dictionary(dict)) => {
612                        let mut replaced_dict = old_dict.to_owned();
613                        replaced_dict.extend(dict);
614                        new_dict.insert(key.to_owned(), Object::Dictionary(replaced_dict));
615                    }
616                    (Object::Array(old_array), Object::Array(array)) => {
617                        let mut replaced_array = old_array.to_owned();
618                        replaced_array.extend(array.to_owned());
619                        new_dict.insert(key.to_owned(), Object::Array(replaced_array));
620                    }
621                    (Object::Integer(old_id), Object::Integer(id)) => {
622                        let array = vec![Object::Integer(*old_id), Object::Integer(*id)];
623                        new_dict.insert(key.to_owned(), Object::Array(array));
624                    }
625                    (Object::Real(old_id), Object::Real(id)) => {
626                        let array = vec![Object::Real(*old_id), Object::Real(*id)];
627                        new_dict.insert(key.to_owned(), Object::Array(array));
628                    }
629                    (Object::String(old_ids, old_format), Object::String(ids, format)) => {
630                        let array = vec![
631                            Object::String(old_ids.to_owned(), old_format.to_owned()),
632                            Object::String(ids.to_owned(), format.to_owned()),
633                        ];
634                        new_dict.insert(key.to_owned(), Object::Array(array));
635                    }
636                    (Object::Reference(old_object_id), Object::Reference(object_id)) => {
637                        let array = vec![
638                            Object::Reference(*old_object_id),
639                            Object::Reference(*object_id),
640                        ];
641                        new_dict.insert(key.to_owned(), Object::Array(array));
642                    }
643                    (Object::Null, _)
644                    | (Object::Boolean(_), _)
645                    | (Object::Name(_), _)
646                    | (Object::Stream(_), _) => {
647                        new_dict.insert(key.to_owned(), old_value);
648                    }
649                    (_, _) => keep_both_objects(&mut new_dict, key, value, old_value),
650                }
651            } else {
652                new_dict.insert(key.to_owned(), value.to_owned());
653            }
654        }
655
656        self.0 = new_dict;
657    }
658
659    /// Return a reference to the inner  [`IndexMap`].
660    pub fn as_hashmap(&self) -> &IndexMap<Vec<u8>, Object> {
661        &self.0
662    }
663
664    /// Return a mut reference to the inner [`IndexMap`].
665    pub fn as_hashmap_mut(&mut self) -> &mut IndexMap<Vec<u8>, Object> {
666        &mut self.0
667    }
668}
669
670#[macro_export]
671macro_rules! dictionary {
672	() => {
673		$crate::Dictionary::new()
674	};
675	($( $key: expr => $value: expr ),+ ,) => {
676		dictionary!( $($key => $value),+ )
677	};
678	($( $key: expr => $value: expr ),*) => {{
679		let mut dict = $crate::Dictionary::new();
680		$(
681			dict.set($key, $value);
682		)*
683		dict
684	}}
685}
686
687impl fmt::Debug for Dictionary {
688    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
689        let entries = self
690            .into_iter()
691            .map(|(key, value)| format!("/{} {:?}", String::from_utf8_lossy(key), value))
692            .collect::<Vec<String>>();
693        write!(f, "<<{}>>", entries.concat())
694    }
695}
696
697impl IntoIterator for Dictionary {
698    type Item = (Vec<u8>, Object);
699    type IntoIter = indexmap::map::IntoIter<Vec<u8>, Object>;
700
701    fn into_iter(self) -> Self::IntoIter {
702        self.0.into_iter()
703    }
704}
705
706impl<'a> IntoIterator for &'a Dictionary {
707    type Item = (&'a Vec<u8>, &'a Object);
708    type IntoIter = indexmap::map::Iter<'a, Vec<u8>, Object>;
709
710    fn into_iter(self) -> Self::IntoIter {
711        self.0.iter()
712    }
713}
714
715impl<'a> IntoIterator for &'a mut Dictionary {
716    type Item = (&'a Vec<u8>, &'a mut Object);
717    type IntoIter = indexmap::map::IterMut<'a, Vec<u8>, Object>;
718
719    fn into_iter(self) -> Self::IntoIter {
720        self.0.iter_mut()
721    }
722}
723
724use std::iter::FromIterator;
725impl<K: Into<Vec<u8>>> FromIterator<(K, Object)> for Dictionary {
726    fn from_iter<I: IntoIterator<Item = (K, Object)>>(iter: I) -> Self {
727        let mut dict = Dictionary::new();
728        for (k, v) in iter {
729            dict.set(k, v);
730        }
731        dict
732    }
733}
734
735impl Stream {
736    pub fn new(mut dict: Dictionary, content: Vec<u8>) -> Stream {
737        dict.set("Length", content.len() as i64);
738        Stream {
739            dict,
740            content,
741            allows_compression: true,
742            start_position: None,
743        }
744    }
745
746    pub fn with_position(dict: Dictionary, position: usize) -> Stream {
747        Stream {
748            dict,
749            content: vec![],
750            allows_compression: true,
751            start_position: Some(position),
752        }
753    }
754
755    /// Default is that the stream may be compressed. On font streams,
756    /// set this to false, otherwise the font will be corrupt
757    #[inline]
758    pub fn with_compression(mut self, allows_compression: bool) -> Stream {
759        self.allows_compression = allows_compression;
760        self
761    }
762
763    pub fn filters(&self) -> Result<Vec<&[u8]>> {
764        let filter = self.dict.get(b"Filter")?;
765
766        if let Ok(name) = filter.as_name() {
767            Ok(vec![name])
768        } else if let Ok(names) = filter.as_array() {
769            names.iter().map(Object::as_name).collect()
770        } else {
771            Err(Error::ObjectType {
772                expected: "Name or Array",
773                found: filter.enum_variant(),
774            })
775        }
776    }
777
778    pub fn set_content(&mut self, content: Vec<u8>) {
779        self.content = content;
780        self.dict.set("Length", self.content.len() as i64);
781    }
782
783    pub fn set_plain_content(&mut self, content: Vec<u8>) {
784        self.dict.remove(b"DecodeParms");
785        self.dict.remove(b"Filter");
786        self.dict.set("Length", content.len() as i64);
787        self.content = content;
788    }
789
790    pub fn get_plain_content(&self) -> Result<Vec<u8>> {
791        match self.filters() {
792            Ok(vec) if !vec.is_empty() => self.decompressed_content(),
793            _ => Ok(self.content.clone()),
794        }
795    }
796
797    pub fn compress(&mut self) -> Result<()> {
798        use flate2::Compression;
799        use flate2::write::ZlibEncoder;
800        use std::io::prelude::*;
801
802        if self.dict.get(b"Filter").is_err() {
803            let mut encoder = ZlibEncoder::new(Vec::new(), Compression::best());
804            encoder.write_all(self.content.as_slice())?;
805            let compressed = encoder.finish()?;
806            if compressed.len() + 19 < self.content.len() {
807                self.dict.set("Filter", "FlateDecode");
808                self.set_content(compressed);
809            }
810        }
811        Ok(())
812    }
813
814    pub fn decompressed_content(&self) -> Result<Vec<u8>> {
815        let params = self.dict.get(b"DecodeParms").and_then(Object::as_dict).ok();
816        let filters = match self.filters() {
817            Ok(f) => f,
818            // No /Filter key means the stream is uncompressed
819            Err(_) => return Ok(self.content.clone()),
820        };
821
822        let mut input = self.content.as_slice();
823        let mut output = vec![];
824
825        // Filters are in decoding order.
826        for filter in filters {
827            output = match filter {
828                b"FlateDecode" => Self::decompress_zlib(input, params)?,
829                b"LZWDecode" => Self::decompress_lzw(input, params)?,
830                b"ASCII85Decode" => Self::decode_ascii85(input)?,
831                _ => return Err(Error::Unimplemented("decompression algorithms")),
832            };
833            input = &output;
834        }
835        Ok(output)
836    }
837
838    fn decompress_lzw(input: &[u8], params: Option<&Dictionary>) -> Result<Vec<u8>> {
839        use weezl::{BitOrder, decode::Decoder};
840        const MIN_BITS: u8 = 9;
841
842        let early_change = params
843            .and_then(|p| p.get(b"EarlyChange").ok())
844            .and_then(|p| Object::as_i64(p).ok())
845            .map(|v| v != 0)
846            .unwrap_or(true);
847
848        let mut decoder = if early_change {
849            Decoder::with_tiff_size_switch(BitOrder::Msb, MIN_BITS - 1)
850        } else {
851            Decoder::new(BitOrder::Msb, MIN_BITS - 1)
852        };
853
854        let output = Self::decompress_lzw_loop(input, &mut decoder);
855        Self::decompress_predictor(output, params)
856    }
857
858    fn decompress_lzw_loop(input: &[u8], decoder: &mut weezl::decode::Decoder) -> Vec<u8> {
859        let mut output = vec![];
860
861        let result = decoder.into_stream(&mut output).decode_all(input);
862        if let Err(err) = result.status {
863            warn!("{err}");
864        }
865
866        output
867    }
868
869    fn decompress_zlib(input: &[u8], params: Option<&Dictionary>) -> Result<Vec<u8>> {
870        use flate2::read::ZlibDecoder;
871        use std::io::prelude::*;
872
873        let mut output = Vec::with_capacity(input.len() * 2);
874
875        if !input.is_empty() {
876            let mut decoder = ZlibDecoder::new(input);
877            if let Err(err) = decoder.read_to_end(&mut output) {
878                warn!("{err}");
879                // Zlib decompression failed (e.g. corrupt adler32 checksum in
880                // encrypted PDFs). Retry with raw deflate, skipping the 2-byte
881                // zlib header and ignoring the checksum.
882                if output.is_empty() && input.len() > 2 {
883                    use flate2::read::DeflateDecoder;
884                    let mut raw_decoder = DeflateDecoder::new(&input[2..]);
885                    if let Err(raw_err) = raw_decoder.read_to_end(&mut output) {
886                        warn!("raw deflate fallback also failed: {raw_err}");
887                    }
888                }
889            }
890        }
891        Self::decompress_predictor(output, params)
892    }
893
894    fn decode_ascii85(input: &[u8]) -> Result<Vec<u8>> {
895        let mut output = vec![];
896        let mut buffer: u32 = 0;
897        let mut count = 0;
898        // Check for EOD marker
899        let input_no_eod = if input.len() >= 2 && &input[input.len() - 2..] == b"~>" {
900            &input[..input.len() - 2]
901        } else {
902            log::warn!("ASCII85 stream is missing its EOD marker");
903            input
904        };
905        for &ch in input_no_eod {
906            if ch == b'z' {
907                if count != 0 {
908                    return Err(DecompressError::Ascii85(
909                        "z character is not allowed in the middle of a group",
910                    )
911                    .into());
912                }
913                output.extend_from_slice(&[0, 0, 0, 0]);
914                continue;
915            }
916
917            if ch.is_ascii_whitespace() {
918                continue;
919            }
920
921            if !(b'!'..=b'u').contains(&ch) {
922                break;
923            }
924            buffer = buffer
925                .checked_mul(85)
926                .ok_or(DecompressError::Ascii85("multiplication overflow"))?;
927            buffer += (ch - b'!') as u32;
928            count += 1;
929
930            if count == 5 {
931                output.extend_from_slice(&buffer.to_be_bytes());
932                buffer = 0;
933                count = 0;
934            }
935        }
936
937        if count > 0 {
938            for _ in count..5 {
939                buffer = buffer
940                    .checked_mul(85)
941                    .ok_or(DecompressError::Ascii85("multiplication overflow"))?;
942                buffer += 84;
943            }
944
945            let bytes = buffer.to_be_bytes();
946            output.extend_from_slice(&bytes[..count - 1]);
947        }
948
949        Ok(output)
950    }
951
952    fn decompress_predictor(mut data: Vec<u8>, params: Option<&Dictionary>) -> Result<Vec<u8>> {
953        use crate::filters::png;
954
955        if let Some(params) = params {
956            let predictor = params
957                .get(b"Predictor")
958                .and_then(Object::as_i64)
959                .unwrap_or(1);
960            if (10..=15).contains(&predictor) {
961                let pixels_per_row = max(
962                    1,
963                    params.get(b"Columns").and_then(Object::as_i64).unwrap_or(1),
964                ) as usize;
965                let colors = max(
966                    1,
967                    params.get(b"Colors").and_then(Object::as_i64).unwrap_or(1),
968                ) as usize;
969                let bits = max(
970                    8,
971                    params
972                        .get(b"BitsPerComponent")
973                        .and_then(Object::as_i64)
974                        .unwrap_or(8),
975                ) as usize;
976                let bytes_per_pixel = colors * bits / 8;
977                data = png::decode_frame(data.as_slice(), bytes_per_pixel, pixels_per_row)?;
978            }
979            Ok(data)
980        } else {
981            Ok(data)
982        }
983    }
984
985    pub fn decompress(&mut self) -> Result<()> {
986        let data = self.decompressed_content()?;
987        self.dict.remove(b"DecodeParms");
988        self.dict.remove(b"Filter");
989        self.set_content(data);
990        Ok(())
991    }
992
993    pub fn is_compressed(&self) -> bool {
994        self.dict.get(b"Filter").is_ok()
995    }
996}
997
998#[cfg(test)]
999mod test {
1000    use crate::{Error, lopdf_error::DecompressError};
1001
1002    use super::Stream;
1003
1004    #[test]
1005    fn test_decode_ascii85() {
1006        let input = r#"9jqo^BlbD-BleB1DJ+*+F(f,q/0JhKF<GL>Cj@.4Gp$d7F!,L7@<6@)/0JDEF<G%<+EV:2F!,O<
1007            DJ+*.@<*K0@<6L(Df-\0Ec5e;DffZ(EZee.Bl.9pF"AGXBPCsi+DGm>@3BB/F*&OCAfu2/AKYi(
1008            DIb:@FD,*)+C]U=@3BN#EcYf8ATD3s@q?d$AftVqCh[NqF<G:8+EV:.+Cf>-FD5W8ARlolDIal(
1009            DId<j@<?3r@:F%a+D58'ATD4$Bl@l3De:,-DJs`8ARoFb/0JMK@qB4^F!,R<AKZ&-DfTqBG%G>u
1010            D.RTpAKYo'+CT/5+Cei#DII?(E,9)oF*2M7/c~>"#;
1011        let expected = "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.";
1012        let output = Stream::decode_ascii85(input.as_bytes()).unwrap();
1013        println!("{}", String::from_utf8(output.clone()).unwrap());
1014        assert_eq!(&output, expected.as_bytes());
1015    }
1016
1017    #[test]
1018    fn test_decode_ascii85_overflow() {
1019        let input = b"uuuuu~>";
1020        let output = Stream::decode_ascii85(input);
1021        // let expected: Result<Vec<u8>, Error> = Err(Error::ContentDecode);
1022        assert!(matches!(
1023            output,
1024            Err(Error::Decompress(DecompressError::Ascii85(_)))
1025        ));
1026    }
1027
1028    #[test]
1029    fn test_decompress_zlib_corrupt_checksum() {
1030        use flate2::Compression;
1031        use flate2::write::ZlibEncoder;
1032        use std::io::Write;
1033
1034        let original = b"BT /F1 12 Tf (Hello World) Tj ET";
1035
1036        // Compress with valid zlib
1037        let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
1038        encoder.write_all(original).unwrap();
1039        let mut compressed = encoder.finish().unwrap();
1040
1041        // Corrupt the adler32 checksum (last 4 bytes)
1042        let len = compressed.len();
1043        assert!(len >= 4);
1044        for byte in &mut compressed[len - 4..] {
1045            *byte ^= 0xFF;
1046        }
1047
1048        // Normal zlib should fail, but our fallback should recover
1049        let result = Stream::decompress_zlib(&compressed, None).unwrap();
1050        assert_eq!(result, original);
1051    }
1052
1053    #[test]
1054    fn test_uncompressed_stream_returns_raw_content() {
1055        use crate::Dictionary;
1056
1057        // A stream with no /Filter should return its raw content from decompressed_content()
1058        let content = b"/FullPage Do
1059"
1060        .to_vec();
1061        let mut dict = Dictionary::new();
1062        dict.set("Length", content.len() as i64);
1063        let stream = Stream::new(dict, content.clone());
1064
1065        let result = stream
1066            .decompressed_content()
1067            .expect("should succeed for uncompressed stream");
1068        assert_eq!(result, content);
1069    }
1070}