Skip to main content

pdfboss_write/
assemble.rs

1//! Merging documents into one fresh output (ISO 32000 §7.7.3, page tree):
2//! selected pages from each source, gathered in argument order under a
3//! single new `/Pages` node.
4
5use pdfboss_core::{Dict, Document, Name, Object};
6#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
7use pdfboss_core::{Encryptor, Permissions};
8
9use crate::error::{Error, Result};
10use crate::importer::Importer;
11use crate::pdf::Metadata;
12use crate::update::{
13    catalog_metadata_ref, core_error, merge_metadata, resolve_dict, xmp_metadata_stream,
14};
15use crate::writer::{WriteOptions, Writer};
16
17/// Assembles `inputs` into one document: each source's selected pages
18/// (`None` takes every page), gathered in argument order under a fresh
19/// `/Pages` node. The catalog and page tree are new; no `/Info` is set and
20/// no `/ID` is inherited (the writer derives its own from the emitted
21/// content). Document-level trees of the inputs -- outlines, names,
22/// optional content -- are not carried, since only individual pages are
23/// imported. A locked input is refused, the same way a lone import would
24/// be; an already password-opened encrypted input copies its plaintext
25/// content across like any unencrypted source.
26pub fn merge_documents(
27    inputs: &[(&Document, Option<&[usize]>)],
28    options: WriteOptions,
29) -> Result<Vec<u8>> {
30    let mut writer = Writer::new(options);
31    let pages_ref = writer.reserve();
32    let mut kids = Vec::new();
33    for (source, selection) in inputs {
34        let mut importer = Importer::new(&mut writer, source)?;
35        let indices: Vec<usize> = match selection {
36            Some(indices) => indices.to_vec(),
37            None => (0..source.page_count()).collect(),
38        };
39        for index in indices {
40            kids.push(importer.page(index, pages_ref)?);
41        }
42    }
43    if kids.is_empty() {
44        return Err(Error::Other(
45            "a document needs at least one page".to_string(),
46        ));
47    }
48    let mut tree = Dict::new();
49    tree.insert(name("Type"), Object::Name(name("Pages")));
50    tree.insert(
51        name("Kids"),
52        Object::Array(kids.iter().copied().map(Object::Ref).collect()),
53    );
54    tree.insert(name("Count"), Object::Int(kids.len() as i64));
55    writer.fill(pages_ref, Object::Dict(tree))?;
56    let mut catalog = Dict::new();
57    catalog.insert(name("Type"), Object::Name(name("Catalog")));
58    catalog.insert(name("Pages"), Object::Ref(pages_ref));
59    let root = writer.put(Object::Dict(catalog));
60    writer.finish(root)
61}
62
63/// A `Name` from a string literal.
64fn name(text: &str) -> Name {
65    Name(text.to_string())
66}
67
68/// Rewrites `doc` fresh, like [`merge_documents`] but keeping the whole
69/// document rather than assembling selected pages into a new tree: every
70/// object the catalog and `/Info` reach is copied over, and each of
71/// `pages` (0-based indices) gets its own leaf dictionary substituted with
72/// `/Rotate` set to its current effective rotation plus `by`, normalized
73/// with `rem_euclid(360)`. Substitution keys by the source object
74/// reference, so a selected page with no object of its own (inlined
75/// directly into `/Kids`) is refused, naming its 1-based page number:
76/// pdfboss does not yet restructure such a page into one with its own
77/// object. `by` must be a multiple of 90; anything else is refused before
78/// any object is copied.
79pub fn rotate_rewrite(
80    doc: &Document,
81    pages: &[usize],
82    by: i32,
83    options: WriteOptions,
84) -> Result<Vec<u8>> {
85    if by % 90 != 0 {
86        return Err(Error::Other(
87            "rotation must be a multiple of 90 degrees".to_string(),
88        ));
89    }
90    let mut writer = Writer::new(options);
91    let mut importer = Importer::new(&mut writer, doc)?;
92    let new_info = doc
93        .xref()
94        .trailer
95        .get_ref("Info")
96        .map(|info| importer.reference(info));
97    for &index in pages {
98        let page = doc.page(index).map_err(core_error)?;
99        let Some(page_ref) = page.object_ref() else {
100            return Err(Error::Other(format!(
101                "page {} is inlined into /Kids and cannot be edited in place; \
102                 pdfboss does not yet restructure such pages to rotate them",
103                index + 1
104            )));
105        };
106        let mut dict = page.dict().clone();
107        let rotate = (page.rotate + by).rem_euclid(360);
108        dict.insert(name("Rotate"), Object::Int(i64::from(rotate)));
109        let body = importer.copy(&Object::Dict(dict))?;
110        importer.substitute(page_ref, body);
111    }
112    let new_root = importer.document()?;
113    if let Some(new_info) = new_info {
114        writer.set_info(new_info);
115    }
116    writer.finish(new_root)
117}
118
119/// The whole document through the [`Writer`]: recompressed, object streams
120/// per `options`, unreachable objects and earlier update sections left
121/// behind. Carries `/Info` along the same way [`rotate_rewrite`] does: it
122/// is a trailer key `Importer::document` alone can never reach, since
123/// nothing in the catalog's own graph points at it.
124pub fn rewrite_document(doc: &Document, options: WriteOptions) -> Result<Vec<u8>> {
125    rewrite_into(Writer::new(options), doc)
126}
127
128/// Shared by [`rewrite_document`] and [`encrypt_document`]: the whole
129/// reachable graph from `doc`'s catalog copied into `writer`, already
130/// constructed plain or encrypting, carrying `/Info` along the same way
131/// [`rotate_rewrite`] does.
132fn rewrite_into(mut writer: Writer, doc: &Document) -> Result<Vec<u8>> {
133    let mut importer = Importer::new(&mut writer, doc)?;
134    let new_info = doc
135        .xref()
136        .trailer
137        .get_ref("Info")
138        .map(|info| importer.reference(info));
139    let new_root = importer.document()?;
140    if let Some(new_info) = new_info {
141        writer.set_info(new_info);
142    }
143    writer.finish(new_root)
144}
145
146/// [`rewrite_document`], writing through an encrypting [`Writer`] instead
147/// of a plain one: every copied string and stream is AES-256 protected
148/// under `user_password` and `owner_password` (ISO 32000-2 §7.6.4.3), with
149/// `permissions` as the restrictions a reader opening under the user
150/// password is granted. An empty `owner_password` falls back to
151/// `user_password`; both empty is refused, since neither password would
152/// then protect the file at all. `doc` is refused when
153/// [`Document::is_locked`], the same refusal [`Importer::new`] already
154/// raises. An already password-opened encrypted `doc` is fine: its
155/// content already reads as plaintext through `Document::get`, so it
156/// copies across like any unencrypted source and gets encrypted afresh
157/// under the new passwords. Also fails when the operating system's random
158/// source cannot be read, the one way [`Encryptor::aes256`] itself fails.
159///
160/// Not available on `wasm32-unknown-unknown`: it builds its `Encryptor`
161/// with [`Encryptor::aes256`], which needs the operating system's random
162/// source. Construct an `Encryptor` with `Encryptor::aes256_with_rng` and
163/// [`Writer::new_encrypted`] directly there instead.
164#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
165pub fn encrypt_document(
166    doc: &Document,
167    user_password: &str,
168    owner_password: &str,
169    permissions: Permissions,
170    options: WriteOptions,
171) -> Result<Vec<u8>> {
172    if user_password.is_empty() && owner_password.is_empty() {
173        return Err(Error::Other(
174            "user_password and owner_password cannot both be empty".to_string(),
175        ));
176    }
177    let owner_password = if owner_password.is_empty() {
178        user_password
179    } else {
180        owner_password
181    };
182    let (encryptor, encrypt_dict) =
183        Encryptor::aes256(user_password, owner_password, permissions).map_err(core_error)?;
184    rewrite_into(Writer::new_encrypted(options, encryptor, encrypt_dict), doc)
185}
186
187/// [`rewrite_document`], named for the decryption it performs when `doc`
188/// was opened under a password: its content already reads as plaintext
189/// through `Document::get`, and the fresh [`Writer`] this builds carries
190/// no `/Encrypt` of its own, so the output is plainly unencrypted no
191/// matter what protected the input. Refuses a [`Document::is_locked`]
192/// `doc` exactly as [`Importer::new`] does, a second safeguard behind
193/// `Document::load_with_password`'s own refusal of a wrong or missing
194/// password: that refusal happens before a `Document` exists, so a locked
195/// one never reaches this function through the public load path in the
196/// first place.
197pub fn decrypt_document(doc: &Document, options: WriteOptions) -> Result<Vec<u8>> {
198    rewrite_document(doc, options)
199}
200
201/// [`rewrite_document`], first replacing `/Info` (and, when the catalog
202/// names one, the XMP packet) with `meta` merged over whatever the base
203/// already carried: the same merge [`crate::update::set_metadata_with`]
204/// performs for an appended update, applied here as substitutions into the
205/// copied graph instead. An existing `/Info` object is translated into the
206/// target's own numbering via [`Importer::copy`] before the substitution
207/// (`resolve_dict` only chases a value's own top-level reference, so a
208/// nested or unresolvable one still names a source object; `copy`
209/// translates it correctly, the same pattern [`rotate_rewrite`] uses for a
210/// page body). A base with no `/Info` gets a fresh one put directly into
211/// the writer, since there is no source object to substitute into and
212/// nothing in a freshly built dict can name one.
213pub fn rewrite_with_metadata(
214    doc: &Document,
215    meta: Metadata,
216    options: WriteOptions,
217) -> Result<Vec<u8>> {
218    let mut writer = Writer::new(options);
219    let mut importer = Importer::new(&mut writer, doc)?;
220    let trailer = &doc.xref().trailer;
221    let root = trailer.get_ref("Root").ok_or(Error::MissingRoot)?;
222    let info_ref = trailer.get_ref("Info");
223    let existing_dict = info_ref.and_then(|r| {
224        let dict = doc.get(r).ok()?.as_dict()?.clone();
225        Some(resolve_dict(doc, &dict))
226    });
227    let xmp_ref = catalog_metadata_ref(doc, root);
228    let (dict, merged) = merge_metadata(existing_dict, &meta);
229
230    let new_info_target = match info_ref {
231        Some(r) => {
232            let target = importer.reference(r);
233            let body = importer.copy(&Object::Dict(dict.clone()))?;
234            importer.substitute(r, body);
235            Some(target)
236        }
237        None => None,
238    };
239    if let Some(r) = xmp_ref {
240        importer.substitute(r, xmp_metadata_stream(&merged));
241    }
242
243    let new_root = importer.document()?;
244    let new_info = match new_info_target {
245        Some(target) => target,
246        None => writer.put(Object::Dict(dict)),
247    };
248    writer.set_info(new_info);
249    writer.finish(new_root)
250}
251
252/// Consecutive chunks of `every` pages, each a fresh document. `every` must
253/// be at least 1; the last chunk carries whatever remains, so no chunk is
254/// ever empty.
255pub fn split_document(doc: &Document, every: usize, options: WriteOptions) -> Result<Vec<Vec<u8>>> {
256    if every == 0 {
257        return Err(Error::Other(
258            "every must be at least 1 page per part".to_string(),
259        ));
260    }
261    let total = doc.page_count();
262    let mut parts = Vec::new();
263    let mut start = 0;
264    while start < total {
265        let end = (start + every).min(total);
266        let indices: Vec<usize> = (start..end).collect();
267        parts.push(merge_documents(&[(doc, Some(&indices))], options)?);
268        start = end;
269    }
270    Ok(parts)
271}
272
273#[cfg(test)]
274mod tests {
275    use pdfboss_core::xref::{parse_section_at, startxref, XrefEntry};
276    use pdfboss_output::{extract_text, ReadingOrder};
277    use pdfboss_testkit::{encrypted_rc4_doc, multi_page_doc, PdfBuilder};
278
279    use crate::pdf::{Metadata, Page, PageSize, Pdf};
280    use crate::update::Update;
281    use crate::writer::XrefStyle;
282
283    use super::*;
284
285    #[test]
286    fn merge_keeps_sources_in_argument_order() {
287        let a = Document::load(multi_page_doc(&["a1", "a2"])).expect("doc a loads");
288        let b = Document::load(multi_page_doc(&["b1", "b2"])).expect("doc b loads");
289        let bytes = merge_documents(&[(&a, None), (&b, None)], WriteOptions::default())
290            .expect("merge succeeds");
291        let merged = Document::load(bytes).expect("merged document loads");
292        assert_eq!(merged.page_count(), 4);
293        let texts: Vec<String> = (0..4)
294            .map(|i| {
295                let page = merged.page(i).expect("page exists");
296                extract_text(&merged, &page, ReadingOrder::Content).expect("text extracts")
297            })
298            .collect();
299        assert!(texts[0].contains("a1"), "page 0: {:?}", texts[0]);
300        assert!(texts[1].contains("a2"), "page 1: {:?}", texts[1]);
301        assert!(texts[2].contains("b1"), "page 2: {:?}", texts[2]);
302        assert!(texts[3].contains("b2"), "page 3: {:?}", texts[3]);
303    }
304
305    #[test]
306    fn a_range_selects_and_reorders_pages() {
307        let doc = Document::load(multi_page_doc(&["one", "two", "three"])).expect("doc loads");
308        let bytes = merge_documents(&[(&doc, Some(&[2, 0]))], WriteOptions::default())
309            .expect("merge succeeds");
310        let merged = Document::load(bytes).expect("merged document loads");
311        assert_eq!(merged.page_count(), 2);
312        let first = merged.page(0).expect("first page exists");
313        let second = merged.page(1).expect("second page exists");
314        assert!(extract_text(&merged, &first, ReadingOrder::Content)
315            .unwrap()
316            .contains("three"));
317        assert!(extract_text(&merged, &second, ReadingOrder::Content)
318            .unwrap()
319            .contains("one"));
320    }
321
322    /// The fixture's empty user password opens transparently, so `doc`
323    /// carries a working decryptor and is not locked: `merge_documents`
324    /// now accepts it, copying its already-decrypted content across like
325    /// any unencrypted source, and the copied page's text still reads
326    /// correctly in the plain output.
327    #[test]
328    fn merge_documents_accepts_a_password_opened_encrypted_source() {
329        let doc = Document::load(encrypted_rc4_doc("secret")).expect("empty-password doc loads");
330        let bytes = merge_documents(&[(&doc, None)], WriteOptions::default())
331            .expect("a password-opened encrypted source is not locked, so merge succeeds");
332        let merged = Document::load(bytes).expect("merged document loads");
333        assert!(
334            !merged.is_encrypted(),
335            "the merged output carries no /Encrypt"
336        );
337        let page = merged.page(0).expect("page 0 exists");
338        let text = extract_text(&merged, &page, ReadingOrder::Content).expect("text extracts");
339        assert!(text.contains("secret"), "{text:?}");
340    }
341
342    #[test]
343    fn split_makes_parts_of_the_requested_size_and_a_shorter_last_part() {
344        let doc = Document::load(multi_page_doc(&["one", "two", "three"])).expect("doc loads");
345        let parts = split_document(&doc, 2, WriteOptions::default()).expect("split succeeds");
346        assert_eq!(parts.len(), 2);
347
348        let first = Document::load(parts[0].clone()).expect("first part loads");
349        assert_eq!(first.page_count(), 2);
350        let texts: Vec<String> = (0..2)
351            .map(|i| {
352                let page = first.page(i).expect("page exists");
353                extract_text(&first, &page, ReadingOrder::Content).expect("text extracts")
354            })
355            .collect();
356        assert!(texts[0].contains("one"), "page 0: {:?}", texts[0]);
357        assert!(texts[1].contains("two"), "page 1: {:?}", texts[1]);
358
359        let second = Document::load(parts[1].clone()).expect("second part loads");
360        assert_eq!(second.page_count(), 1);
361        let page = second.page(0).expect("page exists");
362        let text = extract_text(&second, &page, ReadingOrder::Content).expect("text extracts");
363        assert!(text.contains("three"), "page 0: {:?}", text);
364    }
365
366    #[test]
367    fn split_larger_than_the_page_count_makes_one_part() {
368        let doc = Document::load(multi_page_doc(&["one", "two", "three"])).expect("doc loads");
369        let parts = split_document(&doc, 10, WriteOptions::default()).expect("split succeeds");
370        assert_eq!(parts.len(), 1);
371        let only = Document::load(parts[0].clone()).expect("part loads");
372        assert_eq!(only.page_count(), 3);
373    }
374
375    #[test]
376    fn split_rejects_zero_pages_per_part_with_an_honest_message() {
377        let doc = Document::load(multi_page_doc(&["one", "two", "three"])).expect("doc loads");
378        let result = split_document(&doc, 0, WriteOptions::default());
379        let Err(Error::Other(message)) = result else {
380            panic!("expected Error::Other, got {result:?}");
381        };
382        assert!(message.contains("every"), "message: {message}");
383    }
384
385    /// Rotating pages 1 and 3 of a three-page document by 90 degrees
386    /// clockwise substitutes each page's own object with its effective
387    /// rotation plus 90, leaving the untouched page at 0. Unlike the
388    /// append path, the whole document is copied fresh.
389    #[test]
390    fn rotate_rewrite_rotates_the_selected_pages() {
391        let doc = Document::load(multi_page_doc(&["one", "two", "three"])).expect("doc loads");
392        let bytes =
393            rotate_rewrite(&doc, &[0, 2], 90, WriteOptions::default()).expect("rotate succeeds");
394        let rotated = Document::load(bytes).expect("rotated document loads");
395        for (index, expected) in [90, 0, 90].iter().enumerate() {
396            let page = rotated.page(index).expect("page exists");
397            assert_eq!(page.rotate, *expected, "page {index}");
398        }
399    }
400
401    /// A page inlined directly into `/Kids`, with no object of its own, has
402    /// no reference to substitute a rewritten body onto: `rotate_rewrite`
403    /// refuses it, naming its 1-based page number, rather than silently
404    /// leaving it unrotated.
405    #[test]
406    fn rotate_rewrite_refuses_an_inline_page() {
407        let mut b = PdfBuilder::new();
408        b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
409        b.object(
410            2,
411            "<< /Type /Pages /Count 1 /Kids [ << /Type /Page /Parent 2 0 R \
412             /MediaBox [0 0 612 792] >> ] >>",
413        );
414        let doc = Document::load(b.build(1)).expect("doc loads");
415
416        let result = rotate_rewrite(&doc, &[0], 90, WriteOptions::default());
417        let Err(Error::Other(message)) = result else {
418            panic!("expected Error::Other, got {result:?}");
419        };
420        assert!(message.contains("page 1"), "message: {message}");
421        assert!(
422            message.contains("cannot be edited in place"),
423            "message: {message}"
424        );
425        assert!(
426            message.contains("does not yet restructure"),
427            "message: {message}"
428        );
429    }
430
431    /// A `by` that is not a multiple of 90 is refused before any object is
432    /// copied, rather than silently truncated or wrapped into a confusing
433    /// rotation.
434    #[test]
435    fn rotate_rewrite_refuses_a_non_multiple_of_90() {
436        let doc = Document::load(multi_page_doc(&["one"])).expect("doc loads");
437        let result = rotate_rewrite(&doc, &[0], 45, WriteOptions::default());
438        let Err(Error::Other(message)) = result else {
439            panic!("expected Error::Other, got {result:?}");
440        };
441        assert!(message.contains("multiple of 90"), "message: {message}");
442    }
443
444    /// A negative multiple of 90 stays legal: `rem_euclid(360)` normalizes
445    /// it into the usual 0..360 range instead of refusing it.
446    #[test]
447    fn rotate_rewrite_accepts_a_negative_multiple_of_90() {
448        let doc = Document::load(multi_page_doc(&["one"])).expect("doc loads");
449        let bytes =
450            rotate_rewrite(&doc, &[0], -90, WriteOptions::default()).expect("rotate succeeds");
451        let rotated = Document::load(bytes).expect("rotated document loads");
452        let page = rotated.page(0).expect("page exists");
453        assert_eq!(page.rotate, 270);
454    }
455
456    /// A rewrite carries `/Info` along: the reloaded catalog's trailer
457    /// still resolves an `/Info` dictionary, and its `/Title` still reads
458    /// the base document's title after rotation.
459    #[test]
460    fn rotate_rewrite_carries_info_along() {
461        let base = Pdf {
462            pages: vec![Page::new(PageSize::A4)],
463            metadata: Some(Metadata {
464                title: Some("Rotated Title".to_string()),
465                ..Metadata::default()
466            }),
467            ..Pdf::default()
468        }
469        .to_bytes()
470        .expect("base builds");
471        let doc = Document::load(base).expect("base loads");
472        assert!(
473            doc.xref().trailer.get_ref("Info").is_some(),
474            "the base's trailer must carry /Info for this test to exercise the carry"
475        );
476
477        let bytes =
478            rotate_rewrite(&doc, &[0], 90, WriteOptions::default()).expect("rotate succeeds");
479        let rotated = Document::load(bytes).expect("rotated document loads");
480        assert!(
481            rotated.xref().trailer.get_ref("Info").is_some(),
482            "the rewritten trailer still names an /Info dictionary"
483        );
484        assert_eq!(rotated.metadata().title.as_deref(), Some("Rotated Title"));
485    }
486
487    /// Counts non-free cross-reference entries: the objects a document
488    /// actually carries, whether stored directly or packed into an object
489    /// stream.
490    fn live_count(doc: &Document) -> usize {
491        doc.xref()
492            .iter()
493            .filter(|(_, entry)| !matches!(entry, XrefEntry::Free))
494            .count()
495    }
496
497    /// A rewrite carries `/Info` along, the same way [`rotate_rewrite`]
498    /// does: the reloaded trailer still resolves an `/Info` dictionary, and
499    /// its `/Title` still reads the base document's title.
500    #[test]
501    fn rewrite_document_carries_info_along() {
502        let base = Pdf {
503            pages: vec![Page::new(PageSize::A4)],
504            metadata: Some(Metadata {
505                title: Some("Rewritten Title".to_string()),
506                ..Metadata::default()
507            }),
508            ..Pdf::default()
509        }
510        .to_bytes()
511        .expect("base builds");
512        let doc = Document::load(base).expect("base loads");
513        assert!(
514            doc.xref().trailer.get_ref("Info").is_some(),
515            "the base's trailer must carry /Info for this test to exercise the carry"
516        );
517
518        let bytes = rewrite_document(&doc, WriteOptions::default()).expect("rewrite succeeds");
519        let rewritten = Document::load(bytes).expect("rewritten document loads");
520        assert!(
521            rewritten.xref().trailer.get_ref("Info").is_some(),
522            "the rewritten trailer still names an /Info dictionary"
523        );
524        assert_eq!(
525            rewritten.metadata().title.as_deref(),
526            Some("Rewritten Title")
527        );
528    }
529
530    /// A rewrite recomputes the whole object graph from the catalog and
531    /// `/Info` alone: an object neither one reaches is dropped, even though
532    /// the base carried it, and the pages that remain still read back.
533    #[test]
534    fn rewrite_document_drops_an_unreferenced_object_and_keeps_text() {
535        let options = WriteOptions {
536            xref: XrefStyle::Table,
537            compress: false,
538            object_streams: false,
539            version: (1, 7),
540        };
541        let mut b = PdfBuilder::new();
542        b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
543        b.object(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
544        b.object(
545            3,
546            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] \
547             /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>",
548        );
549        b.stream(4, "", b"BT /F1 12 Tf 72 720 Td (hello) Tj ET");
550        b.object(
551            5,
552            "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>",
553        );
554        b.object(6, "<< /Extra (unreferenced) >>");
555        let doc = Document::load(b.build(1)).expect("doc loads");
556        assert_eq!(
557            live_count(&doc),
558            6,
559            "the fixture carries the extra object alongside the reachable five"
560        );
561
562        let bytes = rewrite_document(&doc, options).expect("rewrite succeeds");
563        let rewritten = Document::load(bytes).expect("rewritten document loads");
564        assert_eq!(
565            live_count(&rewritten),
566            5,
567            "the unreferenced object must not survive the rewrite"
568        );
569
570        let page = rewritten.page(0).expect("page exists");
571        let text = extract_text(&rewritten, &page, ReadingOrder::Content).expect("text extracts");
572        assert!(text.contains("hello"), "text: {text:?}");
573    }
574
575    /// A base already carrying an appended update section (two
576    /// cross-reference sections chained by `/Prev`) collapses to one fresh
577    /// section: a rewrite always builds a whole new graph, never an append
578    /// of its own.
579    #[test]
580    fn rewrite_document_collapses_an_appended_update_into_one_section() {
581        let base = Pdf {
582            pages: vec![Page::new(PageSize::A4)],
583            ..Pdf::default()
584        }
585        .to_bytes()
586        .expect("base builds");
587        let base_doc = Document::load(base).expect("base loads");
588        let mut update = Update::new(&base_doc).expect("update opens");
589        let extra = update.reserve();
590        let mut dict = Dict::new();
591        dict.insert(name("Marker"), Object::Int(1));
592        update.set(extra, Object::Dict(dict));
593        let appended = update.bytes().expect("update appends");
594
595        let control_offset = startxref(&appended).expect("startxref present in the input");
596        let control_section =
597            parse_section_at(&appended, control_offset).expect("input section parses");
598        assert!(
599            control_section.prev.is_some(),
600            "the input must really carry a /Prev chain for this test to exercise the collapse"
601        );
602
603        let appended_doc = Document::load(appended).expect("appended document loads");
604        let bytes =
605            rewrite_document(&appended_doc, WriteOptions::default()).expect("rewrite succeeds");
606
607        let offset = startxref(&bytes).expect("startxref present");
608        let section = parse_section_at(&bytes, offset).expect("section parses");
609        assert!(
610            section.prev.is_none(),
611            "the rewrite must collapse the update chain into one section"
612        );
613    }
614
615    /// Rewriting with metadata merges `meta`'s `Some` fields over whatever
616    /// the base already carried, the same as an appended `set_metadata`,
617    /// but into a whole fresh file: the output cannot start with the
618    /// base's own bytes, since there is no append to preserve a prefix of.
619    #[test]
620    fn rewrite_with_metadata_merges_fields_into_a_fresh_file() {
621        let base = Pdf {
622            pages: vec![Page::new(PageSize::A4)],
623            metadata: Some(Metadata {
624                title: Some("Old".to_string()),
625                author: Some("Keep".to_string()),
626                ..Metadata::default()
627            }),
628            ..Pdf::default()
629        }
630        .to_bytes()
631        .expect("base builds");
632        let doc = Document::load(base.clone()).expect("base loads");
633
634        let bytes = rewrite_with_metadata(
635            &doc,
636            Metadata {
637                title: Some("New".to_string()),
638                ..Metadata::default()
639            },
640            WriteOptions::default(),
641        )
642        .expect("rewrite succeeds");
643        assert!(
644            !bytes.starts_with(&base[..]),
645            "a metadata rewrite must not merely append an update onto the base"
646        );
647
648        let rewritten = Document::load(bytes).expect("rewritten document loads");
649        let meta = rewritten.metadata();
650        assert_eq!(meta.title.as_deref(), Some("New"));
651        assert_eq!(meta.author.as_deref(), Some("Keep"));
652
653        let new_root = rewritten
654            .xref()
655            .trailer
656            .get_ref("Root")
657            .expect("rewritten trailer names /Root");
658        let catalog = rewritten.get(new_root).expect("catalog resolves");
659        let metadata_ref = catalog
660            .as_dict()
661            .expect("catalog is a dictionary")
662            .get_ref("Metadata")
663            .expect("the base's XMP packet must still be named");
664        let stream = rewritten
665            .get(metadata_ref)
666            .expect("metadata stream resolves");
667        let text = String::from_utf8(
668            stream
669                .as_stream()
670                .expect("metadata is a stream")
671                .data
672                .clone(),
673        )
674        .expect("packet is utf-8");
675        assert!(text.contains("New"), "packet: {text}");
676        assert!(text.contains("Keep"), "packet: {text}");
677        assert!(!text.contains("Old"), "packet: {text}");
678    }
679
680    /// A base with no `/Info` at all still gets one from
681    /// `rewrite_with_metadata`: the merge target is a fresh object put
682    /// directly into the writer, never an `Importer` substitution. A base
683    /// with no XMP packet either must not gain one: `set_metadata_with`'s
684    /// own rule (never build a fresh packet where none existed) applies
685    /// here too.
686    #[test]
687    fn rewrite_with_metadata_creates_info_when_absent() {
688        let base = Pdf {
689            pages: vec![Page::new(PageSize::A4)],
690            ..Pdf::default()
691        }
692        .to_bytes()
693        .expect("base builds");
694        let doc = Document::load(base).expect("base loads");
695
696        let bytes = rewrite_with_metadata(
697            &doc,
698            Metadata {
699                title: Some("Fresh".to_string()),
700                ..Metadata::default()
701            },
702            WriteOptions::default(),
703        )
704        .expect("rewrite succeeds");
705
706        let rewritten = Document::load(bytes).expect("rewritten document loads");
707        assert_eq!(rewritten.metadata().title.as_deref(), Some("Fresh"));
708
709        let new_root = rewritten
710            .xref()
711            .trailer
712            .get_ref("Root")
713            .expect("rewritten trailer names /Root");
714        let catalog = rewritten.get(new_root).expect("catalog resolves");
715        assert!(
716            catalog
717                .as_dict()
718                .expect("catalog is a dictionary")
719                .get("Metadata")
720                .is_none(),
721            "a base with no XMP packet must not gain one from a metadata rewrite"
722        );
723    }
724
725    /// A kept `/Info` value stored as an indirect reference must be
726    /// translated into the target's own numbering, not carried verbatim:
727    /// `resolve_dict` only chases a value's own top-level reference chain,
728    /// so the merged dict still names the source object directly, and
729    /// `Importer::substitute` fills bodies verbatim with no renumbering of
730    /// its own. Left untranslated, the raw source number would alias
731    /// whatever the target happens to number the same in the rewritten
732    /// file.
733    #[test]
734    fn rewrite_with_metadata_translates_a_kept_indirect_info_value() {
735        let mut w = Writer::new(WriteOptions {
736            xref: XrefStyle::Table,
737            ..WriteOptions::default()
738        });
739        let pages_root = w.reserve();
740        let page = w.reserve();
741
742        let mut page_dict = Dict::new();
743        page_dict.insert(name("Type"), Object::Name(name("Page")));
744        page_dict.insert(name("Parent"), Object::Ref(pages_root));
745        page_dict.insert(name("Resources"), Object::Dict(Dict::new()));
746        page_dict.insert(
747            name("MediaBox"),
748            Object::Array(vec![
749                Object::Int(0),
750                Object::Int(0),
751                Object::Int(612),
752                Object::Int(792),
753            ]),
754        );
755        w.fill(page, Object::Dict(page_dict))
756            .expect("page slot fills");
757
758        let mut pages_dict = Dict::new();
759        pages_dict.insert(name("Type"), Object::Name(name("Pages")));
760        pages_dict.insert(name("Kids"), Object::Array(vec![Object::Ref(page)]));
761        pages_dict.insert(name("Count"), Object::Int(1));
762        w.fill(pages_root, Object::Dict(pages_dict))
763            .expect("pages slot fills");
764
765        let title_ref = w.put(Object::String(b"Indirect Title".to_vec()));
766        let mut info = Dict::new();
767        info.insert(name("Title"), Object::Ref(title_ref));
768        let info_ref = w.put(Object::Dict(info));
769        w.set_info(info_ref);
770
771        let mut catalog = Dict::new();
772        catalog.insert(name("Type"), Object::Name(name("Catalog")));
773        catalog.insert(name("Pages"), Object::Ref(pages_root));
774        let root = w.put(Object::Dict(catalog));
775        let base = w.finish(root).expect("base finishes");
776        let doc = Document::load(base).expect("base loads");
777
778        let bytes = rewrite_with_metadata(
779            &doc,
780            Metadata {
781                author: Some("New Author".to_string()),
782                ..Metadata::default()
783            },
784            WriteOptions::default(),
785        )
786        .expect("rewrite succeeds");
787
788        let rewritten = Document::load(bytes).expect("rewritten document loads");
789        let meta = rewritten.metadata();
790        assert_eq!(
791            meta.title.as_deref(),
792            Some("Indirect Title"),
793            "a kept indirect /Info value must translate rather than alias"
794        );
795        assert_eq!(meta.author.as_deref(), Some("New Author"));
796
797        let page = rewritten.page(0).expect("page still resolves");
798        assert_eq!(
799            page.dict().get_name("Type"),
800            Some(&Name("Page".to_string())),
801            "the page object must not have been aliased by an untranslated /Info reference"
802        );
803    }
804
805    /// `resolve_dict` resolves a key's own top-level reference chain, but
806    /// never recurses into a value that is itself an array or a nested
807    /// dictionary: a reference held inside one survives the merge
808    /// untouched, still naming a source object. `rewrite_with_metadata`
809    /// must translate it into the target's own numbering rather than
810    /// substituting it verbatim, or the raw source number would alias
811    /// whatever the rewrite happens to number the same.
812    #[test]
813    fn rewrite_with_metadata_translates_a_reference_nested_in_an_info_value() {
814        let mut w = Writer::new(WriteOptions {
815            xref: XrefStyle::Table,
816            ..WriteOptions::default()
817        });
818        let pages_root = w.reserve();
819        let page = w.reserve();
820
821        let mut page_dict = Dict::new();
822        page_dict.insert(name("Type"), Object::Name(name("Page")));
823        page_dict.insert(name("Parent"), Object::Ref(pages_root));
824        page_dict.insert(name("Resources"), Object::Dict(Dict::new()));
825        page_dict.insert(
826            name("MediaBox"),
827            Object::Array(vec![
828                Object::Int(0),
829                Object::Int(0),
830                Object::Int(612),
831                Object::Int(792),
832            ]),
833        );
834        w.fill(page, Object::Dict(page_dict))
835            .expect("page slot fills");
836
837        let mut pages_dict = Dict::new();
838        pages_dict.insert(name("Type"), Object::Name(name("Pages")));
839        pages_dict.insert(name("Kids"), Object::Array(vec![Object::Ref(page)]));
840        pages_dict.insert(name("Count"), Object::Int(1));
841        w.fill(pages_root, Object::Dict(pages_dict))
842            .expect("pages slot fills");
843
844        let witness = w.put(Object::String(b"Witness".to_vec()));
845        let mut info = Dict::new();
846        info.insert(name("Title"), Object::String(b"Plain Title".to_vec()));
847        info.insert(
848            name("CustomRefs"),
849            Object::Array(vec![Object::Ref(witness)]),
850        );
851        let info_ref = w.put(Object::Dict(info));
852        w.set_info(info_ref);
853
854        let mut catalog = Dict::new();
855        catalog.insert(name("Type"), Object::Name(name("Catalog")));
856        catalog.insert(name("Pages"), Object::Ref(pages_root));
857        let root = w.put(Object::Dict(catalog));
858        let base = w.finish(root).expect("base finishes");
859        let doc = Document::load(base).expect("base loads");
860
861        let bytes = rewrite_with_metadata(
862            &doc,
863            Metadata {
864                author: Some("New Author".to_string()),
865                ..Metadata::default()
866            },
867            WriteOptions::default(),
868        )
869        .expect("rewrite succeeds");
870
871        let rewritten = Document::load(bytes).expect("rewritten document loads");
872        let new_info_ref = rewritten
873            .xref()
874            .trailer
875            .get_ref("Info")
876            .expect("rewritten trailer names /Info");
877        let info_dict = rewritten.get(new_info_ref).expect("info resolves");
878        let custom = info_dict
879            .as_dict()
880            .expect("info is a dictionary")
881            .get("CustomRefs")
882            .expect("CustomRefs survives the merge, untouched by the recognized fields");
883        let Object::Array(items) = custom else {
884            panic!("CustomRefs must still be an array, got {custom:?}");
885        };
886        let Object::Ref(witness_target) = items[0] else {
887            panic!(
888                "CustomRefs[0] must still be a reference, got {:?}",
889                items[0]
890            );
891        };
892        let resolved = rewritten
893            .get(witness_target)
894            .expect("the translated reference must resolve to a real object");
895        assert_eq!(
896            resolved.as_str_bytes(),
897            Some(&b"Witness"[..]),
898            "a reference nested inside an /Info value must translate into the \
899             target's own numbering, not alias whatever the rewrite happens to \
900             number the same"
901        );
902    }
903}