Skip to main content

pdf/edit/
mod.rs

1// pdf::edit -- changing a document that pdf::read opened, saved as an incremental update (ISO
2// 32000-1, 7.5.6): the bytes of the file stay as they are, the objects that change and the new
3// ones follow with a cross-reference section and a trailer of their own.  Or written again in
4// full (full.rs: save_full, with its encryption, decrypted, or encrypted anew).  An incremental
5// update (save) keeps the bytes a signature covers as they are, so it still verifies over them
6// (whether a certification's DocMDP permissions allow the change is the verifier's judgement:
7// /P 1 allows none), and an encrypted file stays encrypted with its key; save_full writes new
8// bytes, so signatures break (it asks for Full::break_signatures) and the encryption is what
9// Full::security says.
10//
11//   let doc = read::Document::open(bytes)?;
12//   let mut up = edit::Update::new(&doc);
13//   up.set_field("person.name", FieldValue::Text("Jakob"))?;   // form.rs: fill in a form
14//   up.flatten(None)?;                                        // the fields into the pages
15//   let r = up.add(Object::Dict(d))?;                         // any object -> its Ref
16//   up.set(page_ref, Object::Dict(changed))?;                 // replace one
17//   let s = up.add_stream(dict, &data)?;                      // FlateDecode
18//   let out: Vec<u8> = up.save()?;                            // the file and the update
19//   let all: Vec<u8> = up.save_full(&Full::default())?;       // or a new file of it all
20//
21// set_field and flatten change all they would or, when they fail, nothing.
22//
23//   Update       new, document, get / resolve (as the update will have it), add / add_stream /
24//                add_stream_raw / set / set_stream / delete, save; set_field / flatten /
25//                set_fonts / set_lang (form.rs); save_full (full.rs)
26//   FieldValue   Text, Check, Choice
27//   Full         security (Security::Keep / None / Encrypt(&Encryption)), break_signatures
28//
29// The section: a cross-reference stream when the newest section of the file is one, else a
30// table; /Prev is that section.  A file that was repaired (its cross-reference rebuilt from its
31// objects) gets a section that lists every object, and no /Prev: it is whole again (a stream
32// when objects lie in object streams).  The trailer keeps /Root, /Info and /Encrypt; /ID keeps
33// its first string, the second is a hash of what was added (the same update gives the same
34// bytes).  In an encrypted file the strings and streams of what is written are encrypted with
35// the document's key (crypt.rs: RC4, AES-128, AES-256); cross-reference streams, a signature's
36// /Contents and metadata a file keeps clear (EncryptMetadata false) are not.
37//
38// An existing stream is written again only as set_stream / set gives it: its data as it is in
39// the file when it stays the same object (its key is its number), else decrypted first.
40
41mod form;
42mod full;
43pub(crate) mod ser;
44
45pub use form::FieldValue;
46pub use full::{Full, Security};
47pub(crate) use form::{widget_ap, CodeCache};
48
49use crate::font::FontData;
50use crate::read::xref::Entry;
51use crate::read::{crypt, Dict, Document, Error, Object, Ref, Stream};
52use alloc::collections::BTreeMap;
53use alloc::rc::Rc;
54use alloc::string::String;
55use alloc::vec::Vec;
56use compress::zlib;
57use core::fmt::Write as _;
58
59/// the largest object number (ISO 32000-1, Annex C)
60const MAX_NUM: u32 = 8_388_607;
61
62#[derive(Clone)]
63enum Item {
64    Obj(Object),
65    /// a stream: its dictionary (without /Length) and its data, encoded by the dictionary's
66    /// filters, not yet encrypted
67    Stream(Dict, Vec<u8>),
68    /// an existing stream of this same object: its dictionary and its bytes as the file has
69    /// them (encrypted with this object's key, if at all)
70    Raw(Dict, usize, usize),
71    Free,
72}
73
74/// what a transaction found before it changed anything: the next number then, each existing
75/// object it changed as it was, and the state of the form's work
76struct Journal {
77    next: u32,
78    saved: BTreeMap<u32, Option<(u16, Item)>>,
79    fonts: usize,
80    filled: bool,
81}
82
83/// the changes to one document, written by save() as an incremental update
84pub struct Update<'a> {
85    doc: &'a Document,
86    objs: BTreeMap<u32, (u16, Item)>,
87    next: u32,
88    pub(crate) fonts: Option<Rc<dyn crate::read::FontSource>>,
89    pub(crate) lang: Option<String>,
90    /// a field was set: the AcroForm loses /XFA
91    pub(crate) filled: bool,
92    /// the fonts of the FontSource appearances use, each with its key and the five objects it
93    /// becomes (Type0, CIDFont, FontDescriptor, program, ToUnicode); written by save()
94    pub(crate) fallback_fonts: Vec<FontData>,
95    pub(crate) fallback_meta: Vec<(String, [Ref; 5])>,
96    /// the transactions under way (set_field, flatten): all or nothing
97    journals: Vec<Journal>,
98}
99
100impl<'a> Update<'a> {
101    /// no changes yet
102    pub fn new(doc: &'a Document) -> Update<'a> {
103        // object numbers past MAX_NUM (a scan takes any header) give no room: take() says so
104        let last = doc.xref_entries().keys().next_back().map_or(0, |&n| n.saturating_add(1));
105        let size = doc.trailer().int("Size").and_then(|s| u32::try_from(s).ok()).unwrap_or(0).min(MAX_NUM + 1);
106        let last = last.min(MAX_NUM + 1);
107        Update { doc, objs: BTreeMap::new(), next: last.max(size).max(1), fonts: None, lang: None, filled: false, fallback_fonts: Vec::new(), fallback_meta: Vec::new(), journals: Vec::new() }
108    }
109
110    /// the document the update changes
111    pub fn document(&self) -> &'a Document {
112        self.doc
113    }
114
115    /// an object as the update will have it: changed, added, or as in the file (Null when
116    /// deleted or missing; a stream added here gives its dictionary)
117    pub fn get(&self, r: Ref) -> Object {
118        match self.objs.get(&r.num) {
119            Some((g, item)) if *g == r.generation => match item {
120                Item::Obj(o) => o.clone(),
121                Item::Stream(d, _) | Item::Raw(d, _, _) => Object::Dict(d.clone()),
122                Item::Free => Object::Null,
123            },
124            Some(_) => Object::Null,
125            None => self.doc.get(r),
126        }
127    }
128
129    /// follow references until an object that is none (Null after too many)
130    pub fn resolve(&self, o: &Object) -> Object {
131        let mut cur = o.clone();
132        for _ in 0..32 {
133            match cur {
134                Object::Ref(r) => cur = self.get(r),
135                _ => return cur,
136            }
137        }
138        Object::Null
139    }
140
141    /// a dictionary (a stream's), resolved; empty when it is none
142    pub(crate) fn dict(&self, o: &Object) -> Dict {
143        match self.resolve(o) {
144            Object::Dict(d) => d,
145            Object::Stream(s) => s.dict,
146            _ => Dict::new(),
147        }
148    }
149
150    fn take(&mut self) -> Result<Ref, Error> {
151        if self.next > MAX_NUM {
152            return Err(Error::Limit("more objects than a PDF file can number"));
153        }
154        let r = Ref { num: self.next, generation: 0 };
155        self.next += 1;
156        Ok(r)
157    }
158
159    /// an object about to change: each transaction under way keeps it as it was first
160    fn note(&mut self, num: u32) {
161        for j in &mut self.journals {
162            if num < j.next && !j.saved.contains_key(&num) {
163                j.saved.insert(num, self.objs.get(&num).cloned());
164            }
165        }
166    }
167
168    /// `f`'s changes, all of them or (when it fails) none: the objects it added are gone, those
169    /// it changed are as they were
170    pub(crate) fn transaction<T>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, Error>) -> Result<T, Error> {
171        self.journals.push(Journal { next: self.next, saved: BTreeMap::new(), fonts: self.fallback_fonts.len(), filled: self.filled });
172        let r = f(self);
173        let Some(j) = self.journals.pop() else { return r };
174        if r.is_err() {
175            let added: Vec<u32> = self.objs.range(j.next..).map(|(&n, _)| n).collect();
176            for n in added {
177                self.objs.remove(&n);
178            }
179            for (n, before) in j.saved {
180                match before {
181                    Some(b) => {
182                        self.objs.insert(n, b);
183                    }
184                    None => {
185                        self.objs.remove(&n);
186                    }
187                }
188            }
189            self.next = j.next;
190            self.fallback_fonts.truncate(j.fonts);
191            self.fallback_meta.truncate(j.fonts);
192            self.filled = j.filled;
193        }
194        r
195    }
196
197    /// a new object (not a stream: add_stream), and its reference
198    pub fn add(&mut self, o: Object) -> Result<Ref, Error> {
199        let r = self.take()?;
200        self.set(r, o)?;
201        Ok(r)
202    }
203
204    /// a new stream of `data`, compressed with FlateDecode (dict: its other keys)
205    pub fn add_stream(&mut self, dict: Dict, data: &[u8]) -> Result<Ref, Error> {
206        let r = self.take()?;
207        self.set_stream(r, dict, data)?;
208        Ok(r)
209    }
210
211    /// a new stream whose data is encoded already as the filters of `dict` say
212    pub fn add_stream_raw(&mut self, dict: Dict, encoded: Vec<u8>) -> Result<Ref, Error> {
213        let r = self.take()?;
214        let mut dict = dict;
215        dict.remove("Length");
216        self.note(r.num);
217        self.objs.insert(r.num, (r.generation, Item::Stream(dict, encoded)));
218        Ok(r)
219    }
220
221    /// object r becomes `o`.  A stream from the document keeps its data (decrypted first when
222    /// it was another object's)
223    pub fn set(&mut self, r: Ref, o: Object) -> Result<(), Error> {
224        if r.num == 0 || r.num > MAX_NUM {
225            return Err(Error::Invalid("an object number outside 1 to 8388607"));
226        }
227        if self.doc.encrypt_ref() == Some(r) {
228            return Err(Error::Invalid("the encryption dictionary"));
229        }
230        let item = match o {
231            Object::Stream(s) => self.stream_item(r, *s)?,
232            o => {
233                // an object that holds itself or a stream is not written
234                let mut probe = Vec::new();
235                ser::object(&mut probe, &o)?;
236                Item::Obj(o)
237            }
238        };
239        if r.num >= self.next {
240            self.next = r.num + 1;
241        }
242        self.note(r.num);
243        self.objs.insert(r.num, (r.generation, item));
244        Ok(())
245    }
246
247    fn stream_item(&self, r: Ref, s: Stream) -> Result<Item, Error> {
248        let mut dict = s.dict.clone();
249        dict.remove("Length");
250        let data = self.doc.data();
251        if s.end > data.len() || s.start > s.end {
252            return Err(Error::Damaged("a stream outside the file"));
253        }
254        if s.owner == Some(r) || !self.doc.is_encrypted() {
255            return Ok(Item::Raw(dict, s.start, s.end));
256        }
257        if dict.get("Filter").is_some_and(|f| f.as_name() == Some(b"Crypt") || f.as_array().is_some_and(|a| a.first().and_then(Object::as_name) == Some(b"Crypt"))) {
258            return Err(Error::Unsupported("moving a stream with a /Crypt filter"));
259        }
260        let plain = match (self.doc.crypt(), s.owner) {
261            (Some(c), Some(o)) if !exempt(c, &dict) => c.stream(o, &data[s.start..s.end], None, dict.is("Type", "EmbeddedFile")),
262            _ => data[s.start..s.end].to_vec(),
263        };
264        Ok(Item::Stream(dict, plain))
265    }
266
267    /// stream r becomes `data`, compressed with FlateDecode (dict: its other keys)
268    pub fn set_stream(&mut self, r: Ref, dict: Dict, data: &[u8]) -> Result<(), Error> {
269        if r.num == 0 || r.num > MAX_NUM {
270            return Err(Error::Invalid("an object number outside 1 to 8388607"));
271        }
272        if self.doc.encrypt_ref() == Some(r) {
273            return Err(Error::Invalid("the encryption dictionary"));
274        }
275        let mut dict = dict;
276        dict.remove("Length");
277        dict.remove("DecodeParms");
278        dict.insert("Filter", Object::name("FlateDecode"));
279        let z = zlib::compress(data, 6);
280        if r.num >= self.next {
281            self.next = r.num + 1;
282        }
283        self.note(r.num);
284        self.objs.insert(r.num, (r.generation, Item::Stream(dict, z)));
285        Ok(())
286    }
287
288    /// object r is gone (a free entry with the next generation)
289    pub fn delete(&mut self, r: Ref) {
290        if r.num != 0 && r.num <= MAX_NUM && self.doc.encrypt_ref() != Some(r) {
291            self.note(r.num);
292            self.objs.insert(r.num, (r.generation, Item::Free));
293        }
294    }
295
296    /// nothing changed
297    pub fn is_empty(&self) -> bool {
298        self.objs.is_empty()
299    }
300
301    /// object r is a stream (one of the file's, or one this update adds)
302    pub(crate) fn is_stream(&self, r: Ref) -> bool {
303        match self.objs.get(&r.num) {
304            Some((g, item)) if *g == r.generation => matches!(item, Item::Stream(..) | Item::Raw(..)),
305            Some(_) => false,
306            None => matches!(self.doc.get(r), Object::Stream(_)),
307        }
308    }
309
310    /// the objects of the fallback fonts, subset to the glyphs their appearances drew
311    fn font_items(&self) -> Result<Vec<(Ref, Item)>, Error> {
312        let mut out = Vec::new();
313        for (fd, (_, refs)) in self.fallback_fonts.iter().zip(&self.fallback_meta) {
314            let base = Object::Name(crate::read::Name(fd.base_font()));
315            let mut t0 = Dict::new();
316            t0.insert("Type", Object::name("Font"));
317            t0.insert("Subtype", Object::name("Type0"));
318            t0.insert("BaseFont", base.clone());
319            t0.insert("Encoding", Object::name("Identity-H"));
320            t0.insert("DescendantFonts", Object::Array(alloc::vec![Object::Ref(refs[1])]));
321            t0.insert("ToUnicode", Object::Ref(refs[4]));
322            out.push((refs[0], Item::Obj(Object::Dict(t0))));
323            let mut cid = Dict::new();
324            cid.insert("Type", Object::name("Font"));
325            cid.insert("Subtype", Object::name(if fd.cff { "CIDFontType0" } else { "CIDFontType2" }));
326            cid.insert("BaseFont", base);
327            let mut info = Dict::new();
328            info.insert("Registry", Object::String(b"Adobe".to_vec()));
329            info.insert("Ordering", Object::String(b"Identity".to_vec()));
330            info.insert("Supplement", Object::Int(0));
331            cid.insert("CIDSystemInfo", Object::Dict(info));
332            cid.insert("FontDescriptor", Object::Ref(refs[2]));
333            cid.insert("W", parse(&fd.widths())?);
334            if !fd.cff {
335                cid.insert("CIDToGIDMap", Object::name("Identity"));
336            }
337            out.push((refs[1], Item::Obj(Object::Dict(cid))));
338            let mut desc = b"<<".to_vec();
339            fd.descriptor(&mut desc);
340            desc.extend_from_slice(b">>");
341            let Object::Dict(mut desc) = parse(&desc)? else { return Err(Error::Invalid("a font descriptor")) };
342            desc.insert(if fd.cff { "FontFile3" } else { "FontFile2" }, Object::Ref(refs[3]));
343            out.push((refs[2], Item::Obj(Object::Dict(desc))));
344            let prog = fd.program().map_err(|_| Error::Invalid("a fallback font that cannot be embedded"))?;
345            let mut pd = Dict::new();
346            if fd.cff {
347                pd.insert("Subtype", Object::name("CIDFontType0C"));
348            } else {
349                pd.insert("Length1", Object::Int(prog.len() as i64));
350            }
351            pd.insert("Filter", Object::name("FlateDecode"));
352            out.push((refs[3], Item::Stream(pd, zlib::compress(&prog, 6))));
353            let mut td = Dict::new();
354            td.insert("Filter", Object::name("FlateDecode"));
355            out.push((refs[4], Item::Stream(td, zlib::compress(&fd.to_unicode(), 6))));
356        }
357        Ok(out)
358    }
359
360    /// the file with the update after it (the file as it was when nothing changed)
361    pub fn save(&self) -> Result<Vec<u8>, Error> {
362        let doc = self.doc;
363        let mut out = doc.data().to_vec();
364        if self.objs.is_empty() {
365            return Ok(out);
366        }
367        let base = out.len();
368        if !matches!(out.last(), Some(b'\n' | b'\r')) {
369            out.push(b'\n');
370        }
371        let crypt = doc.crypt();
372        // (offset or None for free, generation)
373        let mut written: BTreeMap<u32, (Option<usize>, u16)> = BTreeMap::new();
374        let fonts = self.font_items()?;
375        let mut items: BTreeMap<u32, (u16, &Item)> = self.objs.iter().map(|(&n, (g, it))| (n, (*g, it))).collect();
376        for (r, it) in &fonts {
377            items.insert(r.num, (r.generation, it));
378        }
379        for (&num, &(generation, item)) in &items {
380            let generation = &generation;
381            let r = Ref { num, generation: *generation };
382            match item {
383                Item::Free => {
384                    written.insert(num, (None, generation.saturating_add(1)));
385                    continue;
386                }
387                Item::Obj(o) => {
388                    written.insert(num, (Some(out.len()), *generation));
389                    let _ = write!(crate::obj::Fmt(&mut out), "{num} {generation} obj\n");
390                    let mut o = o.clone();
391                    if let Some(c) = crypt {
392                        c.seal_strings(r, &mut o);
393                    }
394                    ser::object(&mut out, &o)?;
395                }
396                Item::Stream(d, data) => {
397                    written.insert(num, (Some(out.len()), *generation));
398                    let mut dict = Object::Dict(d.clone());
399                    let sealed;
400                    let body: &[u8] = match crypt {
401                        Some(c) => {
402                            c.seal_strings(r, &mut dict);
403                            if exempt(c, d) {
404                                data
405                            } else {
406                                sealed = c.seal_stream(r, data, d.is("Type", "EmbeddedFile"));
407                                &sealed
408                            }
409                        }
410                        None => data,
411                    };
412                    stream_obj(&mut out, r, &dict, body)?;
413                }
414                Item::Raw(d, start, end) => {
415                    written.insert(num, (Some(out.len()), *generation));
416                    let mut dict = Object::Dict(d.clone());
417                    if let Some(c) = crypt {
418                        c.seal_strings(r, &mut dict);
419                    }
420                    let raw = doc.data()[*start..*end].to_vec();
421                    stream_obj(&mut out, r, &dict, &raw)?;
422                }
423            }
424            out.extend_from_slice(b"\nendobj\n");
425        }
426        self.xref(&mut out, base, written)?;
427        Ok(out)
428    }
429
430    /// the cross-reference section and trailer after the objects
431    fn xref(&self, out: &mut Vec<u8>, base: usize, written: BTreeMap<u32, (Option<usize>, u16)>) -> Result<(), Error> {
432        let doc = self.doc;
433        let start = doc.xref_start();
434        // what the section lists: the objects written, and for a repaired file all the others
435        #[derive(Clone, Copy)]
436        enum E {
437            At(usize, u16),
438            InStream(u32, u32),
439            Free(u16),
440        }
441        let mut list: BTreeMap<u32, E> = BTreeMap::new();
442        if start.is_none() {
443            for (&n, &(e, g)) in doc.xref_entries() {
444                match e {
445                    Entry::At(o) => list.insert(n, E::At(o, g)),
446                    Entry::InStream(s, i) => list.insert(n, E::InStream(s, i)),
447                    Entry::Free => None,
448                };
449            }
450        }
451        for (n, (o, g)) in written {
452            list.insert(n, match o {
453                Some(o) => E::At(o, g),
454                None => E::Free(g),
455            });
456        }
457        let in_streams = list.values().any(|e| matches!(e, E::InStream(..)));
458        let as_stream = start.map(|s| s.1).unwrap_or(false) || in_streams;
459        let mut size = self.next.max(list.keys().next_back().map_or(1, |&n| n + 1));
460        let xref_num = size;
461        if as_stream {
462            size += 1;
463        }
464        // the trailer's keys
465        let t = doc.trailer();
466        let mut tr = Dict::new();
467        tr.insert("Size", Object::Int(size as i64));
468        if let Some((off, _)) = start {
469            tr.insert("Prev", Object::Int(off as i64));
470        }
471        for k in ["Root", "Info", "Encrypt"] {
472            if let Some(v) = t.get(k) {
473                tr.insert(k, v.clone());
474            }
475        }
476        let first = match t.get("ID") {
477            Some(Object::Array(a)) => a.first().and_then(Object::as_bytes).map(<[u8]>::to_vec),
478            _ => None,
479        };
480        let new_id = crypto::md5(&out[base..]).to_vec();
481        tr.insert("ID", Object::Array(alloc::vec![Object::String(first.unwrap_or_else(|| new_id.clone())), Object::String(new_id)]));
482        let at = out.len();
483        if as_stream {
484            list.insert(xref_num, E::At(at, 0));
485            let wide = list.values().map(|e| match *e {
486                E::At(o, _) => o as u64,
487                E::InStream(s, _) => s as u64,
488                E::Free(_) => 0,
489            });
490            let max = wide.max().unwrap_or(0);
491            let w1 = if max < 1 << 32 { 4 } else { 8 };
492            let w2 = 2usize;
493            let mut rows = Vec::new();
494            let mut index = Vec::new();
495            let mut run: Option<(u32, u32)> = None;
496            for (&n, e) in &list {
497                match run {
498                    Some((s, c)) if s + c == n => run = Some((s, c + 1)),
499                    Some((s, c)) => {
500                        index.push(Object::Int(s as i64));
501                        index.push(Object::Int(c as i64));
502                        run = Some((n, 1));
503                    }
504                    None => run = Some((n, 1)),
505                }
506                let (kind, f2, f3) = match *e {
507                    E::At(o, g) => (1u8, o as u64, g as u64),
508                    E::InStream(s, i) => (2, s as u64, i as u64),
509                    E::Free(g) => (0, 0, g as u64),
510                };
511                if f3 > 0xFFFF {
512                    return Err(Error::Limit("an object stream of more than 65535 objects"));
513                }
514                rows.push(kind);
515                rows.extend_from_slice(&f2.to_be_bytes()[8 - w1..]);
516                rows.extend_from_slice(&f3.to_be_bytes()[8 - w2..]);
517            }
518            if let Some((s, c)) = run {
519                index.push(Object::Int(s as i64));
520                index.push(Object::Int(c as i64));
521            }
522            tr.insert("Type", Object::name("XRef"));
523            tr.insert("W", Object::Array(alloc::vec![Object::Int(1), Object::Int(w1 as i64), Object::Int(w2 as i64)]));
524            tr.insert("Index", Object::Array(index));
525            tr.insert("Filter", Object::name("FlateDecode"));
526            let z = zlib::compress(&rows, 6);
527            stream_obj(out, Ref { num: xref_num, generation: 0 }, &Object::Dict(tr), &z)?;
528            out.extend_from_slice(b"\nendobj\n");
529        } else {
530            out.extend_from_slice(b"xref\n");
531            let nums: Vec<u32> = list.keys().copied().collect();
532            let mut i = 0;
533            // a full table begins with object 0, the head of the free list
534            if start.is_none() {
535                out.extend_from_slice(b"0 1\n0000000000 65535 f\r\n");
536            }
537            while i < nums.len() {
538                let mut j = i + 1;
539                while j < nums.len() && nums[j] == nums[j - 1] + 1 {
540                    j += 1;
541                }
542                let _ = write!(crate::obj::Fmt(out), "{} {}\n", nums[i], j - i);
543                for n in &nums[i..j] {
544                    let _ = match list[n] {
545                        E::At(o, g) => write!(crate::obj::Fmt(out), "{o:010} {g:05} n\r\n"),
546                        E::Free(g) => write!(crate::obj::Fmt(out), "0000000000 {g:05} f\r\n"),
547                        E::InStream(..) => Ok(()),
548                    };
549                }
550                i = j;
551            }
552            out.extend_from_slice(b"trailer\n");
553            ser::object(out, &Object::Dict(tr))?;
554            out.push(b'\n');
555        }
556        let _ = write!(crate::obj::Fmt(out), "startxref\n{at}\n%%EOF\n");
557        Ok(())
558    }
559}
560
561/// an object from its bytes
562fn parse(b: &[u8]) -> Result<Object, Error> {
563    crate::read::lex::Lexer::new(b, 0).object(false).map_err(|_| Error::Invalid("an object the writer made"))
564}
565
566/// a stream the file keeps unencrypted: cross-reference streams, metadata when EncryptMetadata
567/// is false, an Identity crypt filter
568fn exempt(c: &crypt::Crypt, d: &Dict) -> bool {
569    let identity = match d.get("Filter") {
570        Some(Object::Name(n)) => n.0 == b"Crypt",
571        Some(Object::Array(a)) => a.first().and_then(Object::as_name) == Some(b"Crypt"),
572        _ => false,
573    };
574    d.is("Type", "XRef") || (!c.encrypt_metadata && d.is("Type", "Metadata")) || identity
575}
576
577/// `num gen obj << dict /Length n >> stream ... endstream` (without endobj)
578fn stream_obj(out: &mut Vec<u8>, r: Ref, dict: &Object, data: &[u8]) -> Result<(), Error> {
579    let _ = write!(crate::obj::Fmt(out), "{} {} obj\n", r.num, r.generation);
580    let Object::Dict(d) = dict else { return Err(Error::Invalid("a stream without a dictionary")) };
581    let mut d = d.clone();
582    d.insert("Length", Object::Int(data.len() as i64));
583    ser::object(out, &Object::Dict(d))?;
584    out.extend_from_slice(b"\nstream\n");
585    out.extend_from_slice(data);
586    out.extend_from_slice(b"\nendstream");
587    Ok(())
588}