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