Skip to main content

pdfboss_write/
update.rs

1//! Incremental updates to an existing file (ISO 32000-1 §7.5.6): the base
2//! bytes stay in place and an update section appends new and replaced
3//! objects plus a cross-reference section chained to the base's by `/Prev`,
4//! in the base's own cross-reference style.
5
6use std::io::Write;
7
8use flate2::write::ZlibEncoder;
9use flate2::Compression;
10use pdfboss_core::crypt::Sha256;
11use pdfboss_core::object::decode_text_string;
12use pdfboss_core::xref::{parse_section_at, startxref};
13use pdfboss_core::{Dict, Document, FastMap, Name, ObjRef, Object, Page, Stream, XrefKind};
14
15use crate::error::{Error, Result};
16use crate::importer::{rect_array, Importer};
17use crate::pdf::{text_string, Date, Metadata};
18use crate::ser::{serialize_dict, serialize_object};
19use crate::writer::{WriteOptions, Writer, XrefStyle};
20
21/// The first name tried for the resource every page draws the overlay
22/// form under. [`free_form_name`] falls back to `PdfbossWatermark2`,
23/// `PdfbossWatermark3`, ... when this one is already taken.
24const FORM_NAME: &str = "PdfbossWatermark";
25
26/// The first name in the series `PdfbossWatermark`, `PdfbossWatermark2`,
27/// ... whose `/XObject` entry is free in every marked page of `pages`.
28/// Overlaying a file that already carries a mark under an earlier name in
29/// the series draws its own form under the next free one instead of
30/// replacing the earlier entry and leaving its `Do` operators pointing at
31/// the new form. `pages` is fetched once by the caller and reused for the
32/// mark loop that follows: [`Document::page`] materializes a page's
33/// effective resources on every call, so probing by re-fetching would
34/// double that cost across the whole document.
35fn free_form_name(base: &Document, pages: &[Page]) -> Result<String> {
36    let mut candidate = FORM_NAME.to_string();
37    let mut next = 2;
38    while xobject_name_taken(base, pages, &candidate)? {
39        candidate = format!("{FORM_NAME}{next}");
40        next += 1;
41    }
42    Ok(candidate)
43}
44
45/// Whether any page in `pages` that is marked (has an [`ObjRef`] of its
46/// own) already carries an `/XObject` resource named `candidate`,
47/// resolving each page's effective resources the same way
48/// [`marked_page_dict`] and [`watermark_placed`] do before adding their
49/// own entry. A page inlined into `/Kids`, having no object of its own,
50/// is never marked, so it is skipped: only a marked page's `/XObject`
51/// dictionary can ever collide with the name this picks.
52fn xobject_name_taken(base: &Document, pages: &[Page], candidate: &str) -> Result<bool> {
53    for page in pages {
54        if page.object_ref().is_none() {
55            continue;
56        }
57        let Some(existing) = page.resources.get("XObject") else {
58            continue;
59        };
60        let existing = base.resolve(existing).map_err(core_error)?;
61        let Some(dict) = existing.as_dict() else {
62            continue;
63        };
64        if dict.get(candidate).is_some() {
65            return Ok(true);
66        }
67    }
68    Ok(false)
69}
70
71/// Every page of `base`, in order, fetched once: shared by the name probe
72/// and the mark loop that follows it, so [`Document::page`] materializes
73/// each page's effective resources only once per watermark construction
74/// rather than once for the probe and again for marking.
75fn fetch_pages(base: &Document) -> Result<Vec<Page>> {
76    crate::assemble::fetch_page_run(base, 0..base.flattened_page_count())
77}
78
79/// The content wrappers for one marked page: what precedes the page's own
80/// content and what follows it. Drawing over paints the form after the
81/// content; drawing under paints it first, so the content covers it.
82fn wrapper_streams(form_name: &str, under: bool) -> (Vec<u8>, Vec<u8>) {
83    if under {
84        return (
85            format!("q /{form_name} Do Q\nq\n").into_bytes(),
86            b"Q\n".to_vec(),
87        );
88    }
89    (
90        b"q\n".to_vec(),
91        format!("Q\nq /{form_name} Do Q\n").into_bytes(),
92    )
93}
94
95/// Shared by [`watermark_with`] and [`watermark_under_with`]: writes a fresh
96/// file through the [`Writer`] under `options` instead of appending an
97/// update, wrapping each page's content per [`wrapper_streams`].
98fn watermark_rewrite_placed(
99    base: &Document,
100    overlay: &Document,
101    options: WriteOptions,
102    under: bool,
103) -> Result<Vec<u8>> {
104    let pages = fetch_pages(base)?;
105    let form_name = free_form_name(base, &pages)?;
106    let mut writer = Writer::new(options);
107    let (prefix_bytes, suffix_bytes) = wrapper_streams(&form_name, under);
108    let prefix = writer.put_stream_raw(Dict::new(), prefix_bytes);
109    let suffix = writer.put_stream_raw(Dict::new(), suffix_bytes);
110    let form = overlay_form(&mut writer, overlay)?;
111
112    let trailer = &base.xref().trailer;
113    let root = trailer.get_ref("Root").ok_or(Error::MissingRoot)?;
114    let mut importer = Importer::new(&mut writer, base)?;
115    let new_root = importer.reference(root);
116    let new_info = trailer.get_ref("Info").map(|info| importer.reference(info));
117    for page in &pages {
118        let Some(page_ref) = page.object_ref() else {
119            continue;
120        };
121        let dict = marked_page_dict(&mut importer, base, page, form, prefix, suffix, &form_name)?;
122        importer.substitute(page_ref, dict);
123    }
124    importer.finish()?;
125    if let Some(new_info) = new_info {
126        writer.set_info(new_info);
127    }
128    writer.finish(new_root)
129}
130
131/// Like [`watermark`], but writes a fresh file through the [`Writer`] under
132/// `options` instead of appending an update: every object the base's
133/// catalog reaches is copied over, uncompressed streams are compressed when
134/// `options.compress` is set, and unreachable objects and earlier sections
135/// are left behind, so the result is usually smaller than the base. Both
136/// `base` and `overlay` are refused when locked, through
137/// [`crate::importer::Importer::new`]; a password-opened encrypted `base`
138/// or `overlay` copies its plaintext content across like any unencrypted
139/// source.
140///
141/// Placement is absolute and unscaled, and an unbalanced graphics state in
142/// a page's own content can clip or restyle the overlay, for the same
143/// reasons documented on [`watermark`].
144pub fn watermark_with(
145    base: &Document,
146    overlay: &Document,
147    options: WriteOptions,
148) -> Result<Vec<u8>> {
149    watermark_rewrite_placed(base, overlay, options, false)
150}
151
152/// Like [`watermark_with`], but draws the overlay beneath each page's
153/// content: the form paints first and the page's own content paints over
154/// it, so opaque content covers the overlay instead of the other way
155/// round.
156///
157/// Placement is absolute and unscaled, for the same reason documented on
158/// [`watermark`]. Painting the form first means no page state can reach
159/// it, so the unbalanced-graphics-state risk documented on [`watermark`]
160/// does not apply to this placement.
161pub fn watermark_under_with(
162    base: &Document,
163    overlay: &Document,
164    options: WriteOptions,
165) -> Result<Vec<u8>> {
166    watermark_rewrite_placed(base, overlay, options, true)
167}
168
169/// The marked dictionary for `page`, already fetched from `base` by the
170/// caller: its own dictionary translated into the target with `/Type
171/// /Page` guaranteed, its effective resources gaining the overlay form
172/// under `form_name`, and its content wrapped in `prefix` and `suffix`.
173fn marked_page_dict(
174    importer: &mut Importer,
175    base: &Document,
176    page: &Page,
177    form: ObjRef,
178    prefix: ObjRef,
179    suffix: ObjRef,
180    form_name: &str,
181) -> Result<Object> {
182    let mut dict = importer.copy_dict(page.dict())?;
183    let mut resources = importer.copy_dict(&page.resources)?;
184    let mut xobjects = match page.resources.get("XObject") {
185        Some(existing) => {
186            let existing = base.resolve(existing).map_err(core_error)?;
187            match existing.as_dict() {
188                Some(d) => importer.copy_dict(d)?,
189                None => Dict::new(),
190            }
191        }
192        None => Dict::new(),
193    };
194    xobjects.insert(name(form_name), Object::Ref(form));
195    resources.insert(name("XObject"), Object::Dict(xobjects));
196    dict.insert(name("Resources"), Object::Dict(resources));
197    dict.insert(name("Type"), Object::Name(name("Page")));
198    let mut contents = vec![Object::Ref(prefix)];
199    match page.dict().get("Contents") {
200        Some(Object::Array(items)) => {
201            for item in items {
202                contents.push(importer.copy(item)?);
203            }
204        }
205        Some(Object::Ref(r)) => match base.get(*r).map_err(core_error)? {
206            Object::Array(items) => {
207                for item in &items {
208                    contents.push(importer.copy(item)?);
209                }
210            }
211            _ => contents.push(Object::Ref(importer.reference(*r))),
212        },
213        _ => {}
214    }
215    contents.push(Object::Ref(suffix));
216    dict.insert(name("Contents"), Object::Array(contents));
217    Ok(Object::Dict(dict))
218}
219
220/// The overlay's first page as a form XObject, filled directly into
221/// `writer`: its media box as the bounding box, its decoded content
222/// deflated, its resources imported from `overlay`.
223fn overlay_form(writer: &mut Writer, overlay: &Document) -> Result<ObjRef> {
224    let page = overlay.page(0).map_err(core_error)?;
225    let content = page.content(overlay).map_err(core_error)?;
226    let resources = {
227        let mut importer = Importer::new(writer, overlay)?;
228        let resources = importer.copy_dict(&page.resources)?;
229        importer.finish()?;
230        resources
231    };
232    let mut dict = Dict::new();
233    dict.insert(name("Type"), Object::Name(name("XObject")));
234    dict.insert(name("Subtype"), Object::Name(name("Form")));
235    dict.insert(name("FormType"), Object::Int(1));
236    dict.insert(name("BBox"), rect_array(page.media_box));
237    dict.insert(name("Resources"), Object::Dict(resources));
238    dict.insert(name("Filter"), Object::Name(name("FlateDecode")));
239    let form = writer.reserve();
240    writer.fill(
241        form,
242        Object::Stream(Stream {
243            dict,
244            data: deflate(&content),
245        }),
246    )?;
247    Ok(form)
248}
249
250/// Shared by [`watermark`] and [`watermark_under`]: draws the first page of
251/// `overlay` over (or, when `under` is set, beneath) every page of `base`,
252/// returning `base`'s bytes followed by an incremental update: the overlay
253/// page as one form XObject (its resources copied into the base's object
254/// space), and each page's dictionary rewritten with that form in its
255/// resources, under the first free name [`free_form_name`] finds, and its
256/// content wrapped per [`wrapper_streams`]. Pages inlined directly into
257/// `/Kids`, having no object of their own, are left as they are. An
258/// encrypted `base` is refused: its new strings and streams would need
259/// encrypting too. An encrypted `overlay` is refused as well: its
260/// decrypted content would otherwise copy across into the plain update
261/// section.
262fn watermark_placed(base: &Document, overlay: &Document, under: bool) -> Result<Vec<u8>> {
263    let pages = fetch_pages(base)?;
264    let form_name = free_form_name(base, &pages)?;
265    let mut update = Update::new(base)?;
266    let form = update.overlay.import_form(overlay)?;
267    let (prefix_bytes, suffix_bytes) = wrapper_streams(&form_name, under);
268    let prefix = update
269        .overlay
270        .put(Object::Stream(plain_stream(prefix_bytes)));
271    let suffix = update
272        .overlay
273        .put(Object::Stream(plain_stream(suffix_bytes)));
274    for page in &pages {
275        let Some(page_ref) = page.object_ref() else {
276            continue;
277        };
278        let mut dict = page.dict().clone();
279        let mut resources = page.resources.clone();
280        let mut xobjects = match resources.get("XObject") {
281            Some(existing) => base
282                .resolve(existing)
283                .map_err(core_error)?
284                .as_dict()
285                .cloned()
286                .unwrap_or_default(),
287            None => Dict::new(),
288        };
289        xobjects.insert(name(&form_name), Object::Ref(form));
290        resources.insert(name("XObject"), Object::Dict(xobjects));
291        dict.insert(name("Resources"), Object::Dict(resources));
292        let mut contents = vec![Object::Ref(prefix)];
293        match dict.get("Contents").cloned() {
294            Some(Object::Array(items)) => contents.extend(items),
295            Some(Object::Ref(r)) => match base.get(r).map_err(core_error)? {
296                Object::Array(items) => contents.extend(items),
297                _ => contents.push(Object::Ref(r)),
298            },
299            _ => {}
300        }
301        contents.push(Object::Ref(suffix));
302        dict.insert(name("Contents"), Object::Array(contents));
303        update.set(page_ref, Object::Dict(dict));
304    }
305    update.bytes()
306}
307
308/// Draws the first page of `overlay` over every page of `base`, returning
309/// `base`'s bytes followed by an incremental update: the overlay page as
310/// one form XObject (its resources copied into the base's object space),
311/// and each page's dictionary rewritten with that form in its resources
312/// and its content wrapped in `q … Q` before the form is drawn. Pages
313/// inlined directly into `/Kids`, having no object of their own, are left
314/// as they are. An encrypted `base` is refused: its new strings and
315/// streams would need encrypting too. An encrypted `overlay` is refused
316/// as well: its decrypted content would otherwise copy across into the
317/// plain update section.
318///
319/// Placement is absolute and unscaled: the overlay page draws at its own
320/// coordinates on every page of `base`, with no scaling to that page's
321/// size, and the overlay page's `/Rotate` and `/CropBox` are not applied.
322/// Because the form paints last, a page whose own content leaves
323/// unbalanced graphics state (an unclosed clip or transform) can clip or
324/// restyle the overlay, since the wrapper's one closing `Q` cannot undo
325/// it.
326pub fn watermark(base: &Document, overlay: &Document) -> Result<Vec<u8>> {
327    watermark_placed(base, overlay, false)
328}
329
330/// Like [`watermark`], but draws the overlay beneath each page's content:
331/// the form paints first and the page's own content paints over it, so
332/// opaque content covers the overlay instead of the other way round.
333///
334/// The same absolute, unscaled placement documented on [`watermark`]
335/// applies here too. Painting the form first, before any of the page's
336/// own operators run, means no page state can reach it, so the
337/// unbalanced-graphics-state risk documented on [`watermark`] does not
338/// apply to this placement.
339pub fn watermark_under(base: &Document, overlay: &Document) -> Result<Vec<u8>> {
340    watermark_placed(base, overlay, true)
341}
342
343/// Stages `by` degrees of rotation, clockwise, on each of `pages` (0-based
344/// indices) into `update`: a clone of the page's own leaf dictionary, its
345/// `/Rotate` set to its current effective rotation plus `by`, normalized
346/// with `rem_euclid(360)`. The staged dictionary is untranslated: it
347/// keeps its own `/Parent`, so it stays exactly where it was in the page
348/// tree. A page with no object of its own (inlined directly into
349/// `/Kids`) cannot be staged this way: refused, naming its 1-based page
350/// number. `by` must be a multiple of 90; anything else is refused before
351/// any page is touched.
352pub fn rotate_pages(update: &mut Update, pages: &[usize], by: i32) -> Result<()> {
353    if by % 90 != 0 {
354        return Err(Error::Other(
355            "rotation must be a multiple of 90 degrees".to_string(),
356        ));
357    }
358    for &index in pages {
359        let page = update.doc.page(index).map_err(core_error)?;
360        let Some(page_ref) = page.object_ref() else {
361            return Err(Error::Other(format!(
362                "page {} is inlined into /Kids and cannot be edited in place",
363                index + 1
364            )));
365        };
366        let mut dict = page.dict().clone();
367        let rotate = (page.rotate + by).rem_euclid(360);
368        dict.insert(name("Rotate"), Object::Int(i64::from(rotate)));
369        update.set(page_ref, Object::Dict(dict));
370    }
371    Ok(())
372}
373
374/// The facts about a base document an update needs, read once from its
375/// trailer and its own newest cross-reference section: refuses an
376/// encrypted base or one missing `/Root` or a `startxref` to chain from.
377#[derive(Debug, Clone)]
378pub struct OverlayBase {
379    /// Byte offset of the base's own newest cross-reference section, named
380    /// as the appended section's `/Prev`.
381    pub prev: u64,
382    /// Style of that newest section, read from the section itself rather
383    /// than the merged trailer (a hybrid base's merged trailer carries
384    /// `/Type /XRef` inherited from its `/XRefStm`, even though its newest
385    /// section, per `startxref`, is the classic table).
386    pub kind: XrefStyle,
387    /// The next free object number: the base's declared `/Size`, raised to
388    /// one past its highest addressed object number.
389    pub size: u32,
390    /// The base's catalog.
391    pub root: ObjRef,
392    /// The base's document information dictionary, when present.
393    pub info: Option<ObjRef>,
394    /// The base trailer's `/ID` array, cloned.
395    pub id: Option<Object>,
396}
397
398impl OverlayBase {
399    /// Reads `doc`'s trailer and newest cross-reference section: the
400    /// section's offset and kind come from `doc.xref().newest_section()`,
401    /// already recorded while core loaded the file, falling back to
402    /// re-deriving them from `startxref` and `parse_section_at` when the
403    /// document has none (a recovery-scan base refuses with
404    /// [`Error::MissingStartxref`] on this fallback path). Refuses any
405    /// encrypted `doc` outright, wider than
406    /// [`crate::importer::Importer::new`]'s own locked-only refusal:
407    /// appending onto an already-encrypted base is a feature this crate
408    /// does not yet implement, so every encrypted base is refused here for
409    /// now, password-opened or not.
410    pub fn from_document(doc: &Document) -> Result<OverlayBase> {
411        if doc.is_encrypted() {
412            return Err(Error::EncryptedBase);
413        }
414        let trailer = &doc.xref().trailer;
415        let root = trailer.get_ref("Root").ok_or(Error::MissingRoot)?;
416        let (prev, kind) = match doc.xref().newest_section() {
417            Some(section) => (section.offset, xref_style(section.kind)),
418            None => {
419                let offset = startxref(doc.bytes()).ok_or(Error::MissingStartxref)?;
420                let kind = xref_style(
421                    parse_section_at(doc.bytes(), offset)
422                        .map_err(core_error)?
423                        .kind,
424                );
425                (offset as u64, kind)
426            }
427        };
428        let highest = doc.xref().iter().map(|(num, _)| num).max().unwrap_or(0);
429        let declared = trailer.get_int("Size").unwrap_or(0).max(0) as u32;
430        Ok(OverlayBase {
431            prev,
432            kind,
433            size: declared.max(highest + 1),
434            root,
435            info: trailer.get_ref("Info"),
436            id: trailer.get("ID").cloned(),
437        })
438    }
439}
440
441/// The [`XrefStyle`] an appended section should copy for a base whose
442/// newest section is `kind`.
443fn xref_style(kind: XrefKind) -> XrefStyle {
444    match kind {
445        XrefKind::Table => XrefStyle::Table,
446        XrefKind::Stream => XrefStyle::Stream,
447    }
448}
449
450/// One recorded change against an object number: a new or replacement body
451/// from [`Overlay::set`], or a free marker from [`Overlay::remove`].
452#[derive(Debug, Clone)]
453enum Change {
454    Set(Object),
455    Free,
456}
457
458/// An update section under construction over an [`OverlayBase`]: which
459/// objects it holds, new ones numbered from the base's first free number.
460#[derive(Debug, Clone)]
461pub struct Overlay {
462    base: OverlayBase,
463    next: u32,
464    objects: Vec<(ObjRef, Change)>,
465    imported: FastMap<ObjRef, ObjRef>,
466    info: Option<ObjRef>,
467}
468
469impl Overlay {
470    /// An empty update section over `base`, numbering new objects from its
471    /// first free number.
472    pub fn new(base: OverlayBase) -> Overlay {
473        let next = base.size;
474        Overlay {
475            base,
476            next,
477            objects: Vec::new(),
478            imported: FastMap::default(),
479            info: None,
480        }
481    }
482
483    /// Sets an object under its own number, whether new or a replacement
484    /// of one already in the base. Raises the next free number past `r`
485    /// when `r` was not already reserved, so a later `reserve`/`put` never
486    /// collides with a caller-chosen number. A no-op for object number 0:
487    /// it is already the free list's own permanent head, represented by
488    /// this section's synthetic entry-0 row whenever any other object is
489    /// freed, and a `set` row for it would collide with that row. Symmetric
490    /// with [`Overlay::remove`]'s guard.
491    pub fn set(&mut self, r: ObjRef, obj: Object) {
492        if r.num == 0 {
493            return;
494        }
495        self.next = self.next.max(r.num.saturating_add(1));
496        self.objects.push((r, Change::Set(obj)));
497    }
498
499    /// Marks `r` free: the appended section's cross-reference data chains
500    /// it into entry 0's free list, in whichever style the base uses. Its
501    /// generation for reuse is `r.gen` advanced by one (saturating at
502    /// 65535, the field's own limit), per the classic table's convention
503    /// for a deleted entry's row. A no-op for object number 0: it is
504    /// already the free list's own permanent head, represented by this
505    /// section's synthetic entry-0 row whenever any other object is freed.
506    pub fn remove(&mut self, r: ObjRef) {
507        if r.num == 0 {
508            return;
509        }
510        self.next = self.next.max(r.num.saturating_add(1));
511        let gen = r.gen.saturating_add(1);
512        self.objects
513            .push((ObjRef { num: r.num, gen }, Change::Free));
514    }
515
516    /// Allocates the next free object number without storing anything
517    /// under it yet.
518    pub fn reserve(&mut self) -> ObjRef {
519        let r = ObjRef {
520            num: self.next,
521            gen: 0,
522        };
523        self.next += 1;
524        r
525    }
526
527    /// Adds a new object under the next free number.
528    pub fn put(&mut self, obj: Object) -> ObjRef {
529        let r = self.reserve();
530        self.set(r, obj);
531        r
532    }
533
534    /// Registers the document information dictionary for the appended
535    /// section's trailer, overriding the base's own.
536    pub fn set_info(&mut self, r: ObjRef) {
537        self.info = Some(r);
538    }
539
540    /// Whether nothing has been set or removed yet.
541    pub fn is_empty(&self) -> bool {
542        self.objects.is_empty()
543    }
544
545    /// The appended section alone: every set object at `start` plus its
546    /// position within this section, then a cross-reference section in the
547    /// base's style naming the base's section as `/Prev`. Refused when no
548    /// object has been set. A number recorded more than once (repeated
549    /// `set`, or `set` and `remove` on the same reference) keeps only its
550    /// last-recorded change, so the appended cross-reference data never
551    /// carries two rows for one number.
552    pub fn section(&self, start: u64) -> Result<Vec<u8>> {
553        if self.is_empty() {
554            return Err(Error::EmptyUpdate);
555        }
556        let mut last: FastMap<u32, usize> = FastMap::default();
557        for (index, (r, _)) in self.objects.iter().enumerate() {
558            last.insert(r.num, index);
559        }
560        let mut winners: Vec<usize> = last.into_values().collect();
561        winners.sort_by_key(|&index| self.objects[index].0.num);
562        let mut out = Vec::new();
563        let mut rows: Vec<Row> = Vec::with_capacity(winners.len() + 1);
564        let mut freed: Vec<ObjRef> = Vec::new();
565        for index in winners {
566            let (r, change) = &self.objects[index];
567            match change {
568                Change::Set(obj) => {
569                    rows.push(Row::InFile(*r, start as usize + out.len()));
570                    write_indirect(&mut out, *r, obj)?;
571                }
572                Change::Free => freed.push(*r),
573            }
574        }
575        if !freed.is_empty() {
576            freed.sort_by_key(|r| r.num);
577            let head = freed.first().map_or(0, |r| r.num);
578            rows.push(Row::Free {
579                num: 0,
580                gen: 65535,
581                next: head,
582            });
583            for (index, r) in freed.iter().enumerate() {
584                let next = freed.get(index + 1).map_or(0, |n| n.num);
585                rows.push(Row::Free {
586                    num: r.num,
587                    gen: r.gen,
588                    next,
589                });
590            }
591        }
592        rows.sort_by_key(Row::num);
593
594        let mut trailer = Dict::new();
595        trailer.insert(name("Root"), Object::Ref(self.base.root));
596        if let Some(info) = self.info.or(self.base.info) {
597            trailer.insert(name("Info"), Object::Ref(info));
598        }
599        if let Some(id) = rotated_id(&self.base, &out, &freed) {
600            trailer.insert(name("ID"), id);
601        }
602        trailer.insert(name("Prev"), Object::Int(self.base.prev as i64));
603        match self.base.kind {
604            XrefStyle::Stream => finish_stream(&mut out, start, rows, trailer, self.next)?,
605            XrefStyle::Table => finish_table(&mut out, start, &rows, trailer, self.next)?,
606        }
607        Ok(out)
608    }
609
610    /// The overlay's first page as a form XObject in the base's object
611    /// space: its media box as the form's bounding box, its decoded content
612    /// as the form's stream, and its resource graph deep-copied and
613    /// renumbered. Refuses any encrypted `overlay` outright, wider than
614    /// [`crate::importer::Importer::new`]'s own locked-only refusal:
615    /// appending onto an encrypted base is a feature this crate does not
616    /// yet implement, so every encrypted overlay is refused here for now,
617    /// password-opened or not.
618    pub(crate) fn import_form(&mut self, overlay: &Document) -> Result<ObjRef> {
619        if overlay.is_encrypted() {
620            return Err(Error::EncryptedBase);
621        }
622        let page = overlay.page(0).map_err(core_error)?;
623        let content = page.content(overlay).map_err(core_error)?;
624        let resources = self.import_object(overlay, &Object::Dict(page.resources.clone()))?;
625        let mut dict = Dict::new();
626        dict.insert(name("Type"), Object::Name(name("XObject")));
627        dict.insert(name("Subtype"), Object::Name(name("Form")));
628        dict.insert(name("FormType"), Object::Int(1));
629        dict.insert(name("BBox"), rect_array(page.media_box));
630        dict.insert(name("Resources"), resources);
631        dict.insert(name("Filter"), Object::Name(name("FlateDecode")));
632        Ok(self.put(Object::Stream(Stream {
633            dict,
634            data: deflate(&content),
635        })))
636    }
637
638    /// A deep copy of `obj` from `source` into the update: every reference
639    /// it reaches becomes a new object here, each source object copied once
640    /// however many times it is referenced. Streams keep their encoded
641    /// bytes and filters; their `/Length` is rewritten on emission.
642    pub(crate) fn import_object(&mut self, source: &Document, obj: &Object) -> Result<Object> {
643        Ok(match obj {
644            Object::Ref(r) => {
645                if let Some(copied) = self.imported.get(r) {
646                    return Ok(Object::Ref(*copied));
647                }
648                let copied = self.reserve();
649                self.imported.insert(*r, copied);
650                let body = source.get(*r).map_err(core_error)?;
651                let body = self.import_object(source, &body)?;
652                self.objects.push((copied, Change::Set(body)));
653                Object::Ref(copied)
654            }
655            Object::Dict(d) => Object::Dict(self.import_dict(source, d)?),
656            Object::Array(items) => Object::Array(
657                items
658                    .iter()
659                    .map(|item| self.import_object(source, item))
660                    .collect::<Result<Vec<Object>>>()?,
661            ),
662            Object::Stream(s) => {
663                let mut dict = s.dict.clone();
664                dict.remove("Length");
665                Object::Stream(Stream {
666                    dict: self.import_dict(source, &dict)?,
667                    data: s.data.clone(),
668                })
669            }
670            other => other.clone(),
671        })
672    }
673
674    pub(crate) fn import_dict(&mut self, source: &Document, dict: &Dict) -> Result<Dict> {
675        let mut out = Dict::new();
676        for (key, value) in dict.iter() {
677            out.insert(key.clone(), self.import_object(source, value)?);
678        }
679        Ok(out)
680    }
681}
682
683/// Merges `meta` into `existing_info`'s dictionary (or a fresh one, staged
684/// under a newly reserved number, when `existing_info` is `None`): a
685/// `Some` field overwrites its key (`Some(String::new())` writes an empty
686/// string), a `None` field leaves whatever key was already there. The
687/// merged dictionary is staged into `overlay` via `set` and `set_info`.
688///
689/// When `xmp_ref` is `Some`, the merged dictionary is read back into a
690/// [`Metadata`] (text fields via `decode_text_string`, dates via
691/// [`Date::parse_pdf`], an unparseable date simply dropping out) and
692/// staged under `xmp_ref` as a fresh, unfiltered `/Type /Metadata /Subtype
693/// /XML` stream of the crate's XMP packet over that merged value: any XMP
694/// property outside those eight fields is not carried into the new
695/// packet, though the original packet's bytes stay in the base.
696///
697/// Shared by [`Update::set_metadata`] and its asynchronous counterpart.
698pub fn set_metadata_with(
699    overlay: &mut Overlay,
700    existing_info: Option<(ObjRef, Dict)>,
701    xmp_ref: Option<ObjRef>,
702    meta: Metadata,
703) -> Result<()> {
704    let (target, existing_dict) = match existing_info {
705        Some((r, dict)) => (r, Some(dict)),
706        None => (overlay.reserve(), None),
707    };
708    let (dict, merged) = merge_metadata(existing_dict, &meta);
709    overlay.set(target, Object::Dict(dict));
710    overlay.set_info(target);
711    let Some(xmp_ref) = xmp_ref else {
712        return Ok(());
713    };
714    overlay.set(xmp_ref, xmp_metadata_stream(&merged));
715    Ok(())
716}
717
718/// `existing` (`None` starts from an empty dictionary) with every `Some`
719/// field of `meta` applied: a `Some` field overwrites its key
720/// (`Some(String::new())` writes an empty string), a `None` field leaves
721/// whatever key was already there. Also returns that merged dictionary read
722/// back into a [`Metadata`] (text fields via `decode_text_string`, dates via
723/// [`Date::parse_pdf`], an unparseable date simply dropping out), for
724/// [`xmp_metadata_stream`]: any XMP property outside those eight fields is
725/// not carried into a rebuilt packet.
726///
727/// Shared by [`set_metadata_with`] and [`crate::assemble::rewrite_with_metadata`].
728pub(crate) fn merge_metadata(existing: Option<Dict>, meta: &Metadata) -> (Dict, Metadata) {
729    let mut dict = existing.unwrap_or_default();
730    apply_metadata_fields(&mut dict, meta);
731    let merged = metadata_from_info(&dict);
732    (dict, merged)
733}
734
735/// A fresh, unfiltered `/Type /Metadata /Subtype /XML` stream over `meta`'s
736/// XMP packet, ready to stage into an [`Overlay`] or substitute into an
737/// import.
738pub(crate) fn xmp_metadata_stream(meta: &Metadata) -> Object {
739    let mut xmp_dict = Dict::new();
740    xmp_dict.insert(name("Type"), Object::Name(name("Metadata")));
741    xmp_dict.insert(name("Subtype"), Object::Name(name("XML")));
742    Object::Stream(Stream {
743        dict: xmp_dict,
744        data: crate::xmp::packet(meta),
745    })
746}
747
748/// `dict` with every value resolved against `doc`: an indirect value such
749/// as `/Title 12 0 R` becomes the string object it points to, so a field
750/// [`merge_metadata`] keeps (a `None` field in the merge) still reads back
751/// as text rather than silently vanishing from a rebuilt XMP packet. A
752/// value whose reference chain fails to resolve (an unreadable target, or
753/// a cycle) is kept as given.
754pub(crate) fn resolve_dict(doc: &Document, dict: &Dict) -> Dict {
755    let mut out = Dict::new();
756    for (key, value) in dict.iter() {
757        let resolved = doc.resolve(value).unwrap_or_else(|_| value.clone());
758        out.insert(key.clone(), resolved);
759    }
760    out
761}
762
763/// `doc`'s catalog's `/Metadata` entry, when it is an indirect reference.
764/// `None` for a catalog with no `/Metadata`, or one that reads as a direct
765/// stream rather than a reference.
766pub(crate) fn catalog_metadata_ref(doc: &Document, root: ObjRef) -> Option<ObjRef> {
767    let catalog = doc.get(root).ok()?;
768    match catalog.as_dict()?.get("Metadata")? {
769        Object::Ref(r) => Some(*r),
770        _ => None,
771    }
772}
773
774/// Writes every `Some` field of `meta` into `dict` under its `/Info` key;
775/// a `None` field is left untouched.
776fn apply_metadata_fields(dict: &mut Dict, meta: &Metadata) {
777    let texts = [
778        ("Title", &meta.title),
779        ("Author", &meta.author),
780        ("Subject", &meta.subject),
781        ("Keywords", &meta.keywords),
782        ("Creator", &meta.creator),
783        ("Producer", &meta.producer),
784    ];
785    for (key, value) in texts {
786        if let Some(value) = value {
787            dict.insert(name(key), text_string(value));
788        }
789    }
790    let dates = [
791        ("CreationDate", meta.creation_date),
792        ("ModDate", meta.modification_date),
793    ];
794    for (key, value) in dates {
795        if let Some(date) = value {
796            dict.insert(name(key), Object::String(date.to_pdf_string().into_bytes()));
797        }
798    }
799}
800
801/// Reads an `/Info` dictionary back into a [`Metadata`]: text fields via
802/// `decode_text_string`, dates via [`Date::parse_pdf`]. A missing or
803/// unparseable field is simply `None`.
804fn metadata_from_info(dict: &Dict) -> Metadata {
805    Metadata {
806        title: info_text(dict, "Title"),
807        author: info_text(dict, "Author"),
808        subject: info_text(dict, "Subject"),
809        keywords: info_text(dict, "Keywords"),
810        creator: info_text(dict, "Creator"),
811        producer: info_text(dict, "Producer"),
812        creation_date: info_date(dict, "CreationDate"),
813        modification_date: info_date(dict, "ModDate"),
814    }
815}
816
817/// `dict[key]` decoded as a text string, when present and a string.
818fn info_text(dict: &Dict, key: &str) -> Option<String> {
819    Some(decode_text_string(dict.get(key)?.as_str_bytes()?))
820}
821
822/// `dict[key]` decoded and parsed as a PDF date, when present, a string,
823/// and a valid date.
824fn info_date(dict: &Dict, key: &str) -> Option<Date> {
825    Date::parse_pdf(&decode_text_string(dict.get(key)?.as_str_bytes()?))
826}
827
828/// The base's length as an update's write position, plus whether a pad
829/// newline must be inserted first: an object header may not follow
830/// directly after `%%EOF` unless the base already ends on a line
831/// terminator (`\n` or `\r`).
832pub fn start_offset(base: &[u8]) -> (u64, bool) {
833    let pad = !matches!(base.last(), Some(b'\n') | Some(b'\r'));
834    (base.len() as u64 + u64::from(pad), pad)
835}
836
837/// A base document plus the update section being built over it.
838pub struct Update<'a> {
839    doc: &'a Document,
840    overlay: Overlay,
841}
842
843impl<'a> Update<'a> {
844    /// Opens `doc` for an update: refuses an encrypted base or one missing
845    /// `/Root` or a `startxref` to chain the appended section's `/Prev` to.
846    pub fn new(doc: &'a Document) -> Result<Update<'a>> {
847        let base = OverlayBase::from_document(doc)?;
848        Ok(Update {
849            doc,
850            overlay: Overlay::new(base),
851        })
852    }
853
854    /// Sets an object under its own number, whether new or a replacement
855    /// of one already in the base.
856    pub fn set(&mut self, r: ObjRef, obj: Object) {
857        self.overlay.set(r, obj);
858    }
859
860    /// Marks `r` free in the appended section's cross-reference data.
861    pub fn remove(&mut self, r: ObjRef) {
862        self.overlay.remove(r);
863    }
864
865    /// Allocates the next free object number without storing anything
866    /// under it yet.
867    pub fn reserve(&mut self) -> ObjRef {
868        self.overlay.reserve()
869    }
870
871    /// The update section under construction.
872    pub fn overlay(&self) -> &Overlay {
873        &self.overlay
874    }
875
876    /// Merges `meta` into the base document's `/Info` dictionary: the ref
877    /// comes from the overlay's own info ref when a prior call set one,
878    /// else the base's; the dictionary itself always comes from the base
879    /// document (never from a prior call's staged fields, so two calls on
880    /// one `Update` do not compound; on a base without `/Info`, a call
881    /// starts from a fresh dictionary). When the catalog already names an
882    /// XMP packet, it is rewritten from the merged fields. See
883    /// [`set_metadata_with`] for the merge and rewrite rules.
884    pub fn set_metadata(&mut self, meta: Metadata) -> Result<()> {
885        let info_ref = self.overlay.info.or(self.overlay.base.info);
886        let existing_info = info_ref.and_then(|r| {
887            let dict = self.doc.get(r).ok()?.as_dict()?.clone();
888            Some((r, resolve_dict(self.doc, &dict)))
889        });
890        let xmp_ref = catalog_metadata_ref(self.doc, self.overlay.base.root);
891        set_metadata_with(&mut self.overlay, existing_info, xmp_ref, meta)
892    }
893
894    /// The base bytes, whether a pad newline goes before the appended
895    /// section, and the section itself, computed together so a refused
896    /// update (or any other failure) is known before anything is written
897    /// anywhere.
898    fn parts(&self) -> Result<(&[u8], bool, Vec<u8>)> {
899        let base = self.doc.bytes();
900        let (start, pad) = start_offset(base);
901        let section = self.overlay.section(start)?;
902        Ok((base, pad, section))
903    }
904
905    /// Writes the base bytes, a pad newline when the base needs one, and
906    /// the appended section into `out`. The section is built before any
907    /// byte reaches `out`, so a refused update (or any other failure)
908    /// writes nothing at all.
909    pub fn append_into(&self, mut out: impl std::io::Write) -> Result<()> {
910        let (base, pad, section) = self.parts()?;
911        out.write_all(base)?;
912        if pad {
913            out.write_all(b"\n")?;
914        }
915        out.write_all(&section)?;
916        Ok(())
917    }
918
919    /// [`Update::append_into`] to a new file at `path`: the file is
920    /// created only once the update is known to build, so a refused
921    /// update leaves no file behind at all.
922    pub fn save(&self, path: impl AsRef<std::path::Path>) -> Result<()> {
923        let (base, pad, section) = self.parts()?;
924        let mut file = std::fs::File::create(path)?;
925        file.write_all(base)?;
926        if pad {
927            file.write_all(b"\n")?;
928        }
929        file.write_all(&section)?;
930        Ok(())
931    }
932
933    /// The base bytes followed by the update section, as one buffer.
934    pub fn bytes(&self) -> Result<Vec<u8>> {
935        let mut out = Vec::new();
936        self.append_into(&mut out)?;
937        Ok(out)
938    }
939}
940
941/// One row of the appended section's cross-reference data: an object
942/// stored at a byte offset, or a freed number chained to the next free
943/// number in the section's own free list (entry 0 when it is the head).
944#[derive(Debug, Clone, Copy)]
945enum Row {
946    InFile(ObjRef, usize),
947    Free { num: u32, gen: u16, next: u32 },
948}
949
950impl Row {
951    fn num(&self) -> u32 {
952        match self {
953            Row::InFile(r, _) => r.num,
954            Row::Free { num, .. } => *num,
955        }
956    }
957}
958
959/// Splits `rows`, already sorted ascending by object number, into maximal
960/// runs of consecutive numbers, as `(run start index, run length)` pairs.
961/// Shared by the classic table's subsections and the xref stream's
962/// `/Index` pairs, so both group the same way.
963fn contiguous_runs(rows: &[Row]) -> Vec<(usize, usize)> {
964    let mut runs = Vec::new();
965    let mut begin = 0;
966    while begin < rows.len() {
967        let mut end = begin + 1;
968        while end < rows.len() && rows[end].num() == rows[end - 1].num() + 1 {
969            end += 1;
970        }
971        runs.push((begin, end - begin));
972        begin = end;
973    }
974    runs
975}
976
977/// The appended trailer's `/ID`: the base's first half kept verbatim, the
978/// second half replaced by the first 16 bytes of a SHA-256 over the first
979/// half's bytes, the base's `/Prev` offset as little-endian bytes, `body`
980/// (the section's serialized objects, built before its xref part), and
981/// finally each of `freed`'s `(num, gen)` pairs in order (`num` then `gen`,
982/// both little-endian), so a frees-only update, whose `body` is empty,
983/// still rotates by what it freed rather than staying fixed. `None` when
984/// the base carries no `/ID` array with a string first element, in which
985/// case the appended trailer omits the key entirely.
986fn rotated_id(base: &OverlayBase, body: &[u8], freed: &[ObjRef]) -> Option<Object> {
987    let Some(Object::Array(halves)) = &base.id else {
988        return None;
989    };
990    let Some(Object::String(first)) = halves.first() else {
991        return None;
992    };
993    let mut hasher = Sha256::new();
994    hasher.update(first);
995    hasher.update(&base.prev.to_le_bytes());
996    hasher.update(body);
997    for r in freed {
998        hasher.update(&r.num.to_le_bytes());
999        hasher.update(&r.gen.to_le_bytes());
1000    }
1001    let digest = hasher.finalize();
1002    Some(Object::Array(vec![
1003        Object::String(first.clone()),
1004        Object::String(digest[..16].to_vec()),
1005    ]))
1006}
1007
1008/// A cross-reference stream as the section's last object: one row per
1009/// object of the update (or per freed number) plus one for the stream
1010/// itself, and `/Index` pairs one per contiguous run of object numbers.
1011fn finish_stream(
1012    out: &mut Vec<u8>,
1013    start: u64,
1014    mut rows: Vec<Row>,
1015    mut dict: Dict,
1016    mut next: u32,
1017) -> Result<()> {
1018    let xref_ref = ObjRef { num: next, gen: 0 };
1019    next += 1;
1020    let xref_offset = start as usize + out.len();
1021    rows.push(Row::InFile(xref_ref, xref_offset));
1022    rows.sort_by_key(Row::num);
1023    let runs = contiguous_runs(&rows);
1024    let mut index = Vec::with_capacity(runs.len() * 2);
1025    for (begin, len) in runs {
1026        index.push(Object::Int(i64::from(rows[begin].num())));
1027        index.push(Object::Int(len as i64));
1028    }
1029    let mut data = Vec::with_capacity(rows.len() * 7);
1030    for row in &rows {
1031        match row {
1032            Row::InFile(r, offset) => {
1033                data.push(1);
1034                data.extend_from_slice(&field_offset(*offset)?.to_be_bytes());
1035                data.extend_from_slice(&r.gen.to_be_bytes());
1036            }
1037            Row::Free {
1038                gen,
1039                next: free_next,
1040                ..
1041            } => {
1042                data.push(0);
1043                data.extend_from_slice(&free_next.to_be_bytes());
1044                data.extend_from_slice(&gen.to_be_bytes());
1045            }
1046        }
1047    }
1048    dict.insert(name("Type"), Object::Name(name("XRef")));
1049    dict.insert(name("Size"), Object::Int(i64::from(next)));
1050    dict.insert(
1051        name("W"),
1052        Object::Array(vec![Object::Int(1), Object::Int(4), Object::Int(2)]),
1053    );
1054    dict.insert(name("Index"), Object::Array(index));
1055    write_indirect(out, xref_ref, &Object::Stream(Stream { dict, data }))?;
1056    out.extend_from_slice(format!("startxref\n{xref_offset}\n%%EOF\n").as_bytes());
1057    Ok(())
1058}
1059
1060/// A classic `xref` table with one subsection per run of consecutive
1061/// object numbers, then the `trailer` dictionary. A freed row uses `f` in
1062/// place of `n`, its first field naming the next free number in the
1063/// section's own chain rather than a byte offset.
1064fn finish_table(
1065    out: &mut Vec<u8>,
1066    start: u64,
1067    rows: &[Row],
1068    mut dict: Dict,
1069    size: u32,
1070) -> Result<()> {
1071    let xref_offset = start as usize + out.len();
1072    out.extend_from_slice(b"xref\n");
1073    for (begin, len) in contiguous_runs(rows) {
1074        out.extend_from_slice(format!("{} {}\n", rows[begin].num(), len).as_bytes());
1075        for row in &rows[begin..begin + len] {
1076            match row {
1077                Row::InFile(r, offset) => out.extend_from_slice(
1078                    format!("{:010} {:05} n \n", table_offset(*offset)?, r.gen).as_bytes(),
1079                ),
1080                Row::Free { gen, next, .. } => {
1081                    out.extend_from_slice(format!("{next:010} {gen:05} f \n").as_bytes())
1082                }
1083            }
1084        }
1085    }
1086    dict.insert(name("Size"), Object::Int(i64::from(size)));
1087    out.extend_from_slice(b"trailer\n");
1088    serialize_dict(&dict, out)?;
1089    out.extend_from_slice(format!("\nstartxref\n{xref_offset}\n%%EOF\n").as_bytes());
1090    Ok(())
1091}
1092
1093/// Emits `num gen obj` through `endobj`; a stream carries a direct
1094/// `/Length` of its stored byte count.
1095fn write_indirect(out: &mut Vec<u8>, r: ObjRef, obj: &Object) -> Result<()> {
1096    out.extend_from_slice(format!("{} {} obj\n", r.num, r.gen).as_bytes());
1097    match obj {
1098        Object::Stream(s) => {
1099            let mut dict = s.dict.clone();
1100            dict.insert(name("Length"), Object::Int(s.data.len() as i64));
1101            serialize_dict(&dict, out)?;
1102            out.extend_from_slice(b"\nstream\n");
1103            out.extend_from_slice(&s.data);
1104            out.extend_from_slice(b"\nendstream\nendobj\n");
1105        }
1106        direct => {
1107            serialize_object(direct, out)?;
1108            out.extend_from_slice(b"\nendobj\n");
1109        }
1110    }
1111    Ok(())
1112}
1113
1114/// An uncompressed stream with no filter of its own.
1115fn plain_stream(data: Vec<u8>) -> Stream {
1116    Stream {
1117        dict: Dict::new(),
1118        data,
1119    }
1120}
1121
1122pub(crate) fn deflate(data: &[u8]) -> Vec<u8> {
1123    let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
1124    encoder
1125        .write_all(data)
1126        .expect("writing into a Vec cannot fail");
1127    encoder
1128        .finish()
1129        .expect("finishing an in-memory zlib stream cannot fail")
1130}
1131
1132/// A byte position as the 4-byte offset field of a cross-reference stream.
1133fn field_offset(position: usize) -> Result<u32> {
1134    u32::try_from(position)
1135        .map_err(|_| Error::Other("file offset exceeds the 4-byte xref field".to_string()))
1136}
1137
1138/// A byte position as the 10-digit offset field of a classic xref table.
1139fn table_offset(position: usize) -> Result<usize> {
1140    if position as u64 <= 9_999_999_999 {
1141        return Ok(position);
1142    }
1143    Err(Error::Other(
1144        "file offset exceeds the 10-digit xref table field".to_string(),
1145    ))
1146}
1147
1148fn name(text: &str) -> Name {
1149    Name(text.to_string())
1150}
1151
1152pub(crate) fn core_error(error: pdfboss_core::Error) -> Error {
1153    Error::Other(error.to_string())
1154}