oxidize_pdf/objects/
stream.rs

1#[cfg(feature = "compression")]
2use crate::error::{PdfError, Result};
3use crate::objects::Dictionary;
4
5#[derive(Debug, Clone)]
6pub struct Stream {
7    dictionary: Dictionary,
8    data: Vec<u8>,
9}
10
11impl Stream {
12    pub fn new(data: Vec<u8>) -> Self {
13        let mut dictionary = Dictionary::new();
14        dictionary.set("Length", data.len() as i64);
15
16        Self { dictionary, data }
17    }
18
19    pub fn with_dictionary(dictionary: Dictionary, data: Vec<u8>) -> Self {
20        let mut dict = dictionary;
21        dict.set("Length", data.len() as i64);
22
23        Self {
24            dictionary: dict,
25            data,
26        }
27    }
28
29    pub fn dictionary(&self) -> &Dictionary {
30        &self.dictionary
31    }
32
33    pub fn dictionary_mut(&mut self) -> &mut Dictionary {
34        &mut self.dictionary
35    }
36
37    pub fn data(&self) -> &[u8] {
38        &self.data
39    }
40
41    pub fn data_mut(&mut self) -> &mut Vec<u8> {
42        &mut self.data
43    }
44
45    pub fn set_filter(&mut self, filter: &str) {
46        self.dictionary
47            .set("Filter", crate::objects::Object::Name(filter.to_string()));
48    }
49
50    pub fn set_decode_params(&mut self, params: Dictionary) {
51        self.dictionary.set("DecodeParms", params);
52    }
53
54    #[cfg(feature = "compression")]
55    pub fn compress_flate(&mut self) -> Result<()> {
56        use flate2::write::ZlibEncoder;
57        use flate2::Compression;
58        use std::io::Write;
59
60        let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
61        encoder
62            .write_all(&self.data)
63            .map_err(|e| PdfError::CompressionError(e.to_string()))?;
64        let compressed = encoder
65            .finish()
66            .map_err(|e| PdfError::CompressionError(e.to_string()))?;
67
68        self.data = compressed;
69        self.dictionary.set("Length", self.data.len() as i64);
70        self.set_filter("FlateDecode");
71
72        Ok(())
73    }
74}