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