Skip to main content

pdfboss_write/
pdf.rs

1//! Document assembly: pages of canvas content, document metadata, and the
2//! save path. `Pdf` is a plain struct — the fields are the composition,
3//! and `Default` fills everything optional.
4
5use std::path::Path;
6
7use pdfboss_core::{Dict, Name, ObjRef, Object};
8
9use crate::canvas::{Canvas, CanvasParts};
10use crate::content::serialize_ops;
11use crate::element::{self, Content};
12use crate::error::{Error, Result};
13use crate::font::Standard14;
14use crate::sink::AsyncByteSink;
15use crate::writer::{WriteOptions, Writer};
16
17/// A page size, in default user-space units (1/72 inch), portrait.
18#[derive(Debug, Clone, Copy, PartialEq, Default)]
19pub enum PageSize {
20    /// 297 × 420 mm.
21    A3,
22    /// 210 × 297 mm.
23    #[default]
24    A4,
25    /// 148 × 210 mm.
26    A5,
27    /// 8.5 × 11 in.
28    Letter,
29    /// 8.5 × 14 in.
30    Legal,
31    /// Explicit dimensions in user-space units.
32    Custom {
33        /// Width in units.
34        width: f32,
35        /// Height in units.
36        height: f32,
37    },
38}
39
40impl PageSize {
41    /// Width and height in user-space units.
42    pub fn dimensions(self) -> (f32, f32) {
43        match self {
44            PageSize::A3 => (841.89, 1190.55),
45            PageSize::A4 => (595.28, 841.89),
46            PageSize::A5 => (419.53, 595.28),
47            PageSize::Letter => (612.0, 792.0),
48            PageSize::Legal => (612.0, 1008.0),
49            PageSize::Custom { width, height } => (width, height),
50        }
51    }
52
53    /// The same size with width and height swapped.
54    pub fn landscape(self) -> PageSize {
55        let (width, height) = self.dimensions();
56        PageSize::Custom {
57            width: height,
58            height: width,
59        }
60    }
61
62    /// Parses one of the five named sizes case-insensitively: `a3`, `a4`,
63    /// `a5`, `letter`, `legal`. `None` for anything else — a custom size
64    /// has no name to parse.
65    pub fn by_name(name: &str) -> Option<PageSize> {
66        match name.to_ascii_lowercase().as_str() {
67            "a3" => Some(PageSize::A3),
68            "a4" => Some(PageSize::A4),
69            "a5" => Some(PageSize::A5),
70            "letter" => Some(PageSize::Letter),
71            "legal" => Some(PageSize::Legal),
72            _ => None,
73        }
74    }
75}
76
77/// The date type of `/CreationDate` and `/ModDate`, shared with the reader
78/// crate (`pdfboss_core::Date`). The writer never reads a clock: dates
79/// appear in output only when a caller provides them, keeping builds
80/// reproducible.
81pub use pdfboss_core::Date;
82
83/// Document information written to the `/Info` dictionary. Every field is
84/// optional; an all-`None` value writes no dictionary at all.
85#[derive(Debug, Clone, Default, PartialEq)]
86pub struct Metadata {
87    /// `/Title`.
88    pub title: Option<String>,
89    /// `/Author`.
90    pub author: Option<String>,
91    /// `/Subject`.
92    pub subject: Option<String>,
93    /// `/Keywords`.
94    pub keywords: Option<String>,
95    /// `/Creator` (the producing application's name).
96    pub creator: Option<String>,
97    /// `/Producer`.
98    pub producer: Option<String>,
99    /// `/CreationDate`.
100    pub creation_date: Option<Date>,
101    /// `/ModDate`.
102    pub modification_date: Option<Date>,
103}
104
105/// One page: its size, rotation, painted content and link annotations.
106#[derive(Debug, Default)]
107pub struct Page {
108    /// Page size (the `/MediaBox`).
109    pub size: PageSize,
110    /// Clockwise view rotation in degrees; must be a multiple of 90.
111    pub rotation: i32,
112    /// The page's painted content.
113    pub canvas: Canvas,
114    /// Composed elements, painted onto `canvas` at assemble time, after
115    /// any content already painted there directly.
116    pub content: Vec<Content>,
117    /// Clickable link areas, emitted as `/Annots`.
118    pub links: Vec<LinkAnnotation>,
119}
120
121/// A clickable rectangle on a page that opens a URI or jumps to a page in
122/// the same document (a `/Link` annotation with a `/URI` or `/GoTo`
123/// action; ISO 32000 §12.5.6.5, §12.6.4.7, §12.3.2).
124///
125/// Covers ISO 32000-1 §12.5.6.5.
126#[derive(Debug, Clone, PartialEq)]
127pub struct LinkAnnotation {
128    /// The clickable area, `[x0, y0, x1, y1]` in the page's user space.
129    pub rect: [f32; 4],
130    /// Where the link goes.
131    pub target: LinkTarget,
132}
133
134/// Where a [`LinkAnnotation`] leads.
135#[derive(Debug, Clone, PartialEq)]
136pub enum LinkTarget {
137    /// An external URI, opened with a `/URI` action.
138    Uri(String),
139    /// A page within the same document, by index, opened with a `/GoTo`
140    /// action that keeps the viewer's current position and zoom.
141    Page(usize),
142}
143
144impl Page {
145    /// An empty page of the given size.
146    pub fn new(size: PageSize) -> Page {
147        Page {
148            size,
149            ..Page::default()
150        }
151    }
152}
153
154/// A document's bookmark panel: an ordered forest of [`Bookmark`] nodes,
155/// each linking to a page via an explicit `/XYZ` destination.
156///
157/// Covers ISO 32000-1 §12.3.3.
158#[derive(Debug, Clone, Default, PartialEq)]
159pub struct Outline {
160    /// Top-level bookmarks, in reading order.
161    pub bookmarks: Vec<Bookmark>,
162}
163
164/// One outline entry: a title, the page it jumps to, and nested children.
165#[derive(Debug, Clone, Default, PartialEq)]
166pub struct Bookmark {
167    /// Text shown in the outline panel.
168    pub title: String,
169    /// Target page index, opened keeping the viewer's current position
170    /// and zoom.
171    pub page: usize,
172    /// Nested bookmarks, in reading order.
173    pub children: Vec<Bookmark>,
174}
175
176impl Bookmark {
177    /// A leaf bookmark: `title` targeting `page`, with no children.
178    pub fn new(title: impl Into<String>, page: usize) -> Bookmark {
179        Bookmark {
180            title: title.into(),
181            page,
182            children: Vec::new(),
183        }
184    }
185}
186
187/// A document-level attachment, embedded via the catalog's `/Names
188/// /EmbeddedFiles` name tree (ISO 32000 §7.11.4). Unlike a page's painted
189/// content, an attachment carries no rendering — only the bytes and the
190/// metadata a viewer shows about them.
191#[derive(Debug, Clone, PartialEq)]
192pub struct Attachment {
193    /// The file name: written as both the filespec's `/F` and `/UF`, and
194    /// as the name-tree key.
195    pub name: String,
196    /// The attachment's raw bytes, stored as the embedded-file stream
197    /// (compressed like any other stream, per [`WriteOptions::compress`]).
198    pub data: Vec<u8>,
199    /// MIME type, written as the embedded-file stream's `/Subtype`.
200    /// `None` writes `application/octet-stream`.
201    pub mime: Option<String>,
202    /// `/Params /ModDate`, written only when given.
203    pub modified: Option<Date>,
204    /// `/Desc` on the filespec, written only when given.
205    pub description: Option<String>,
206}
207
208pub use pdfboss_core::page_label::{LabelStyle, PageLabel};
209
210/// Initial page-layout mode, written as the catalog's `/PageLayout` (ISO
211/// 32000 §7.7.2, Table 27).
212#[derive(Debug, Clone, Copy, PartialEq)]
213pub enum PageLayout {
214    /// One page at a time.
215    SinglePage,
216    /// One continuously scrolling column of pages.
217    OneColumn,
218    /// Two columns, an odd-numbered page on the left.
219    TwoColumnLeft,
220    /// Two columns, an odd-numbered page on the right.
221    TwoColumnRight,
222    /// Two pages at a time, an odd-numbered page on the left.
223    TwoPageLeft,
224    /// Two pages at a time, an odd-numbered page on the right.
225    TwoPageRight,
226}
227
228/// Initial navigation-panel mode, written as the catalog's `/PageMode`
229/// (ISO 32000 §7.7.2, Table 28).
230#[derive(Debug, Clone, Copy, PartialEq)]
231pub enum PageMode {
232    /// No panel open.
233    UseNone,
234    /// The outline (bookmarks) panel.
235    UseOutlines,
236    /// The page-thumbnails panel.
237    UseThumbs,
238    /// Full-screen presentation mode.
239    FullScreen,
240}
241
242/// Viewer preferences written to the catalog: initial layout, navigation
243/// mode, and the page opened at document start (ISO 32000 §7.7.2).
244#[derive(Debug, Clone, Default, PartialEq)]
245pub struct Viewer {
246    /// `/PageLayout`, omitted when `None`.
247    pub layout: Option<PageLayout>,
248    /// `/PageMode`, omitted when `None`.
249    pub mode: Option<PageMode>,
250    /// Page index opened via `/OpenAction`, keeping the viewer's current
251    /// position and zoom, omitted when `None`.
252    pub open_to: Option<usize>,
253}
254
255/// A document under construction. The fields are the composition:
256/// singleton slots are `Option`s, pages keep the order given.
257#[derive(Debug, Default)]
258pub struct Pdf {
259    /// Document information, if any.
260    pub metadata: Option<Metadata>,
261    /// Pages, in reading order.
262    pub pages: Vec<Page>,
263    /// Bookmark panel, if any.
264    pub outline: Option<Outline>,
265    /// Document-level attachments. Reordered by `name`, lexicographically
266    /// by bytes, at emission — the name-tree keys must be sorted, so the
267    /// order given here is not preserved. Duplicate names are an error.
268    pub attachments: Vec<Attachment>,
269    /// Page-numbering ranges shown in viewer UI as `/PageLabels`.
270    /// Reordered by `first_page` at emission. Must include a range
271    /// starting at page 0 when non-empty; duplicate `first_page` values
272    /// are an error.
273    pub page_labels: Vec<PageLabel>,
274    /// Viewer preferences, if any.
275    pub viewer: Option<Viewer>,
276    /// File-emission options.
277    pub options: WriteOptions,
278}
279
280impl Pdf {
281    /// Serializes the document to complete PDF file bytes.
282    ///
283    /// Fonts are shared document-wide: each distinct [`Standard14`] face
284    /// gets one font object, in first-use order. Images are embedded per
285    /// page with no cross-page deduplication — the same raster drawn on
286    /// two pages is stored twice. Groups follow the same rule: a canvas
287    /// registered with `Canvas::group` on two different pages produces two
288    /// Form XObjects — cross-page group sharing is deferred.
289    pub fn to_bytes(self) -> Result<Vec<u8>> {
290        let (w, root) = self.assemble()?;
291        w.finish(root)
292    }
293
294    /// [`Pdf::to_bytes`] streaming into a [`std::io::Write`]: the same
295    /// bytes, delivered in bounded chunks instead of one buffer. Unlike
296    /// `to_bytes`, an error can leave a prefix of the file already written
297    /// to `out`. No flush is performed.
298    pub fn write_into(self, out: impl std::io::Write) -> Result<()> {
299        let (w, root) = self.assemble()?;
300        w.finish_into(root, out)
301    }
302
303    /// [`Pdf::to_bytes`] streaming into any [`AsyncByteSink`] — the
304    /// asynchronous twin of [`Pdf::write_into`]. An error can leave a
305    /// prefix of the file already written. Hands the sink back unflushed.
306    pub async fn write_into_with<S: AsyncByteSink>(self, sink: S) -> Result<S> {
307        let (w, root) = self.assemble()?;
308        w.finish_into_with(root, sink).await
309    }
310
311    /// Builds the writer every write path finishes: all objects placed,
312    /// the catalog's reference returned alongside.
313    ///
314    /// Covers ISO 32000-1 §12.3.2, §12.3.2.2, §12.3.3, §12.5.4, §12.5.6.5, §12.6.2, §12.6.3, §12.6.4, §12.6.4.2, §12.6.4.7 and §14.3.2.
315    fn assemble(self) -> Result<(Writer, ObjRef)> {
316        let Pdf {
317            metadata,
318            pages,
319            outline,
320            attachments,
321            page_labels,
322            viewer,
323            options,
324        } = self;
325        if pages.is_empty() {
326            return Err(Error::Other(
327                "a document needs at least one page".to_string(),
328            ));
329        }
330        let mut w = Writer::new(options);
331        let pages_root = w.reserve();
332        let page_count = pages.len();
333        let page_refs: Vec<ObjRef> = pages.iter().map(|_| w.reserve()).collect();
334        let mut font_cache: Vec<(Standard14, ObjRef)> = Vec::new();
335        for (index, page) in pages.into_iter().enumerate() {
336            let Page {
337                size,
338                rotation,
339                mut canvas,
340                content,
341                mut links,
342            } = page;
343            if rotation % 90 != 0 {
344                return Err(Error::Other(format!(
345                    "page rotation {rotation} is not a multiple of 90"
346                )));
347            }
348            element::lower(content, &mut canvas, &mut links)?;
349            let (width, height) = size.dimensions();
350            let parts = canvas.into_parts();
351            let (content, resources) = lower_canvas(&mut w, parts, &mut font_cache)?;
352            let content_ref = w.put_stream(Dict::new(), content);
353            let mut dict = Dict::new();
354            dict.insert(name("Type"), Object::Name(name("Page")));
355            dict.insert(name("Parent"), Object::Ref(pages_root));
356            dict.insert(
357                name("MediaBox"),
358                Object::Array(vec![
359                    Object::Int(0),
360                    Object::Int(0),
361                    Object::Real(f64::from(width)),
362                    Object::Real(f64::from(height)),
363                ]),
364            );
365            dict.insert(name("Contents"), Object::Ref(content_ref));
366            dict.insert(name("Resources"), Object::Dict(resources));
367            if !links.is_empty() {
368                let mut annots = Vec::with_capacity(links.len());
369                for link in links {
370                    let action = match link.target {
371                        LinkTarget::Uri(uri) => {
372                            let mut action = Dict::new();
373                            action.insert(name("S"), Object::Name(name("URI")));
374                            action.insert(name("URI"), text_string(&uri));
375                            action
376                        }
377                        LinkTarget::Page(target_index) => {
378                            let target = page_refs.get(target_index).copied().ok_or_else(|| {
379                                Error::Other(format!(
380                                    "link target page {target_index} is out of range: the document has {page_count} pages"
381                                ))
382                            })?;
383                            let mut action = Dict::new();
384                            action.insert(name("S"), Object::Name(name("GoTo")));
385                            action.insert(
386                                name("D"),
387                                Object::Array(vec![
388                                    Object::Ref(target),
389                                    Object::Name(name("XYZ")),
390                                    Object::Null,
391                                    Object::Null,
392                                    Object::Null,
393                                ]),
394                            );
395                            action
396                        }
397                    };
398                    let mut annot = Dict::new();
399                    annot.insert(name("Type"), Object::Name(name("Annot")));
400                    annot.insert(name("Subtype"), Object::Name(name("Link")));
401                    annot.insert(
402                        name("Rect"),
403                        Object::Array(
404                            link.rect
405                                .iter()
406                                .map(|v| Object::Real(f64::from(*v)))
407                                .collect(),
408                        ),
409                    );
410                    annot.insert(
411                        name("Border"),
412                        Object::Array(vec![Object::Int(0), Object::Int(0), Object::Int(0)]),
413                    );
414                    annot.insert(name("A"), Object::Dict(action));
415                    annots.push(Object::Ref(w.put(Object::Dict(annot))));
416                }
417                dict.insert(name("Annots"), Object::Array(annots));
418            }
419            if rotation != 0 {
420                dict.insert(name("Rotate"), Object::Int(i64::from(rotation)));
421            }
422            w.fill(page_refs[index], Object::Dict(dict))?;
423        }
424        let kids: Vec<Object> = page_refs.iter().copied().map(Object::Ref).collect();
425        let mut tree = Dict::new();
426        tree.insert(name("Type"), Object::Name(name("Pages")));
427        tree.insert(name("Count"), Object::Int(kids.len() as i64));
428        tree.insert(name("Kids"), Object::Array(kids));
429        w.fill(pages_root, Object::Dict(tree))?;
430        let xmp_ref = match metadata {
431            Some(meta) => {
432                let packet = crate::xmp::packet(&meta);
433                if let Some(info) = info_dict(meta) {
434                    let info_ref = w.put(Object::Dict(info));
435                    w.set_info(info_ref);
436                }
437                let mut xmp_dict = Dict::new();
438                xmp_dict.insert(name("Type"), Object::Name(name("Metadata")));
439                xmp_dict.insert(name("Subtype"), Object::Name(name("XML")));
440                Some(w.put_stream_raw(xmp_dict, packet))
441            }
442            None => None,
443        };
444        let outline_ref = match outline {
445            Some(outline) if !outline.bookmarks.is_empty() => {
446                let root_ref = w.reserve();
447                let refs = reserve_bookmarks(&mut w, &outline.bookmarks);
448                let (first, last, count) = fill_bookmarks(
449                    &mut w,
450                    outline.bookmarks,
451                    &refs,
452                    root_ref,
453                    &page_refs,
454                    page_count,
455                )?;
456                let mut dict = Dict::new();
457                dict.insert(name("Type"), Object::Name(name("Outlines")));
458                dict.insert(name("First"), Object::Ref(first));
459                dict.insert(name("Last"), Object::Ref(last));
460                dict.insert(name("Count"), Object::Int(count));
461                w.fill(root_ref, Object::Dict(dict))?;
462                Some(root_ref)
463            }
464            _ => None,
465        };
466        let names = embedded_files_dict(&mut w, attachments)?;
467        let page_labels_entry = page_labels_dict(page_labels)?;
468        let mut catalog = Dict::new();
469        catalog.insert(name("Type"), Object::Name(name("Catalog")));
470        catalog.insert(name("Pages"), Object::Ref(pages_root));
471        if let Some(outline_ref) = outline_ref {
472            catalog.insert(name("Outlines"), Object::Ref(outline_ref));
473        }
474        if let Some(xmp_ref) = xmp_ref {
475            catalog.insert(name("Metadata"), Object::Ref(xmp_ref));
476        }
477        if let Some(names) = names {
478            catalog.insert(name("Names"), Object::Dict(names));
479        }
480        if let Some(page_labels_entry) = page_labels_entry {
481            catalog.insert(name("PageLabels"), Object::Dict(page_labels_entry));
482        }
483        if let Some(viewer) = viewer {
484            let Viewer {
485                layout,
486                mode,
487                open_to,
488            } = viewer;
489            if let Some(layout) = layout {
490                catalog.insert(
491                    name("PageLayout"),
492                    Object::Name(name(page_layout_name(layout))),
493                );
494            }
495            if let Some(mode) = mode {
496                catalog.insert(name("PageMode"), Object::Name(name(page_mode_name(mode))));
497            }
498            if let Some(open_to) = open_to {
499                let target = page_refs.get(open_to).copied().ok_or_else(|| {
500                    Error::Other(format!(
501                        "open_to target page {open_to} is out of range: the document has {page_count} pages"
502                    ))
503                })?;
504                catalog.insert(
505                    name("OpenAction"),
506                    Object::Array(vec![
507                        Object::Ref(target),
508                        Object::Name(name("XYZ")),
509                        Object::Null,
510                        Object::Null,
511                        Object::Null,
512                    ]),
513                );
514            }
515        }
516        let root = w.put(Object::Dict(catalog));
517        Ok((w, root))
518    }
519
520    /// Serializes and writes the document to `path`.
521    pub fn save(self, path: impl AsRef<Path>) -> Result<()> {
522        let path = path.as_ref();
523        let bytes = self.to_bytes()?;
524        std::fs::write(path, bytes)?;
525        Ok(())
526    }
527}
528
529/// A `Name` from a string literal.
530fn name(text: &str) -> Name {
531    Name(text.to_string())
532}
533
534/// Builds the `/Info` dictionary, or `None` when every field is `None`.
535///
536/// Covers ISO 32000-1 §14.3.3.
537fn info_dict(meta: Metadata) -> Option<Dict> {
538    let mut dict = Dict::new();
539    let texts = [
540        ("Title", meta.title),
541        ("Author", meta.author),
542        ("Subject", meta.subject),
543        ("Keywords", meta.keywords),
544        ("Creator", meta.creator),
545        ("Producer", meta.producer),
546    ];
547    for (key, value) in texts {
548        if let Some(value) = value {
549            dict.insert(name(key), text_string(&value));
550        }
551    }
552    let dates = [
553        ("CreationDate", meta.creation_date),
554        ("ModDate", meta.modification_date),
555    ];
556    for (key, value) in dates {
557        if let Some(date) = value {
558            dict.insert(name(key), Object::String(date.to_pdf_string().into_bytes()));
559        }
560    }
561    if dict.is_empty() {
562        return None;
563    }
564    Some(dict)
565}
566
567/// Default MIME type for an [`Attachment`] whose `mime` is `None`.
568const DEFAULT_ATTACHMENT_MIME: &str = "application/octet-stream";
569
570/// Builds the catalog's `/Names` dictionary from `attachments`, or `None`
571/// when there are none. Attachments are reordered by `name`, bytewise, to
572/// satisfy the name tree's sorted-key requirement — string comparison in
573/// Rust is already a byte comparison, so sorting `String` values sorts
574/// their bytes. A repeated name is an error naming the duplicate.
575fn embedded_files_dict(w: &mut Writer, mut attachments: Vec<Attachment>) -> Result<Option<Dict>> {
576    if attachments.is_empty() {
577        return Ok(None);
578    }
579    attachments.sort_by(|a, b| a.name.cmp(&b.name));
580    for pair in attachments.windows(2) {
581        if pair[0].name == pair[1].name {
582            return Err(Error::Other(format!(
583                "duplicate attachment name: {:?}",
584                pair[0].name
585            )));
586        }
587    }
588    let mut entries = Vec::with_capacity(attachments.len() * 2);
589    for attachment in attachments {
590        let Attachment {
591            name: file_name,
592            data,
593            mime,
594            modified,
595            description,
596        } = attachment;
597        let mime = mime.unwrap_or_else(|| DEFAULT_ATTACHMENT_MIME.to_string());
598
599        let mut params = Dict::new();
600        params.insert(name("Size"), Object::Int(data.len() as i64));
601        if let Some(modified) = modified {
602            params.insert(
603                name("ModDate"),
604                Object::String(modified.to_pdf_string().into_bytes()),
605            );
606        }
607        let mut stream_dict = Dict::new();
608        stream_dict.insert(name("Type"), Object::Name(name("EmbeddedFile")));
609        stream_dict.insert(name("Subtype"), Object::Name(Name(mime)));
610        stream_dict.insert(name("Params"), Object::Dict(params));
611        let stream_ref = w.put_stream(stream_dict, data);
612
613        let mut ef = Dict::new();
614        ef.insert(name("F"), Object::Ref(stream_ref));
615
616        let mut filespec = Dict::new();
617        filespec.insert(name("Type"), Object::Name(name("Filespec")));
618        filespec.insert(name("F"), text_string(&file_name));
619        filespec.insert(name("UF"), text_string(&file_name));
620        if let Some(description) = description {
621            filespec.insert(name("Desc"), text_string(&description));
622        }
623        filespec.insert(name("EF"), Object::Dict(ef));
624        let filespec_ref = w.put(Object::Dict(filespec));
625
626        entries.push(text_string(&file_name));
627        entries.push(Object::Ref(filespec_ref));
628    }
629    let mut name_tree = Dict::new();
630    name_tree.insert(name("Names"), Object::Array(entries));
631    let mut embedded_files = Dict::new();
632    embedded_files.insert(name("EmbeddedFiles"), Object::Dict(name_tree));
633    Ok(Some(embedded_files))
634}
635
636/// Builds the catalog's `/PageLabels` dictionary from `labels`, or `None`
637/// when there are none. Ranges are reordered by `first_page` to satisfy
638/// the number tree's sorted-key requirement. A non-empty set must include
639/// a range starting at page 0; a repeated `first_page` is an error naming
640/// the page; a `start_at` of 0 is an error naming the page, since ISO
641/// 32000 page-label numbering starts at 1.
642fn page_labels_dict(mut labels: Vec<PageLabel>) -> Result<Option<Dict>> {
643    if labels.is_empty() {
644        return Ok(None);
645    }
646    for label in &labels {
647        if label.start_at == 0 {
648            return Err(Error::Other(format!(
649                "page label at page {} has start_at 0: numbering starts at 1",
650                label.first_page
651            )));
652        }
653    }
654    labels.sort_by_key(|label| label.first_page);
655    if labels[0].first_page != 0 {
656        return Err(Error::Other("page labels must start at page 0".to_string()));
657    }
658    for pair in labels.windows(2) {
659        if pair[0].first_page == pair[1].first_page {
660            return Err(Error::Other(format!(
661                "duplicate page label at page {}",
662                pair[0].first_page
663            )));
664        }
665    }
666    let mut nums = Vec::with_capacity(labels.len() * 2);
667    for label in labels {
668        let PageLabel {
669            first_page,
670            style,
671            prefix,
672            start_at,
673        } = label;
674        let mut range = Dict::new();
675        if let Some(style) = style {
676            range.insert(name("S"), Object::Name(name(style.code())));
677        }
678        if let Some(prefix) = prefix {
679            range.insert(name("P"), text_string(&prefix));
680        }
681        if start_at != 1 {
682            range.insert(name("St"), Object::Int(i64::from(start_at)));
683        }
684        nums.push(Object::Int(first_page as i64));
685        nums.push(Object::Dict(range));
686    }
687    let mut dict = Dict::new();
688    dict.insert(name("Nums"), Object::Array(nums));
689    Ok(Some(dict))
690}
691
692/// The `/PageLayout` name for a [`PageLayout`].
693fn page_layout_name(layout: PageLayout) -> &'static str {
694    match layout {
695        PageLayout::SinglePage => "SinglePage",
696        PageLayout::OneColumn => "OneColumn",
697        PageLayout::TwoColumnLeft => "TwoColumnLeft",
698        PageLayout::TwoColumnRight => "TwoColumnRight",
699        PageLayout::TwoPageLeft => "TwoPageLeft",
700        PageLayout::TwoPageRight => "TwoPageRight",
701    }
702}
703
704/// The `/PageMode` name for a [`PageMode`].
705fn page_mode_name(mode: PageMode) -> &'static str {
706    match mode {
707        PageMode::UseNone => "UseNone",
708        PageMode::UseOutlines => "UseOutlines",
709        PageMode::UseThumbs => "UseThumbs",
710        PageMode::FullScreen => "FullScreen",
711    }
712}
713
714/// One bookmark's reserved object number, mirroring the tree shape so the
715/// fill pass can wire parent, sibling and child refs before any of their
716/// dictionary bodies exist.
717struct BookmarkRef {
718    r: ObjRef,
719    children: Vec<BookmarkRef>,
720}
721
722/// Reserves an object number for every node in `bookmarks`, recursively —
723/// the reserve half of the reserve/fill idiom: an outline item's `/Parent`,
724/// `/Prev`, `/Next`, `/First` and `/Last` may all point at nodes that do
725/// not have a body yet.
726fn reserve_bookmarks(w: &mut Writer, bookmarks: &[Bookmark]) -> Vec<BookmarkRef> {
727    bookmarks
728        .iter()
729        .map(|bookmark| BookmarkRef {
730            r: w.reserve(),
731            children: reserve_bookmarks(w, &bookmark.children),
732        })
733        .collect()
734}
735
736/// Fills one sibling chain of outline items against their already-reserved
737/// refs: `/Title`, `/Parent`, the `/Prev`/`/Next` chain, `/Dest`, and — for
738/// any bookmark with children — `/First`/`/Last`/`/Count` from a recursive
739/// fill of that subtree. Returns the chain's first and last refs and the
740/// total number of items in the whole subtree, which doubles as `/Count`
741/// wherever the caller needs it (every bookmark is open).
742fn fill_bookmarks(
743    w: &mut Writer,
744    bookmarks: Vec<Bookmark>,
745    refs: &[BookmarkRef],
746    parent: ObjRef,
747    page_refs: &[ObjRef],
748    page_count: usize,
749) -> Result<(ObjRef, ObjRef, i64)> {
750    let last_index = bookmarks.len() - 1;
751    let mut total = 0i64;
752    for (index, bookmark) in bookmarks.into_iter().enumerate() {
753        let Bookmark {
754            title,
755            page,
756            children,
757        } = bookmark;
758        let dest = page_refs.get(page).copied().ok_or_else(|| {
759            Error::Other(format!(
760                "bookmark target page {page} is out of range: the document has {page_count} pages"
761            ))
762        })?;
763        let mut dict = Dict::new();
764        dict.insert(name("Title"), text_string(&title));
765        dict.insert(name("Parent"), Object::Ref(parent));
766        if index > 0 {
767            dict.insert(name("Prev"), Object::Ref(refs[index - 1].r));
768        }
769        if index < last_index {
770            dict.insert(name("Next"), Object::Ref(refs[index + 1].r));
771        }
772        dict.insert(
773            name("Dest"),
774            Object::Array(vec![
775                Object::Ref(dest),
776                Object::Name(name("XYZ")),
777                Object::Null,
778                Object::Null,
779                Object::Null,
780            ]),
781        );
782        let mut subtree_count = 0i64;
783        if !children.is_empty() {
784            let (first, last, count) = fill_bookmarks(
785                w,
786                children,
787                &refs[index].children,
788                refs[index].r,
789                page_refs,
790                page_count,
791            )?;
792            dict.insert(name("First"), Object::Ref(first));
793            dict.insert(name("Last"), Object::Ref(last));
794            dict.insert(name("Count"), Object::Int(count));
795            subtree_count = count;
796        }
797        w.fill(refs[index].r, Object::Dict(dict))?;
798        total += 1 + subtree_count;
799    }
800    Ok((refs[0].r, refs[last_index].r, total))
801}
802
803/// The document-wide font object for `face`: an existing entry from
804/// `font_cache` when one matches, otherwise a freshly built one that is
805/// cached for the next lookup. Shared by the page loop and every nested
806/// [`build_form`] so a face used both on a page and inside a group still
807/// gets exactly one font object.
808fn cached_font(
809    w: &mut Writer,
810    font_cache: &mut Vec<(Standard14, ObjRef)>,
811    face: &Standard14,
812) -> ObjRef {
813    if let Some((_, r)) = font_cache.iter().find(|(seen, _)| seen == face) {
814        return *r;
815    }
816    let r = w.put(Object::Dict(face.font_dict()));
817    font_cache.push((*face, r));
818    r
819}
820
821/// Serializes `parts`' operators and builds its resources dict: fonts,
822/// images, nested groups (recursing through `build_form`), and
823/// ext-gstates, each inserted as `/Font`, `/XObject`, `/ExtGState` only
824/// when non-empty. Shared by the page loop and `build_form`, whose page
825/// and Form XObject dicts differ but whose resource assembly is the same.
826fn lower_canvas(
827    w: &mut Writer,
828    parts: CanvasParts,
829    font_cache: &mut Vec<(Standard14, ObjRef)>,
830) -> Result<(Vec<u8>, Dict)> {
831    let content = serialize_ops(&parts.ops);
832    let mut fonts = Dict::new();
833    for (index, face) in parts.fonts.iter().enumerate() {
834        let font_ref = cached_font(w, font_cache, face);
835        fonts.insert(Name(format!("F{}", index + 1)), Object::Ref(font_ref));
836    }
837    let mut xobjects = Dict::new();
838    for (index, image) in parts.images.iter().enumerate() {
839        let image_ref = image.build_xobject(w);
840        xobjects.insert(Name(format!("Im{}", index + 1)), Object::Ref(image_ref));
841    }
842    for (index, (group_parts, group_bbox)) in parts.groups.into_iter().enumerate() {
843        let group_ref = build_form(w, group_parts, group_bbox, font_cache)?;
844        xobjects.insert(Name(format!("Gp{}", index + 1)), Object::Ref(group_ref));
845    }
846    let mut ext_gstates = Dict::new();
847    for (index, state) in parts.gstates.iter().enumerate() {
848        let gstate_ref = w.put(Object::Dict(state.ext_gstate_dict()));
849        ext_gstates.insert(Name(format!("Gs{}", index + 1)), Object::Ref(gstate_ref));
850    }
851    let mut resources = Dict::new();
852    if !fonts.is_empty() {
853        resources.insert(name("Font"), Object::Dict(fonts));
854    }
855    if !xobjects.is_empty() {
856        resources.insert(name("XObject"), Object::Dict(xobjects));
857    }
858    if !ext_gstates.is_empty() {
859        resources.insert(name("ExtGState"), Object::Dict(ext_gstates));
860    }
861    Ok((content, resources))
862}
863
864/// Builds one Form XObject from a registered group's parts: `/Type
865/// /XObject /Subtype /Form /BBox /Resources`, with the sub-canvas's
866/// operators as its content stream. Recurses for groups nested inside
867/// groups, and shares `font_cache` with the page loop so nested forms
868/// never duplicate a font already emitted elsewhere in the document.
869fn build_form(
870    w: &mut Writer,
871    parts: CanvasParts,
872    bbox: [f32; 4],
873    font_cache: &mut Vec<(Standard14, ObjRef)>,
874) -> Result<ObjRef> {
875    let (content, resources) = lower_canvas(w, parts, font_cache)?;
876    let mut dict = Dict::new();
877    dict.insert(name("Type"), Object::Name(name("XObject")));
878    dict.insert(name("Subtype"), Object::Name(name("Form")));
879    dict.insert(
880        name("BBox"),
881        Object::Array(bbox.iter().map(|v| Object::Real(f64::from(*v))).collect()),
882    );
883    dict.insert(name("Resources"), Object::Dict(resources));
884    Ok(w.put_stream(dict, content))
885}
886
887/// Encodes a text string (ISO 32000 §7.9.2.2): pure ASCII passes through
888/// as its own bytes, anything else becomes UTF-16BE with a `FE FF` byte
889/// order mark.
890pub(crate) fn text_string(value: &str) -> Object {
891    if value.is_ascii() {
892        return Object::String(value.as_bytes().to_vec());
893    }
894    let mut bytes = vec![0xFE, 0xFF];
895    for unit in value.encode_utf16() {
896        bytes.extend_from_slice(&unit.to_be_bytes());
897    }
898    Object::String(bytes)
899}
900
901#[cfg(test)]
902mod tests {
903    use super::*;
904
905    #[test]
906    fn dimensions_match_the_contract() {
907        assert_eq!(PageSize::A3.dimensions(), (841.89, 1190.55));
908        assert_eq!(PageSize::A4.dimensions(), (595.28, 841.89));
909        assert_eq!(PageSize::A5.dimensions(), (419.53, 595.28));
910        assert_eq!(PageSize::Letter.dimensions(), (612.0, 792.0));
911        assert_eq!(PageSize::Legal.dimensions(), (612.0, 1008.0));
912        assert_eq!(
913            PageSize::Custom {
914                width: 10.0,
915                height: 20.0
916            }
917            .dimensions(),
918            (10.0, 20.0)
919        );
920    }
921
922    #[test]
923    fn by_name_parses_the_five_named_sizes_case_insensitively() {
924        for (name, expected) in [
925            ("a3", PageSize::A3),
926            ("A4", PageSize::A4),
927            ("a5", PageSize::A5),
928            ("Letter", PageSize::Letter),
929            ("LEGAL", PageSize::Legal),
930        ] {
931            assert_eq!(PageSize::by_name(name), Some(expected), "{name}");
932        }
933    }
934
935    #[test]
936    fn by_name_rejects_anything_else() {
937        assert_eq!(PageSize::by_name("tabloid"), None);
938        assert_eq!(PageSize::by_name(""), None);
939    }
940
941    #[test]
942    fn landscape_swaps_into_custom() {
943        assert_eq!(
944            PageSize::A4.landscape(),
945            PageSize::Custom {
946                width: 841.89,
947                height: 595.28
948            }
949        );
950        assert_eq!(
951            PageSize::Custom {
952                width: 1.0,
953                height: 2.0
954            }
955            .landscape(),
956            PageSize::Custom {
957                width: 2.0,
958                height: 1.0
959            }
960        );
961        assert_eq!(PageSize::Letter.landscape().dimensions(), (792.0, 612.0));
962    }
963
964    /// Two pages with text and an image — enough to exercise fonts,
965    /// XObjects and the reserved page tree through every write path.
966    fn two_page_doc() -> Pdf {
967        let mut first = Page::new(PageSize::A4);
968        first
969            .canvas
970            .text("Streamed parity", 72.0, 720.0, Standard14::Helvetica, 14.0)
971            .expect("ASCII encodes");
972        let image = crate::image::ImageData::gray8(2, 2, vec![0, 85, 170, 255])
973            .expect("2x2 grayscale builds");
974        let handle = first.canvas.add_image(image);
975        first.canvas.draw_image(handle, 72.0, 400.0, 144.0, 144.0);
976        let mut second = Page::new(PageSize::Letter);
977        second
978            .canvas
979            .text("Page two", 72.0, 700.0, Standard14::TimesRoman, 12.0)
980            .expect("ASCII encodes");
981        Pdf {
982            pages: vec![first, second],
983            ..Pdf::default()
984        }
985    }
986
987    /// The three write paths are one assembly and one emission: identical
988    /// bytes whether buffered, streamed into an `io::Write`, or streamed
989    /// into an async sink.
990    #[test]
991    fn write_into_and_write_into_with_match_to_bytes() {
992        let bytes = two_page_doc().to_bytes().expect("to_bytes succeeds");
993        let mut via_io = Vec::new();
994        two_page_doc()
995            .write_into(&mut via_io)
996            .expect("write_into succeeds");
997        assert_eq!(via_io, bytes);
998        let via_sink = pdfboss_core::block_on(two_page_doc().write_into_with(Vec::new()))
999            .expect("write_into_with succeeds");
1000        assert_eq!(via_sink, bytes);
1001    }
1002
1003    #[test]
1004    fn zero_page_document_is_an_error() {
1005        let err = Pdf::default()
1006            .to_bytes()
1007            .expect_err("a page-less document must not serialize");
1008        assert!(err.to_string().contains("at least one page"), "{err}");
1009    }
1010}