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.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    /// Offset of the cross-reference stream the base's newest section names
391    /// as its `/XRefStm`, when the base is a hybrid-reference file; the
392    /// appended trailer repeats it.
393    pub xrefstm: Option<u64>,
394    /// The base's catalog.
395    pub root: ObjRef,
396    /// The base's document information dictionary, when present.
397    pub info: Option<ObjRef>,
398    /// The base trailer's `/ID` array, cloned.
399    pub id: Option<Object>,
400}
401
402impl OverlayBase {
403    /// Reads `doc`'s trailer and newest cross-reference section: the
404    /// section's offset and kind come from `doc.xref().newest_section()`,
405    /// already recorded while core loaded the file, falling back to
406    /// re-deriving them from `startxref` and `parse_section_at` when the
407    /// document has none (a recovery-scan base refuses with
408    /// [`Error::MissingStartxref`] on this fallback path). Refuses any
409    /// encrypted `doc` outright, wider than
410    /// [`crate::importer::Importer::new`]'s own locked-only refusal:
411    /// appending onto an already-encrypted base is a feature this crate
412    /// does not yet implement, so every encrypted base is refused here for
413    /// now, password-opened or not.
414    pub fn from_document(doc: &Document) -> Result<OverlayBase> {
415        if doc.is_encrypted() {
416            return Err(Error::EncryptedBase);
417        }
418        let trailer = &doc.xref().trailer;
419        let root = trailer.get_ref("Root").ok_or(Error::MissingRoot)?;
420        let (prev, kind) = match doc.xref().newest_section() {
421            Some(section) => (section.offset, xref_style(section.kind)),
422            None => {
423                let offset = startxref(doc.bytes()).ok_or(Error::MissingStartxref)?;
424                let kind = xref_style(
425                    parse_section_at(doc.bytes(), offset)
426                        .map_err(core_error)?
427                        .kind,
428                );
429                (offset as u64, kind)
430            }
431        };
432        let xrefstm = usize::try_from(prev)
433            .ok()
434            .and_then(|offset| parse_section_at(doc.bytes(), offset).ok())
435            .and_then(|section| section.xrefstm)
436            .and_then(|offset| u64::try_from(offset).ok());
437        let highest = doc.xref().iter().map(|(num, _)| num).max().unwrap_or(0);
438        let declared = trailer.get_int("Size").unwrap_or(0).max(0) as u32;
439        Ok(OverlayBase {
440            prev,
441            kind,
442            size: declared.max(highest + 1),
443            xrefstm,
444            root,
445            info: trailer.get_ref("Info"),
446            id: trailer.get("ID").cloned(),
447        })
448    }
449}
450
451/// The [`XrefStyle`] an appended section should copy for a base whose
452/// newest section is `kind`.
453fn xref_style(kind: XrefKind) -> XrefStyle {
454    match kind {
455        XrefKind::Table => XrefStyle::Table,
456        XrefKind::Stream => XrefStyle::Stream,
457    }
458}
459
460/// A byte offset as a PDF integer for the trailer entry `key`. An offset
461/// past `i64::MAX` is an error, never a wrapped negative value.
462fn offset_integer(key: &str, offset: u64) -> Result<Object> {
463    i64::try_from(offset)
464        .map(Object::Int)
465        .map_err(|_| Error::Other(format!("/{key} offset {offset} exceeds a PDF integer")))
466}
467
468/// One recorded change against an object number: a new or replacement body
469/// from [`Overlay::set`], or a free marker from [`Overlay::remove`].
470#[derive(Debug, Clone)]
471enum Change {
472    Set(Object),
473    Free,
474}
475
476/// An update section under construction over an [`OverlayBase`]: which
477/// objects it holds, new ones numbered from the base's first free number.
478#[derive(Debug, Clone)]
479pub struct Overlay {
480    base: OverlayBase,
481    next: u32,
482    objects: Vec<(ObjRef, Change)>,
483    imported: FastMap<ObjRef, ObjRef>,
484    info: Option<ObjRef>,
485}
486
487impl Overlay {
488    /// An empty update section over `base`, numbering new objects from its
489    /// first free number.
490    pub fn new(base: OverlayBase) -> Overlay {
491        let next = base.size;
492        Overlay {
493            base,
494            next,
495            objects: Vec::new(),
496            imported: FastMap::default(),
497            info: None,
498        }
499    }
500
501    /// Sets an object under its own number, whether new or a replacement
502    /// of one already in the base. Raises the next free number past `r`
503    /// when `r` was not already reserved, so a later `reserve`/`put` never
504    /// collides with a caller-chosen number. A no-op for object number 0:
505    /// it is already the free list's own permanent head, represented by
506    /// this section's synthetic entry-0 row whenever any other object is
507    /// freed, and a `set` row for it would collide with that row. Symmetric
508    /// with [`Overlay::remove`]'s guard.
509    pub fn set(&mut self, r: ObjRef, obj: Object) {
510        if r.num == 0 {
511            return;
512        }
513        self.next = self.next.max(r.num.saturating_add(1));
514        self.objects.push((r, Change::Set(obj)));
515    }
516
517    /// Marks `r` free: the appended section's cross-reference data chains
518    /// it into entry 0's free list, in whichever style the base uses. Its
519    /// generation for reuse is `r.gen` advanced by one (saturating at
520    /// 65535, the field's own limit), per the classic table's convention
521    /// for a deleted entry's row. A no-op for object number 0: it is
522    /// already the free list's own permanent head, represented by this
523    /// section's synthetic entry-0 row whenever any other object is freed.
524    pub fn remove(&mut self, r: ObjRef) {
525        if r.num == 0 {
526            return;
527        }
528        self.next = self.next.max(r.num.saturating_add(1));
529        let gen = r.gen.saturating_add(1);
530        self.objects
531            .push((ObjRef { num: r.num, gen }, Change::Free));
532    }
533
534    /// Allocates the next free object number without storing anything
535    /// under it yet.
536    pub fn reserve(&mut self) -> ObjRef {
537        let r = ObjRef {
538            num: self.next,
539            gen: 0,
540        };
541        self.next += 1;
542        r
543    }
544
545    /// Adds a new object under the next free number.
546    pub fn put(&mut self, obj: Object) -> ObjRef {
547        let r = self.reserve();
548        self.set(r, obj);
549        r
550    }
551
552    /// Registers the document information dictionary for the appended
553    /// section's trailer, overriding the base's own.
554    pub fn set_info(&mut self, r: ObjRef) {
555        self.info = Some(r);
556    }
557
558    /// Whether nothing has been set or removed yet.
559    pub fn is_empty(&self) -> bool {
560        self.objects.is_empty()
561    }
562
563    /// The appended section alone: every set object at `start` plus its
564    /// position within this section, then a cross-reference section in the
565    /// base's style naming the base's section as `/Prev`. Refused when no
566    /// object has been set. A number recorded more than once (repeated
567    /// `set`, or `set` and `remove` on the same reference) keeps only its
568    /// last-recorded change, so the appended cross-reference data never
569    /// carries two rows for one number.
570    pub fn section(&self, start: u64) -> Result<Vec<u8>> {
571        if self.is_empty() {
572            return Err(Error::EmptyUpdate);
573        }
574        let mut last: FastMap<u32, usize> = FastMap::default();
575        for (index, (r, _)) in self.objects.iter().enumerate() {
576            last.insert(r.num, index);
577        }
578        let mut winners: Vec<usize> = last.into_values().collect();
579        winners.sort_by_key(|&index| self.objects[index].0.num);
580        let mut out = Vec::new();
581        let mut rows: Vec<Row> = Vec::with_capacity(winners.len() + 1);
582        let mut freed: Vec<ObjRef> = Vec::new();
583        for index in winners {
584            let (r, change) = &self.objects[index];
585            match change {
586                Change::Set(obj) => {
587                    rows.push(Row::InFile(*r, start as usize + out.len()));
588                    write_indirect(&mut out, *r, obj)?;
589                }
590                Change::Free => freed.push(*r),
591            }
592        }
593        if !freed.is_empty() {
594            freed.sort_by_key(|r| r.num);
595            let head = freed.first().map_or(0, |r| r.num);
596            rows.push(Row::Free {
597                num: 0,
598                gen: 65535,
599                next: head,
600            });
601            for (index, r) in freed.iter().enumerate() {
602                let next = freed.get(index + 1).map_or(0, |n| n.num);
603                rows.push(Row::Free {
604                    num: r.num,
605                    gen: r.gen,
606                    next,
607                });
608            }
609        }
610        rows.sort_by_key(Row::num);
611
612        let mut trailer = Dict::new();
613        trailer.insert(name("Root"), Object::Ref(self.base.root));
614        if let Some(info) = self.info.or(self.base.info) {
615            trailer.insert(name("Info"), Object::Ref(info));
616        }
617        if let Some(id) = rotated_id(&self.base, &out, &freed) {
618            trailer.insert(name("ID"), id);
619        }
620        trailer.insert(name("Prev"), offset_integer("Prev", self.base.prev)?);
621        if let (XrefStyle::Table, Some(xrefstm)) = (self.base.kind, self.base.xrefstm) {
622            trailer.insert(name("XRefStm"), offset_integer("XRefStm", xrefstm)?);
623        }
624        match self.base.kind {
625            XrefStyle::Stream => finish_stream(&mut out, start, rows, trailer, self.next)?,
626            XrefStyle::Table => finish_table(&mut out, start, &rows, trailer, self.next)?,
627        }
628        Ok(out)
629    }
630
631    /// The overlay's first page as a form XObject in the base's object
632    /// space: its media box as the form's bounding box, its decoded content
633    /// as the form's stream, and its resource graph deep-copied and
634    /// renumbered. Refuses any encrypted `overlay` outright, wider than
635    /// [`crate::importer::Importer::new`]'s own locked-only refusal:
636    /// appending onto an encrypted base is a feature this crate does not
637    /// yet implement, so every encrypted overlay is refused here for now,
638    /// password-opened or not.
639    pub(crate) fn import_form(&mut self, overlay: &Document) -> Result<ObjRef> {
640        if overlay.is_encrypted() {
641            return Err(Error::EncryptedBase);
642        }
643        let page = overlay.page(0).map_err(core_error)?;
644        let content = page.content(overlay).map_err(core_error)?;
645        let resources = self.import_object(overlay, &Object::Dict(page.resources.clone()))?;
646        let mut dict = Dict::new();
647        dict.insert(name("Type"), Object::Name(name("XObject")));
648        dict.insert(name("Subtype"), Object::Name(name("Form")));
649        dict.insert(name("FormType"), Object::Int(1));
650        dict.insert(name("BBox"), rect_array(page.media_box));
651        dict.insert(name("Resources"), resources);
652        dict.insert(name("Filter"), Object::Name(name("FlateDecode")));
653        Ok(self.put(Object::Stream(Stream {
654            dict,
655            data: deflate(&content)?,
656        })))
657    }
658
659    /// A deep copy of `obj` from `source` into the update: every reference
660    /// it reaches becomes a new object here, each source object copied once
661    /// however many times it is referenced. Streams keep their encoded
662    /// bytes and filters; their `/Length` is rewritten on emission.
663    pub(crate) fn import_object(&mut self, source: &Document, obj: &Object) -> Result<Object> {
664        Ok(match obj {
665            Object::Ref(r) => {
666                if let Some(copied) = self.imported.get(r) {
667                    return Ok(Object::Ref(*copied));
668                }
669                let copied = self.reserve();
670                self.imported.insert(*r, copied);
671                let body = source.get(*r).map_err(core_error)?;
672                let body = self.import_object(source, &body)?;
673                self.objects.push((copied, Change::Set(body)));
674                Object::Ref(copied)
675            }
676            Object::Dict(d) => Object::Dict(self.import_dict(source, d)?),
677            Object::Array(items) => Object::Array(
678                items
679                    .iter()
680                    .map(|item| self.import_object(source, item))
681                    .collect::<Result<Vec<Object>>>()?,
682            ),
683            Object::Stream(s) => {
684                let mut dict = s.dict.clone();
685                dict.remove("Length");
686                Object::Stream(Stream {
687                    dict: self.import_dict(source, &dict)?,
688                    data: s.data.clone(),
689                })
690            }
691            other => other.clone(),
692        })
693    }
694
695    pub(crate) fn import_dict(&mut self, source: &Document, dict: &Dict) -> Result<Dict> {
696        let mut out = Dict::new();
697        for (key, value) in dict.iter() {
698            out.insert(key.clone(), self.import_object(source, value)?);
699        }
700        Ok(out)
701    }
702}
703
704/// Merges `meta` into `existing_info`'s dictionary (or a fresh one, staged
705/// under a newly reserved number, when `existing_info` is `None`): a
706/// `Some` field overwrites its key (`Some(String::new())` writes an empty
707/// string), a `None` field leaves whatever key was already there. The
708/// merged dictionary is staged into `overlay` via `set` and `set_info`.
709///
710/// When `xmp_ref` is `Some`, the merged dictionary is read back into a
711/// [`Metadata`] (text fields via `decode_text_string`, dates via
712/// [`Date::parse_pdf`], an unparseable date simply dropping out) and
713/// staged under `xmp_ref` as a fresh, unfiltered `/Type /Metadata /Subtype
714/// /XML` stream of the crate's XMP packet over that merged value: any XMP
715/// property outside those eight fields is not carried into the new
716/// packet, though the original packet's bytes stay in the base.
717///
718/// Shared by [`Update::set_metadata`] and its asynchronous counterpart.
719pub fn set_metadata_with(
720    overlay: &mut Overlay,
721    existing_info: Option<(ObjRef, Dict)>,
722    xmp_ref: Option<ObjRef>,
723    meta: Metadata,
724) -> Result<()> {
725    let (target, existing_dict) = match existing_info {
726        Some((r, dict)) => (r, Some(dict)),
727        None => (overlay.reserve(), None),
728    };
729    let (dict, merged) = merge_metadata(existing_dict, &meta);
730    overlay.set(target, Object::Dict(dict));
731    overlay.set_info(target);
732    let Some(xmp_ref) = xmp_ref else {
733        return Ok(());
734    };
735    overlay.set(xmp_ref, xmp_metadata_stream(&merged));
736    Ok(())
737}
738
739/// `existing` (`None` starts from an empty dictionary) with every `Some`
740/// field of `meta` applied: a `Some` field overwrites its key
741/// (`Some(String::new())` writes an empty string), a `None` field leaves
742/// whatever key was already there. Also returns that merged dictionary read
743/// back into a [`Metadata`] (text fields via `decode_text_string`, dates via
744/// [`Date::parse_pdf`], an unparseable date simply dropping out), for
745/// [`xmp_metadata_stream`]: any XMP property outside those eight fields is
746/// not carried into a rebuilt packet.
747///
748/// Shared by [`set_metadata_with`] and [`crate::assemble::rewrite_with_metadata`].
749pub(crate) fn merge_metadata(existing: Option<Dict>, meta: &Metadata) -> (Dict, Metadata) {
750    let mut dict = existing.unwrap_or_default();
751    apply_metadata_fields(&mut dict, meta);
752    let merged = metadata_from_info(&dict);
753    (dict, merged)
754}
755
756/// A fresh, unfiltered `/Type /Metadata /Subtype /XML` stream over `meta`'s
757/// XMP packet, ready to stage into an [`Overlay`] or substitute into an
758/// import.
759pub(crate) fn xmp_metadata_stream(meta: &Metadata) -> Object {
760    let mut xmp_dict = Dict::new();
761    xmp_dict.insert(name("Type"), Object::Name(name("Metadata")));
762    xmp_dict.insert(name("Subtype"), Object::Name(name("XML")));
763    Object::Stream(Stream {
764        dict: xmp_dict,
765        data: crate::xmp::packet(meta),
766    })
767}
768
769/// `dict` with every value resolved against `doc`: an indirect value such
770/// as `/Title 12 0 R` becomes the string object it points to, so a field
771/// [`merge_metadata`] keeps (a `None` field in the merge) still reads back
772/// as text rather than silently vanishing from a rebuilt XMP packet. A
773/// value whose reference chain fails to resolve (an unreadable target, or
774/// a cycle) is kept as given.
775pub(crate) fn resolve_dict(doc: &Document, dict: &Dict) -> Dict {
776    let mut out = Dict::new();
777    for (key, value) in dict.iter() {
778        let resolved = doc.resolve(value).unwrap_or_else(|_| value.clone());
779        out.insert(key.clone(), resolved);
780    }
781    out
782}
783
784/// `doc`'s catalog's `/Metadata` entry, when it is an indirect reference.
785/// `None` for a catalog with no `/Metadata`, or one that reads as a direct
786/// stream rather than a reference.
787pub(crate) fn catalog_metadata_ref(doc: &Document, root: ObjRef) -> Option<ObjRef> {
788    let catalog = doc.get(root).ok()?;
789    match catalog.as_dict()?.get("Metadata")? {
790        Object::Ref(r) => Some(*r),
791        _ => None,
792    }
793}
794
795/// Writes every `Some` field of `meta` into `dict` under its `/Info` key;
796/// a `None` field is left untouched.
797fn apply_metadata_fields(dict: &mut Dict, meta: &Metadata) {
798    let texts = [
799        ("Title", &meta.title),
800        ("Author", &meta.author),
801        ("Subject", &meta.subject),
802        ("Keywords", &meta.keywords),
803        ("Creator", &meta.creator),
804        ("Producer", &meta.producer),
805    ];
806    for (key, value) in texts {
807        if let Some(value) = value {
808            dict.insert(name(key), text_string(value));
809        }
810    }
811    let dates = [
812        ("CreationDate", meta.creation_date),
813        ("ModDate", meta.modification_date),
814    ];
815    for (key, value) in dates {
816        if let Some(date) = value {
817            dict.insert(name(key), Object::String(date.to_pdf_string().into_bytes()));
818        }
819    }
820}
821
822/// Reads an `/Info` dictionary back into a [`Metadata`]: text fields via
823/// `decode_text_string`, dates via [`Date::parse_pdf`]. A missing or
824/// unparseable field is simply `None`.
825fn metadata_from_info(dict: &Dict) -> Metadata {
826    Metadata {
827        title: info_text(dict, "Title"),
828        author: info_text(dict, "Author"),
829        subject: info_text(dict, "Subject"),
830        keywords: info_text(dict, "Keywords"),
831        creator: info_text(dict, "Creator"),
832        producer: info_text(dict, "Producer"),
833        creation_date: info_date(dict, "CreationDate"),
834        modification_date: info_date(dict, "ModDate"),
835    }
836}
837
838/// `dict[key]` decoded as a text string, when present and a string.
839fn info_text(dict: &Dict, key: &str) -> Option<String> {
840    Some(decode_text_string(dict.get(key)?.as_str_bytes()?))
841}
842
843/// `dict[key]` decoded and parsed as a PDF date, when present, a string,
844/// and a valid date.
845fn info_date(dict: &Dict, key: &str) -> Option<Date> {
846    Date::parse_pdf(&decode_text_string(dict.get(key)?.as_str_bytes()?))
847}
848
849/// The base's length as an update's write position, plus whether a pad
850/// newline must be inserted first: an object header may not follow
851/// directly after `%%EOF` unless the base already ends on a line
852/// terminator (`\n` or `\r`).
853pub fn start_offset(base: &[u8]) -> (u64, bool) {
854    let pad = !matches!(base.last(), Some(b'\n') | Some(b'\r'));
855    (base.len() as u64 + u64::from(pad), pad)
856}
857
858/// A base document plus the update section being built over it.
859pub struct Update<'a> {
860    doc: &'a Document,
861    overlay: Overlay,
862}
863
864impl<'a> Update<'a> {
865    /// Opens `doc` for an update: refuses an encrypted base or one missing
866    /// `/Root` or a `startxref` to chain the appended section's `/Prev` to.
867    pub fn new(doc: &'a Document) -> Result<Update<'a>> {
868        let base = OverlayBase::from_document(doc)?;
869        Ok(Update {
870            doc,
871            overlay: Overlay::new(base),
872        })
873    }
874
875    /// Sets an object under its own number, whether new or a replacement
876    /// of one already in the base.
877    pub fn set(&mut self, r: ObjRef, obj: Object) {
878        self.overlay.set(r, obj);
879    }
880
881    /// Marks `r` free in the appended section's cross-reference data.
882    pub fn remove(&mut self, r: ObjRef) {
883        self.overlay.remove(r);
884    }
885
886    /// Allocates the next free object number without storing anything
887    /// under it yet.
888    pub fn reserve(&mut self) -> ObjRef {
889        self.overlay.reserve()
890    }
891
892    /// The update section under construction.
893    pub fn overlay(&self) -> &Overlay {
894        &self.overlay
895    }
896
897    /// Merges `meta` into the base document's `/Info` dictionary: the ref
898    /// comes from the overlay's own info ref when a prior call set one,
899    /// else the base's; the dictionary itself always comes from the base
900    /// document (never from a prior call's staged fields, so two calls on
901    /// one `Update` do not compound; on a base without `/Info`, a call
902    /// starts from a fresh dictionary). When the catalog already names an
903    /// XMP packet, it is rewritten from the merged fields. See
904    /// [`set_metadata_with`] for the merge and rewrite rules.
905    pub fn set_metadata(&mut self, meta: Metadata) -> Result<()> {
906        let info_ref = self.overlay.info.or(self.overlay.base.info);
907        let existing_info = info_ref.and_then(|r| {
908            let dict = self.doc.get(r).ok()?.as_dict()?.clone();
909            Some((r, resolve_dict(self.doc, &dict)))
910        });
911        let xmp_ref = catalog_metadata_ref(self.doc, self.overlay.base.root);
912        set_metadata_with(&mut self.overlay, existing_info, xmp_ref, meta)
913    }
914
915    /// The base bytes, whether a pad newline goes before the appended
916    /// section, and the section itself, computed together so a refused
917    /// update (or any other failure) is known before anything is written
918    /// anywhere.
919    fn parts(&self) -> Result<(&[u8], bool, Vec<u8>)> {
920        let base = self.doc.bytes();
921        let (start, pad) = start_offset(base);
922        let section = self.overlay.section(start)?;
923        Ok((base, pad, section))
924    }
925
926    /// Writes the base bytes, a pad newline when the base needs one, and
927    /// the appended section into `out`. The section is built before any
928    /// byte reaches `out`, so a refused update (or any other failure)
929    /// writes nothing at all.
930    pub fn append_into(&self, mut out: impl std::io::Write) -> Result<()> {
931        let (base, pad, section) = self.parts()?;
932        out.write_all(base)?;
933        if pad {
934            out.write_all(b"\n")?;
935        }
936        out.write_all(&section)?;
937        Ok(())
938    }
939
940    /// [`Update::append_into`] to a new file at `path`: the file is
941    /// created only once the update is known to build, so a refused
942    /// update leaves no file behind at all.
943    pub fn save(&self, path: impl AsRef<std::path::Path>) -> Result<()> {
944        let (base, pad, section) = self.parts()?;
945        let mut file = std::fs::File::create(path)?;
946        file.write_all(base)?;
947        if pad {
948            file.write_all(b"\n")?;
949        }
950        file.write_all(&section)?;
951        Ok(())
952    }
953
954    /// The base bytes followed by the update section, as one buffer.
955    pub fn bytes(&self) -> Result<Vec<u8>> {
956        let mut out = Vec::new();
957        self.append_into(&mut out)?;
958        Ok(out)
959    }
960}
961
962/// One row of the appended section's cross-reference data: an object
963/// stored at a byte offset, or a freed number chained to the next free
964/// number in the section's own free list (entry 0 when it is the head).
965#[derive(Debug, Clone, Copy)]
966enum Row {
967    InFile(ObjRef, usize),
968    Free { num: u32, gen: u16, next: u32 },
969}
970
971impl Row {
972    fn num(&self) -> u32 {
973        match self {
974            Row::InFile(r, _) => r.num,
975            Row::Free { num, .. } => *num,
976        }
977    }
978}
979
980/// Splits `rows`, already sorted ascending by object number, into maximal
981/// runs of consecutive numbers, as `(run start index, run length)` pairs.
982/// Shared by the classic table's subsections and the xref stream's
983/// `/Index` pairs, so both group the same way.
984fn contiguous_runs(rows: &[Row]) -> Vec<(usize, usize)> {
985    let mut runs = Vec::new();
986    let mut begin = 0;
987    while begin < rows.len() {
988        let mut end = begin + 1;
989        while end < rows.len() && rows[end].num() == rows[end - 1].num() + 1 {
990            end += 1;
991        }
992        runs.push((begin, end - begin));
993        begin = end;
994    }
995    runs
996}
997
998/// The appended trailer's `/ID`: the base's first half kept verbatim, the
999/// second half replaced by the first 16 bytes of a SHA-256 over the first
1000/// half's bytes, the base's `/Prev` offset as little-endian bytes, `body`
1001/// (the section's serialized objects, built before its xref part), and
1002/// finally each of `freed`'s `(num, gen)` pairs in order (`num` then `gen`,
1003/// both little-endian), so a frees-only update, whose `body` is empty,
1004/// still rotates by what it freed rather than staying fixed. `None` when
1005/// the base carries no `/ID` array with a string first element, in which
1006/// case the appended trailer omits the key entirely.
1007fn rotated_id(base: &OverlayBase, body: &[u8], freed: &[ObjRef]) -> Option<Object> {
1008    let Some(Object::Array(halves)) = &base.id else {
1009        return None;
1010    };
1011    let Some(Object::String(first)) = halves.first() else {
1012        return None;
1013    };
1014    let mut hasher = Sha256::new();
1015    hasher.update(first);
1016    hasher.update(&base.prev.to_le_bytes());
1017    hasher.update(body);
1018    for r in freed {
1019        hasher.update(&r.num.to_le_bytes());
1020        hasher.update(&r.gen.to_le_bytes());
1021    }
1022    let digest = hasher.finalize();
1023    Some(Object::Array(vec![
1024        Object::String(first.clone()),
1025        Object::String(digest[..16].to_vec()),
1026    ]))
1027}
1028
1029/// A cross-reference stream as the section's last object: one row per
1030/// object of the update (or per freed number) plus one for the stream
1031/// itself, and `/Index` pairs one per contiguous run of object numbers.
1032fn finish_stream(
1033    out: &mut Vec<u8>,
1034    start: u64,
1035    mut rows: Vec<Row>,
1036    mut dict: Dict,
1037    mut next: u32,
1038) -> Result<()> {
1039    let xref_ref = ObjRef { num: next, gen: 0 };
1040    next += 1;
1041    let xref_offset = start as usize + out.len();
1042    rows.push(Row::InFile(xref_ref, xref_offset));
1043    rows.sort_by_key(Row::num);
1044    let runs = contiguous_runs(&rows);
1045    let mut index = Vec::with_capacity(runs.len() * 2);
1046    for (begin, len) in runs {
1047        index.push(Object::Int(i64::from(rows[begin].num())));
1048        index.push(Object::Int(len as i64));
1049    }
1050    let mut data = Vec::with_capacity(rows.len() * 7);
1051    for row in &rows {
1052        match row {
1053            Row::InFile(r, offset) => {
1054                data.push(1);
1055                data.extend_from_slice(&field_offset(*offset)?.to_be_bytes());
1056                data.extend_from_slice(&r.gen.to_be_bytes());
1057            }
1058            Row::Free {
1059                gen,
1060                next: free_next,
1061                ..
1062            } => {
1063                data.push(0);
1064                data.extend_from_slice(&free_next.to_be_bytes());
1065                data.extend_from_slice(&gen.to_be_bytes());
1066            }
1067        }
1068    }
1069    dict.insert(name("Type"), Object::Name(name("XRef")));
1070    dict.insert(name("Size"), Object::Int(i64::from(next)));
1071    dict.insert(
1072        name("W"),
1073        Object::Array(vec![Object::Int(1), Object::Int(4), Object::Int(2)]),
1074    );
1075    dict.insert(name("Index"), Object::Array(index));
1076    write_indirect(out, xref_ref, &Object::Stream(Stream { dict, data }))?;
1077    out.extend_from_slice(format!("startxref\n{xref_offset}\n%%EOF\n").as_bytes());
1078    Ok(())
1079}
1080
1081/// A classic `xref` table with one subsection per run of consecutive
1082/// object numbers, then the `trailer` dictionary. A freed row uses `f` in
1083/// place of `n`, its first field naming the next free number in the
1084/// section's own chain rather than a byte offset.
1085fn finish_table(
1086    out: &mut Vec<u8>,
1087    start: u64,
1088    rows: &[Row],
1089    mut dict: Dict,
1090    size: u32,
1091) -> Result<()> {
1092    let xref_offset = start as usize + out.len();
1093    out.extend_from_slice(b"xref\n");
1094    for (begin, len) in contiguous_runs(rows) {
1095        out.extend_from_slice(format!("{} {}\n", rows[begin].num(), len).as_bytes());
1096        for row in &rows[begin..begin + len] {
1097            match row {
1098                Row::InFile(r, offset) => out.extend_from_slice(
1099                    format!("{:010} {:05} n \n", table_offset(*offset)?, r.gen).as_bytes(),
1100                ),
1101                Row::Free { gen, next, .. } => {
1102                    out.extend_from_slice(format!("{next:010} {gen:05} f \n").as_bytes())
1103                }
1104            }
1105        }
1106    }
1107    dict.insert(name("Size"), Object::Int(i64::from(size)));
1108    out.extend_from_slice(b"trailer\n");
1109    serialize_dict(&dict, out)?;
1110    out.extend_from_slice(format!("\nstartxref\n{xref_offset}\n%%EOF\n").as_bytes());
1111    Ok(())
1112}
1113
1114/// Emits `num gen obj` through `endobj`; a stream carries a direct
1115/// `/Length` of its stored byte count.
1116fn write_indirect(out: &mut Vec<u8>, r: ObjRef, obj: &Object) -> Result<()> {
1117    out.extend_from_slice(format!("{} {} obj\n", r.num, r.gen).as_bytes());
1118    match obj {
1119        Object::Stream(s) => {
1120            let mut dict = s.dict.clone();
1121            dict.insert(name("Length"), Object::Int(s.data.len() as i64));
1122            serialize_dict(&dict, out)?;
1123            out.extend_from_slice(b"\nstream\n");
1124            out.extend_from_slice(&s.data);
1125            out.extend_from_slice(b"\nendstream\nendobj\n");
1126        }
1127        direct => {
1128            serialize_object(direct, out)?;
1129            out.extend_from_slice(b"\nendobj\n");
1130        }
1131    }
1132    Ok(())
1133}
1134
1135/// An uncompressed stream with no filter of its own.
1136fn plain_stream(data: Vec<u8>) -> Stream {
1137    Stream {
1138        dict: Dict::new(),
1139        data,
1140    }
1141}
1142
1143pub(crate) fn deflate(data: &[u8]) -> Result<Vec<u8>> {
1144    let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
1145    encoder.write_all(data)?;
1146    Ok(encoder.finish()?)
1147}
1148
1149/// A byte position as the 4-byte offset field of a cross-reference stream.
1150fn field_offset(position: usize) -> Result<u32> {
1151    u32::try_from(position)
1152        .map_err(|_| Error::Other("file offset exceeds the 4-byte xref field".to_string()))
1153}
1154
1155/// A byte position as the 10-digit offset field of a classic xref table.
1156fn table_offset(position: usize) -> Result<usize> {
1157    if position as u64 <= 9_999_999_999 {
1158        return Ok(position);
1159    }
1160    Err(Error::Other(
1161        "file offset exceeds the 10-digit xref table field".to_string(),
1162    ))
1163}
1164
1165fn name(text: &str) -> Name {
1166    Name(text.to_string())
1167}
1168
1169pub(crate) fn core_error(error: pdfboss_core::Error) -> Error {
1170    Error::Other(error.to_string())
1171}
1172
1173#[cfg(test)]
1174mod tests {
1175    use super::*;
1176
1177    #[test]
1178    fn offset_integer_keeps_offsets_that_fit_and_refuses_the_rest() {
1179        assert!(matches!(offset_integer("Prev", 521), Ok(Object::Int(521))));
1180        assert!(matches!(
1181            offset_integer("XRefStm", i64::MAX as u64),
1182            Ok(Object::Int(i64::MAX))
1183        ));
1184        assert!(matches!(
1185            offset_integer("XRefStm", u64::MAX),
1186            Err(Error::Other(msg)) if msg.contains("/XRefStm")
1187        ));
1188    }
1189}