oxidize_pdf/objects/
stream.rs1use crate::objects::Dictionary;
2#[cfg(feature = "compression")]
3use crate::error::{PdfError, Result};
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.set("Filter", format!("/{}", filter));
47 }
48
49 pub fn set_decode_params(&mut self, params: Dictionary) {
50 self.dictionary.set("DecodeParms", params);
51 }
52
53 #[cfg(feature = "compression")]
54 pub fn compress_flate(&mut self) -> Result<()> {
55 use flate2::write::ZlibEncoder;
56 use flate2::Compression;
57 use std::io::Write;
58
59 let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
60 encoder.write_all(&self.data)
61 .map_err(|e| PdfError::CompressionError(e.to_string()))?;
62 let compressed = encoder.finish()
63 .map_err(|e| PdfError::CompressionError(e.to_string()))?;
64
65 self.data = compressed;
66 self.dictionary.set("Length", self.data.len() as i64);
67 self.set_filter("FlateDecode");
68
69 Ok(())
70 }
71}