pdfboss-write 0.25.0

PDF creation for pdfboss: COS object writer, content canvas and document assembly
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
//! Document assembly: pages of canvas content, document metadata, and the
//! save path. `Pdf` is a plain struct — the fields are the composition,
//! and `Default` fills everything optional.

use std::path::Path;

use pdfboss_core::{Dict, Name, ObjRef, Object};

use crate::canvas::{Canvas, CanvasParts};
use crate::content::serialize_ops;
use crate::element::{self, Content};
use crate::error::{Error, Result};
use crate::font::Standard14;
use crate::sink::AsyncByteSink;
use crate::writer::{WriteOptions, Writer};

/// A page size, in default user-space units (1/72 inch), portrait.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum PageSize {
    /// 297 × 420 mm.
    A3,
    /// 210 × 297 mm.
    #[default]
    A4,
    /// 148 × 210 mm.
    A5,
    /// 8.5 × 11 in.
    Letter,
    /// 8.5 × 14 in.
    Legal,
    /// Explicit dimensions in user-space units.
    Custom {
        /// Width in units.
        width: f32,
        /// Height in units.
        height: f32,
    },
}

impl PageSize {
    /// Width and height in user-space units.
    pub fn dimensions(self) -> (f32, f32) {
        match self {
            PageSize::A3 => (841.89, 1190.55),
            PageSize::A4 => (595.28, 841.89),
            PageSize::A5 => (419.53, 595.28),
            PageSize::Letter => (612.0, 792.0),
            PageSize::Legal => (612.0, 1008.0),
            PageSize::Custom { width, height } => (width, height),
        }
    }

    /// The same size with width and height swapped.
    pub fn landscape(self) -> PageSize {
        let (width, height) = self.dimensions();
        PageSize::Custom {
            width: height,
            height: width,
        }
    }

    /// Parses one of the five named sizes case-insensitively: `a3`, `a4`,
    /// `a5`, `letter`, `legal`. `None` for anything else — a custom size
    /// has no name to parse.
    pub fn by_name(name: &str) -> Option<PageSize> {
        match name.to_ascii_lowercase().as_str() {
            "a3" => Some(PageSize::A3),
            "a4" => Some(PageSize::A4),
            "a5" => Some(PageSize::A5),
            "letter" => Some(PageSize::Letter),
            "legal" => Some(PageSize::Legal),
            _ => None,
        }
    }
}

/// A calendar date and time with a UTC offset, for `/CreationDate` and
/// `/ModDate`. The writer never reads a clock — dates appear in output
/// only when a caller provides them, keeping builds reproducible.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Date {
    /// Four-digit year.
    pub year: u16,
    /// Month, 1–12.
    pub month: u8,
    /// Day of month, 1–31.
    pub day: u8,
    /// Hour, 0–23.
    pub hour: u8,
    /// Minute, 0–59.
    pub minute: u8,
    /// Second, 0–59.
    pub second: u8,
    /// Offset from UTC in minutes (positive east).
    pub utc_offset_minutes: i16,
}

impl Date {
    /// Formats as a PDF date string, `D:YYYYMMDDHHmmSSOHH'mm` — with a
    /// literal `Z` in place of the offset when the date is exactly UTC.
    pub fn to_pdf_string(self) -> String {
        let Date {
            year,
            month,
            day,
            hour,
            minute,
            second,
            utc_offset_minutes,
        } = self;
        let mut out = format!("D:{year:04}{month:02}{day:02}{hour:02}{minute:02}{second:02}");
        if utc_offset_minutes == 0 {
            out.push('Z');
            return out;
        }
        let sign = if utc_offset_minutes < 0 { '-' } else { '+' };
        let magnitude = utc_offset_minutes.unsigned_abs();
        out.push_str(&format!(
            "{sign}{:02}'{:02}",
            magnitude / 60,
            magnitude % 60
        ));
        out
    }

    /// Formats as an ISO-8601 date-time, `YYYY-MM-DDTHH:mm:SS±HH:MM` — with
    /// a literal `Z` in place of the offset when the date is exactly UTC.
    /// Used for the XMP `xmp:CreateDate`/`xmp:ModifyDate` elements.
    pub(crate) fn to_iso8601(self) -> String {
        let Date {
            year,
            month,
            day,
            hour,
            minute,
            second,
            utc_offset_minutes,
        } = self;
        let mut out = format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}");
        if utc_offset_minutes == 0 {
            out.push('Z');
            return out;
        }
        let sign = if utc_offset_minutes < 0 { '-' } else { '+' };
        let magnitude = utc_offset_minutes.unsigned_abs();
        out.push_str(&format!(
            "{sign}{:02}:{:02}",
            magnitude / 60,
            magnitude % 60
        ));
        out
    }
}

/// Document information written to the `/Info` dictionary. Every field is
/// optional; an all-`None` value writes no dictionary at all.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Metadata {
    /// `/Title`.
    pub title: Option<String>,
    /// `/Author`.
    pub author: Option<String>,
    /// `/Subject`.
    pub subject: Option<String>,
    /// `/Keywords`.
    pub keywords: Option<String>,
    /// `/Creator` (the producing application's name).
    pub creator: Option<String>,
    /// `/Producer`.
    pub producer: Option<String>,
    /// `/CreationDate`.
    pub creation_date: Option<Date>,
    /// `/ModDate`.
    pub modification_date: Option<Date>,
}

/// One page: its size, rotation, painted content and link annotations.
#[derive(Debug, Default)]
pub struct Page {
    /// Page size (the `/MediaBox`).
    pub size: PageSize,
    /// Clockwise view rotation in degrees; must be a multiple of 90.
    pub rotation: i32,
    /// The page's painted content.
    pub canvas: Canvas,
    /// Composed elements, painted onto `canvas` at assemble time, after
    /// any content already painted there directly.
    pub content: Vec<Content>,
    /// Clickable link areas, emitted as `/Annots`.
    pub links: Vec<LinkAnnotation>,
}

/// A clickable rectangle on a page that opens a URI or jumps to a page in
/// the same document (a `/Link` annotation with a `/URI` or `/GoTo`
/// action; ISO 32000 §12.5.6.5, §12.6.4.7, §12.3.2).
#[derive(Debug, Clone, PartialEq)]
pub struct LinkAnnotation {
    /// The clickable area, `[x0, y0, x1, y1]` in the page's user space.
    pub rect: [f32; 4],
    /// Where the link goes.
    pub target: LinkTarget,
}

/// Where a [`LinkAnnotation`] leads.
#[derive(Debug, Clone, PartialEq)]
pub enum LinkTarget {
    /// An external URI, opened with a `/URI` action.
    Uri(String),
    /// A page within the same document, by index, opened with a `/GoTo`
    /// action that keeps the viewer's current position and zoom.
    Page(usize),
}

impl Page {
    /// An empty page of the given size.
    pub fn new(size: PageSize) -> Page {
        Page {
            size,
            ..Page::default()
        }
    }
}

/// A document's bookmark panel: an ordered forest of [`Bookmark`] nodes,
/// each linking to a page via an explicit `/XYZ` destination.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Outline {
    /// Top-level bookmarks, in reading order.
    pub bookmarks: Vec<Bookmark>,
}

/// One outline entry: a title, the page it jumps to, and nested children.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Bookmark {
    /// Text shown in the outline panel.
    pub title: String,
    /// Target page index, opened keeping the viewer's current position
    /// and zoom.
    pub page: usize,
    /// Nested bookmarks, in reading order.
    pub children: Vec<Bookmark>,
}

impl Bookmark {
    /// A leaf bookmark: `title` targeting `page`, with no children.
    pub fn new(title: impl Into<String>, page: usize) -> Bookmark {
        Bookmark {
            title: title.into(),
            page,
            children: Vec::new(),
        }
    }
}

/// A document-level attachment, embedded via the catalog's `/Names
/// /EmbeddedFiles` name tree (ISO 32000 §7.11.4). Unlike a page's painted
/// content, an attachment carries no rendering — only the bytes and the
/// metadata a viewer shows about them.
#[derive(Debug, Clone, PartialEq)]
pub struct Attachment {
    /// The file name: written as both the filespec's `/F` and `/UF`, and
    /// as the name-tree key.
    pub name: String,
    /// The attachment's raw bytes, stored as the embedded-file stream
    /// (compressed like any other stream, per [`WriteOptions::compress`]).
    pub data: Vec<u8>,
    /// MIME type, written as the embedded-file stream's `/Subtype`.
    /// `None` writes `application/octet-stream`.
    pub mime: Option<String>,
    /// `/Params /ModDate`, written only when given.
    pub modified: Option<Date>,
    /// `/Desc` on the filespec, written only when given.
    pub description: Option<String>,
}

/// A page-numbering style for a [`PageLabel`] range, written as its `/S`
/// (ISO 32000 §12.4.2, Table 159).
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum LabelStyle {
    /// Arabic numerals: 1, 2, 3…
    Decimal,
    /// Uppercase Roman numerals: I, II, III…
    RomanUpper,
    /// Lowercase Roman numerals: i, ii, iii…
    RomanLower,
    /// Uppercase letters: A, B, …, Z, AA…
    LettersUpper,
    /// Lowercase letters: a, b, …, z, aa…
    LettersLower,
}

/// One page-numbering range, taking effect from `first_page` (0-based)
/// until the next range's `first_page` or the document's end (ISO 32000
/// §12.4.2). A document's `page_labels` must include a range with
/// `first_page == 0` whenever it is non-empty.
#[derive(Debug, Clone, PartialEq)]
pub struct PageLabel {
    /// 0-based page index where this range begins.
    pub first_page: usize,
    /// Numbering style, written as `/S`; `None` omits it, showing only
    /// `prefix` for every page in the range.
    pub style: Option<LabelStyle>,
    /// Text prepended to every number in the range, written as `/P`.
    pub prefix: Option<String>,
    /// The number shown on `first_page`, written as `/St` only when not
    /// `1`. Conventionally `1`.
    pub start_at: u32,
}

/// Initial page-layout mode, written as the catalog's `/PageLayout` (ISO
/// 32000 §7.7.2, Table 27).
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum PageLayout {
    /// One page at a time.
    SinglePage,
    /// One continuously scrolling column of pages.
    OneColumn,
    /// Two columns, an odd-numbered page on the left.
    TwoColumnLeft,
    /// Two columns, an odd-numbered page on the right.
    TwoColumnRight,
    /// Two pages at a time, an odd-numbered page on the left.
    TwoPageLeft,
    /// Two pages at a time, an odd-numbered page on the right.
    TwoPageRight,
}

/// Initial navigation-panel mode, written as the catalog's `/PageMode`
/// (ISO 32000 §7.7.2, Table 28).
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum PageMode {
    /// No panel open.
    UseNone,
    /// The outline (bookmarks) panel.
    UseOutlines,
    /// The page-thumbnails panel.
    UseThumbs,
    /// Full-screen presentation mode.
    FullScreen,
}

/// Viewer preferences written to the catalog: initial layout, navigation
/// mode, and the page opened at document start (ISO 32000 §7.7.2).
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Viewer {
    /// `/PageLayout`, omitted when `None`.
    pub layout: Option<PageLayout>,
    /// `/PageMode`, omitted when `None`.
    pub mode: Option<PageMode>,
    /// Page index opened via `/OpenAction`, keeping the viewer's current
    /// position and zoom, omitted when `None`.
    pub open_to: Option<usize>,
}

/// A document under construction. The fields are the composition:
/// singleton slots are `Option`s, pages keep the order given.
#[derive(Debug, Default)]
pub struct Pdf {
    /// Document information, if any.
    pub metadata: Option<Metadata>,
    /// Pages, in reading order.
    pub pages: Vec<Page>,
    /// Bookmark panel, if any.
    pub outline: Option<Outline>,
    /// Document-level attachments. Reordered by `name`, lexicographically
    /// by bytes, at emission — the name-tree keys must be sorted, so the
    /// order given here is not preserved. Duplicate names are an error.
    pub attachments: Vec<Attachment>,
    /// Page-numbering ranges shown in viewer UI as `/PageLabels`.
    /// Reordered by `first_page` at emission. Must include a range
    /// starting at page 0 when non-empty; duplicate `first_page` values
    /// are an error.
    pub page_labels: Vec<PageLabel>,
    /// Viewer preferences, if any.
    pub viewer: Option<Viewer>,
    /// File-emission options.
    pub options: WriteOptions,
}

impl Pdf {
    /// Serializes the document to complete PDF file bytes.
    ///
    /// Fonts are shared document-wide: each distinct [`Standard14`] face
    /// gets one font object, in first-use order. Images are embedded per
    /// page with no cross-page deduplication — the same raster drawn on
    /// two pages is stored twice. Groups follow the same rule: a canvas
    /// registered with `Canvas::group` on two different pages produces two
    /// Form XObjects — cross-page group sharing is deferred.
    pub fn to_bytes(self) -> Result<Vec<u8>> {
        let (w, root) = self.assemble()?;
        w.finish(root)
    }

    /// [`Pdf::to_bytes`] streaming into a [`std::io::Write`]: the same
    /// bytes, delivered in bounded chunks instead of one buffer. Unlike
    /// `to_bytes`, an error can leave a prefix of the file already written
    /// to `out`. No flush is performed.
    pub fn write_into(self, out: impl std::io::Write) -> Result<()> {
        let (w, root) = self.assemble()?;
        w.finish_into(root, out)
    }

    /// [`Pdf::to_bytes`] streaming into any [`AsyncByteSink`] — the
    /// asynchronous twin of [`Pdf::write_into`]. An error can leave a
    /// prefix of the file already written. Hands the sink back unflushed.
    pub async fn write_into_with<S: AsyncByteSink>(self, sink: S) -> Result<S> {
        let (w, root) = self.assemble()?;
        w.finish_into_with(root, sink).await
    }

    /// Builds the writer every write path finishes: all objects placed,
    /// the catalog's reference returned alongside.
    fn assemble(self) -> Result<(Writer, ObjRef)> {
        let Pdf {
            metadata,
            pages,
            outline,
            attachments,
            page_labels,
            viewer,
            options,
        } = self;
        if pages.is_empty() {
            return Err(Error::Other(
                "a document needs at least one page".to_string(),
            ));
        }
        let mut w = Writer::new(options);
        let pages_root = w.reserve();
        let page_count = pages.len();
        let page_refs: Vec<ObjRef> = pages.iter().map(|_| w.reserve()).collect();
        let mut font_cache: Vec<(Standard14, ObjRef)> = Vec::new();
        for (index, page) in pages.into_iter().enumerate() {
            let Page {
                size,
                rotation,
                mut canvas,
                content,
                mut links,
            } = page;
            if rotation % 90 != 0 {
                return Err(Error::Other(format!(
                    "page rotation {rotation} is not a multiple of 90"
                )));
            }
            element::lower(content, &mut canvas, &mut links)?;
            let (width, height) = size.dimensions();
            let parts = canvas.into_parts();
            let content_ref = w.put_stream(Dict::new(), serialize_ops(&parts.ops));
            let mut fonts = Dict::new();
            for (index, face) in parts.fonts.iter().enumerate() {
                let font_ref = cached_font(&mut w, &mut font_cache, face);
                fonts.insert(Name(format!("F{}", index + 1)), Object::Ref(font_ref));
            }
            let mut xobjects = Dict::new();
            for (index, image) in parts.images.iter().enumerate() {
                let image_ref = image.build_xobject(&mut w);
                xobjects.insert(Name(format!("Im{}", index + 1)), Object::Ref(image_ref));
            }
            for (index, (group_parts, bbox)) in parts.groups.into_iter().enumerate() {
                let group_ref = build_form(&mut w, group_parts, bbox, &mut font_cache)?;
                xobjects.insert(Name(format!("Gp{}", index + 1)), Object::Ref(group_ref));
            }
            let mut ext_gstates = Dict::new();
            for (index, state) in parts.gstates.iter().enumerate() {
                let gstate_ref = w.put(Object::Dict(state.ext_gstate_dict()));
                ext_gstates.insert(Name(format!("Gs{}", index + 1)), Object::Ref(gstate_ref));
            }
            let mut resources = Dict::new();
            if !fonts.is_empty() {
                resources.insert(name("Font"), Object::Dict(fonts));
            }
            if !xobjects.is_empty() {
                resources.insert(name("XObject"), Object::Dict(xobjects));
            }
            if !ext_gstates.is_empty() {
                resources.insert(name("ExtGState"), Object::Dict(ext_gstates));
            }
            let mut dict = Dict::new();
            dict.insert(name("Type"), Object::Name(name("Page")));
            dict.insert(name("Parent"), Object::Ref(pages_root));
            dict.insert(
                name("MediaBox"),
                Object::Array(vec![
                    Object::Int(0),
                    Object::Int(0),
                    Object::Real(f64::from(width)),
                    Object::Real(f64::from(height)),
                ]),
            );
            dict.insert(name("Contents"), Object::Ref(content_ref));
            dict.insert(name("Resources"), Object::Dict(resources));
            if !links.is_empty() {
                let mut annots = Vec::with_capacity(links.len());
                for link in links {
                    let action = match link.target {
                        LinkTarget::Uri(uri) => {
                            let mut action = Dict::new();
                            action.insert(name("S"), Object::Name(name("URI")));
                            action.insert(name("URI"), text_string(&uri));
                            action
                        }
                        LinkTarget::Page(target_index) => {
                            let target = page_refs.get(target_index).copied().ok_or_else(|| {
                                Error::Other(format!(
                                    "link target page {target_index} is out of range: the document has {page_count} pages"
                                ))
                            })?;
                            let mut action = Dict::new();
                            action.insert(name("S"), Object::Name(name("GoTo")));
                            action.insert(
                                name("D"),
                                Object::Array(vec![
                                    Object::Ref(target),
                                    Object::Name(name("XYZ")),
                                    Object::Null,
                                    Object::Null,
                                    Object::Null,
                                ]),
                            );
                            action
                        }
                    };
                    let mut annot = Dict::new();
                    annot.insert(name("Type"), Object::Name(name("Annot")));
                    annot.insert(name("Subtype"), Object::Name(name("Link")));
                    annot.insert(
                        name("Rect"),
                        Object::Array(
                            link.rect
                                .iter()
                                .map(|v| Object::Real(f64::from(*v)))
                                .collect(),
                        ),
                    );
                    annot.insert(
                        name("Border"),
                        Object::Array(vec![Object::Int(0), Object::Int(0), Object::Int(0)]),
                    );
                    annot.insert(name("A"), Object::Dict(action));
                    annots.push(Object::Ref(w.put(Object::Dict(annot))));
                }
                dict.insert(name("Annots"), Object::Array(annots));
            }
            if rotation != 0 {
                dict.insert(name("Rotate"), Object::Int(i64::from(rotation)));
            }
            w.fill(page_refs[index], Object::Dict(dict))?;
        }
        let kids: Vec<Object> = page_refs.iter().copied().map(Object::Ref).collect();
        let mut tree = Dict::new();
        tree.insert(name("Type"), Object::Name(name("Pages")));
        tree.insert(name("Count"), Object::Int(kids.len() as i64));
        tree.insert(name("Kids"), Object::Array(kids));
        w.fill(pages_root, Object::Dict(tree))?;
        let xmp_ref = match metadata {
            Some(meta) => {
                let packet = crate::xmp::packet(&meta);
                if let Some(info) = info_dict(meta) {
                    let info_ref = w.put(Object::Dict(info));
                    w.set_info(info_ref);
                }
                let mut xmp_dict = Dict::new();
                xmp_dict.insert(name("Type"), Object::Name(name("Metadata")));
                xmp_dict.insert(name("Subtype"), Object::Name(name("XML")));
                Some(w.put_stream_raw(xmp_dict, packet))
            }
            None => None,
        };
        let outline_ref = match outline {
            Some(outline) if !outline.bookmarks.is_empty() => {
                let root_ref = w.reserve();
                let refs = reserve_bookmarks(&mut w, &outline.bookmarks);
                let (first, last, count) = fill_bookmarks(
                    &mut w,
                    outline.bookmarks,
                    &refs,
                    root_ref,
                    &page_refs,
                    page_count,
                )?;
                let mut dict = Dict::new();
                dict.insert(name("Type"), Object::Name(name("Outlines")));
                dict.insert(name("First"), Object::Ref(first));
                dict.insert(name("Last"), Object::Ref(last));
                dict.insert(name("Count"), Object::Int(count));
                w.fill(root_ref, Object::Dict(dict))?;
                Some(root_ref)
            }
            _ => None,
        };
        let names = embedded_files_dict(&mut w, attachments)?;
        let page_labels_entry = page_labels_dict(page_labels)?;
        let mut catalog = Dict::new();
        catalog.insert(name("Type"), Object::Name(name("Catalog")));
        catalog.insert(name("Pages"), Object::Ref(pages_root));
        if let Some(outline_ref) = outline_ref {
            catalog.insert(name("Outlines"), Object::Ref(outline_ref));
        }
        if let Some(xmp_ref) = xmp_ref {
            catalog.insert(name("Metadata"), Object::Ref(xmp_ref));
        }
        if let Some(names) = names {
            catalog.insert(name("Names"), Object::Dict(names));
        }
        if let Some(page_labels_entry) = page_labels_entry {
            catalog.insert(name("PageLabels"), Object::Dict(page_labels_entry));
        }
        if let Some(viewer) = viewer {
            let Viewer {
                layout,
                mode,
                open_to,
            } = viewer;
            if let Some(layout) = layout {
                catalog.insert(
                    name("PageLayout"),
                    Object::Name(name(page_layout_name(layout))),
                );
            }
            if let Some(mode) = mode {
                catalog.insert(name("PageMode"), Object::Name(name(page_mode_name(mode))));
            }
            if let Some(open_to) = open_to {
                let target = page_refs.get(open_to).copied().ok_or_else(|| {
                    Error::Other(format!(
                        "open_to target page {open_to} is out of range: the document has {page_count} pages"
                    ))
                })?;
                catalog.insert(
                    name("OpenAction"),
                    Object::Array(vec![
                        Object::Ref(target),
                        Object::Name(name("XYZ")),
                        Object::Null,
                        Object::Null,
                        Object::Null,
                    ]),
                );
            }
        }
        let root = w.put(Object::Dict(catalog));
        Ok((w, root))
    }

    /// Serializes and writes the document to `path`.
    pub fn save(self, path: impl AsRef<Path>) -> Result<()> {
        let path = path.as_ref();
        let bytes = self.to_bytes()?;
        std::fs::write(path, bytes)?;
        Ok(())
    }
}

/// A `Name` from a string literal.
fn name(text: &str) -> Name {
    Name(text.to_string())
}

/// Builds the `/Info` dictionary, or `None` when every field is `None`.
fn info_dict(meta: Metadata) -> Option<Dict> {
    let mut dict = Dict::new();
    let texts = [
        ("Title", meta.title),
        ("Author", meta.author),
        ("Subject", meta.subject),
        ("Keywords", meta.keywords),
        ("Creator", meta.creator),
        ("Producer", meta.producer),
    ];
    for (key, value) in texts {
        if let Some(value) = value {
            dict.insert(name(key), text_string(&value));
        }
    }
    let dates = [
        ("CreationDate", meta.creation_date),
        ("ModDate", meta.modification_date),
    ];
    for (key, value) in dates {
        if let Some(date) = value {
            dict.insert(name(key), Object::String(date.to_pdf_string().into_bytes()));
        }
    }
    if dict.is_empty() {
        return None;
    }
    Some(dict)
}

/// Default MIME type for an [`Attachment`] whose `mime` is `None`.
const DEFAULT_ATTACHMENT_MIME: &str = "application/octet-stream";

/// Builds the catalog's `/Names` dictionary from `attachments`, or `None`
/// when there are none. Attachments are reordered by `name`, bytewise, to
/// satisfy the name tree's sorted-key requirement — string comparison in
/// Rust is already a byte comparison, so sorting `String` values sorts
/// their bytes. A repeated name is an error naming the duplicate.
fn embedded_files_dict(w: &mut Writer, mut attachments: Vec<Attachment>) -> Result<Option<Dict>> {
    if attachments.is_empty() {
        return Ok(None);
    }
    attachments.sort_by(|a, b| a.name.cmp(&b.name));
    for pair in attachments.windows(2) {
        if pair[0].name == pair[1].name {
            return Err(Error::Other(format!(
                "duplicate attachment name: {:?}",
                pair[0].name
            )));
        }
    }
    let mut entries = Vec::with_capacity(attachments.len() * 2);
    for attachment in attachments {
        let Attachment {
            name: file_name,
            data,
            mime,
            modified,
            description,
        } = attachment;
        let mime = mime.unwrap_or_else(|| DEFAULT_ATTACHMENT_MIME.to_string());

        let mut params = Dict::new();
        params.insert(name("Size"), Object::Int(data.len() as i64));
        if let Some(modified) = modified {
            params.insert(
                name("ModDate"),
                Object::String(modified.to_pdf_string().into_bytes()),
            );
        }
        let mut stream_dict = Dict::new();
        stream_dict.insert(name("Type"), Object::Name(name("EmbeddedFile")));
        stream_dict.insert(name("Subtype"), Object::Name(Name(mime)));
        stream_dict.insert(name("Params"), Object::Dict(params));
        let stream_ref = w.put_stream(stream_dict, data);

        let mut ef = Dict::new();
        ef.insert(name("F"), Object::Ref(stream_ref));

        let mut filespec = Dict::new();
        filespec.insert(name("Type"), Object::Name(name("Filespec")));
        filespec.insert(name("F"), text_string(&file_name));
        filespec.insert(name("UF"), text_string(&file_name));
        if let Some(description) = description {
            filespec.insert(name("Desc"), text_string(&description));
        }
        filespec.insert(name("EF"), Object::Dict(ef));
        let filespec_ref = w.put(Object::Dict(filespec));

        entries.push(text_string(&file_name));
        entries.push(Object::Ref(filespec_ref));
    }
    let mut name_tree = Dict::new();
    name_tree.insert(name("Names"), Object::Array(entries));
    let mut embedded_files = Dict::new();
    embedded_files.insert(name("EmbeddedFiles"), Object::Dict(name_tree));
    Ok(Some(embedded_files))
}

/// Builds the catalog's `/PageLabels` dictionary from `labels`, or `None`
/// when there are none. Ranges are reordered by `first_page` to satisfy
/// the number tree's sorted-key requirement. A non-empty set must include
/// a range starting at page 0; a repeated `first_page` is an error naming
/// the page; a `start_at` of 0 is an error naming the page, since ISO
/// 32000 page-label numbering starts at 1.
fn page_labels_dict(mut labels: Vec<PageLabel>) -> Result<Option<Dict>> {
    if labels.is_empty() {
        return Ok(None);
    }
    for label in &labels {
        if label.start_at == 0 {
            return Err(Error::Other(format!(
                "page label at page {} has start_at 0: numbering starts at 1",
                label.first_page
            )));
        }
    }
    labels.sort_by_key(|label| label.first_page);
    if labels[0].first_page != 0 {
        return Err(Error::Other("page labels must start at page 0".to_string()));
    }
    for pair in labels.windows(2) {
        if pair[0].first_page == pair[1].first_page {
            return Err(Error::Other(format!(
                "duplicate page label at page {}",
                pair[0].first_page
            )));
        }
    }
    let mut nums = Vec::with_capacity(labels.len() * 2);
    for label in labels {
        let PageLabel {
            first_page,
            style,
            prefix,
            start_at,
        } = label;
        let mut range = Dict::new();
        if let Some(style) = style {
            range.insert(name("S"), Object::Name(name(label_style_name(style))));
        }
        if let Some(prefix) = prefix {
            range.insert(name("P"), text_string(&prefix));
        }
        if start_at != 1 {
            range.insert(name("St"), Object::Int(i64::from(start_at)));
        }
        nums.push(Object::Int(first_page as i64));
        nums.push(Object::Dict(range));
    }
    let mut dict = Dict::new();
    dict.insert(name("Nums"), Object::Array(nums));
    Ok(Some(dict))
}

/// The `/S` name for a [`LabelStyle`].
fn label_style_name(style: LabelStyle) -> &'static str {
    match style {
        LabelStyle::Decimal => "D",
        LabelStyle::RomanUpper => "R",
        LabelStyle::RomanLower => "r",
        LabelStyle::LettersUpper => "A",
        LabelStyle::LettersLower => "a",
    }
}

/// The `/PageLayout` name for a [`PageLayout`].
fn page_layout_name(layout: PageLayout) -> &'static str {
    match layout {
        PageLayout::SinglePage => "SinglePage",
        PageLayout::OneColumn => "OneColumn",
        PageLayout::TwoColumnLeft => "TwoColumnLeft",
        PageLayout::TwoColumnRight => "TwoColumnRight",
        PageLayout::TwoPageLeft => "TwoPageLeft",
        PageLayout::TwoPageRight => "TwoPageRight",
    }
}

/// The `/PageMode` name for a [`PageMode`].
fn page_mode_name(mode: PageMode) -> &'static str {
    match mode {
        PageMode::UseNone => "UseNone",
        PageMode::UseOutlines => "UseOutlines",
        PageMode::UseThumbs => "UseThumbs",
        PageMode::FullScreen => "FullScreen",
    }
}

/// One bookmark's reserved object number, mirroring the tree shape so the
/// fill pass can wire parent, sibling and child refs before any of their
/// dictionary bodies exist.
struct BookmarkRef {
    r: ObjRef,
    children: Vec<BookmarkRef>,
}

/// Reserves an object number for every node in `bookmarks`, recursively —
/// the reserve half of the reserve/fill idiom: an outline item's `/Parent`,
/// `/Prev`, `/Next`, `/First` and `/Last` may all point at nodes that do
/// not have a body yet.
fn reserve_bookmarks(w: &mut Writer, bookmarks: &[Bookmark]) -> Vec<BookmarkRef> {
    bookmarks
        .iter()
        .map(|bookmark| BookmarkRef {
            r: w.reserve(),
            children: reserve_bookmarks(w, &bookmark.children),
        })
        .collect()
}

/// Fills one sibling chain of outline items against their already-reserved
/// refs: `/Title`, `/Parent`, the `/Prev`/`/Next` chain, `/Dest`, and — for
/// any bookmark with children — `/First`/`/Last`/`/Count` from a recursive
/// fill of that subtree. Returns the chain's first and last refs and the
/// total number of items in the whole subtree, which doubles as `/Count`
/// wherever the caller needs it (every bookmark is open).
fn fill_bookmarks(
    w: &mut Writer,
    bookmarks: Vec<Bookmark>,
    refs: &[BookmarkRef],
    parent: ObjRef,
    page_refs: &[ObjRef],
    page_count: usize,
) -> Result<(ObjRef, ObjRef, i64)> {
    let last_index = bookmarks.len() - 1;
    let mut total = 0i64;
    for (index, bookmark) in bookmarks.into_iter().enumerate() {
        let Bookmark {
            title,
            page,
            children,
        } = bookmark;
        let dest = page_refs.get(page).copied().ok_or_else(|| {
            Error::Other(format!(
                "bookmark target page {page} is out of range: the document has {page_count} pages"
            ))
        })?;
        let mut dict = Dict::new();
        dict.insert(name("Title"), text_string(&title));
        dict.insert(name("Parent"), Object::Ref(parent));
        if index > 0 {
            dict.insert(name("Prev"), Object::Ref(refs[index - 1].r));
        }
        if index < last_index {
            dict.insert(name("Next"), Object::Ref(refs[index + 1].r));
        }
        dict.insert(
            name("Dest"),
            Object::Array(vec![
                Object::Ref(dest),
                Object::Name(name("XYZ")),
                Object::Null,
                Object::Null,
                Object::Null,
            ]),
        );
        let mut subtree_count = 0i64;
        if !children.is_empty() {
            let (first, last, count) = fill_bookmarks(
                w,
                children,
                &refs[index].children,
                refs[index].r,
                page_refs,
                page_count,
            )?;
            dict.insert(name("First"), Object::Ref(first));
            dict.insert(name("Last"), Object::Ref(last));
            dict.insert(name("Count"), Object::Int(count));
            subtree_count = count;
        }
        w.fill(refs[index].r, Object::Dict(dict))?;
        total += 1 + subtree_count;
    }
    Ok((refs[0].r, refs[last_index].r, total))
}

/// The document-wide font object for `face`: an existing entry from
/// `font_cache` when one matches, otherwise a freshly built one that is
/// cached for the next lookup. Shared by the page loop and every nested
/// [`build_form`] so a face used both on a page and inside a group still
/// gets exactly one font object.
fn cached_font(
    w: &mut Writer,
    font_cache: &mut Vec<(Standard14, ObjRef)>,
    face: &Standard14,
) -> ObjRef {
    if let Some((_, r)) = font_cache.iter().find(|(seen, _)| seen == face) {
        return *r;
    }
    let r = w.put(Object::Dict(face.font_dict()));
    font_cache.push((*face, r));
    r
}

/// Builds one Form XObject from a registered group's parts: `/Type
/// /XObject /Subtype /Form /BBox /Resources`, with the sub-canvas's
/// operators as its content stream. Recurses for groups nested inside
/// groups, and shares `font_cache` with the page loop so nested forms
/// never duplicate a font already emitted elsewhere in the document.
fn build_form(
    w: &mut Writer,
    parts: CanvasParts,
    bbox: [f32; 4],
    font_cache: &mut Vec<(Standard14, ObjRef)>,
) -> Result<ObjRef> {
    let content = serialize_ops(&parts.ops);
    let mut fonts = Dict::new();
    for (index, face) in parts.fonts.iter().enumerate() {
        let font_ref = cached_font(w, font_cache, face);
        fonts.insert(Name(format!("F{}", index + 1)), Object::Ref(font_ref));
    }
    let mut xobjects = Dict::new();
    for (index, image) in parts.images.iter().enumerate() {
        let image_ref = image.build_xobject(w);
        xobjects.insert(Name(format!("Im{}", index + 1)), Object::Ref(image_ref));
    }
    for (index, (group_parts, group_bbox)) in parts.groups.into_iter().enumerate() {
        let group_ref = build_form(w, group_parts, group_bbox, font_cache)?;
        xobjects.insert(Name(format!("Gp{}", index + 1)), Object::Ref(group_ref));
    }
    let mut ext_gstates = Dict::new();
    for (index, state) in parts.gstates.iter().enumerate() {
        let gstate_ref = w.put(Object::Dict(state.ext_gstate_dict()));
        ext_gstates.insert(Name(format!("Gs{}", index + 1)), Object::Ref(gstate_ref));
    }
    let mut resources = Dict::new();
    if !fonts.is_empty() {
        resources.insert(name("Font"), Object::Dict(fonts));
    }
    if !xobjects.is_empty() {
        resources.insert(name("XObject"), Object::Dict(xobjects));
    }
    if !ext_gstates.is_empty() {
        resources.insert(name("ExtGState"), Object::Dict(ext_gstates));
    }
    let mut dict = Dict::new();
    dict.insert(name("Type"), Object::Name(name("XObject")));
    dict.insert(name("Subtype"), Object::Name(name("Form")));
    dict.insert(
        name("BBox"),
        Object::Array(bbox.iter().map(|v| Object::Real(f64::from(*v))).collect()),
    );
    dict.insert(name("Resources"), Object::Dict(resources));
    Ok(w.put_stream(dict, content))
}

/// Encodes a text string (ISO 32000 §7.9.2.2): pure ASCII passes through
/// as its own bytes, anything else becomes UTF-16BE with a `FE FF` byte
/// order mark.
fn text_string(value: &str) -> Object {
    if value.is_ascii() {
        return Object::String(value.as_bytes().to_vec());
    }
    let mut bytes = vec![0xFE, 0xFF];
    for unit in value.encode_utf16() {
        bytes.extend_from_slice(&unit.to_be_bytes());
    }
    Object::String(bytes)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn dimensions_match_the_contract() {
        assert_eq!(PageSize::A3.dimensions(), (841.89, 1190.55));
        assert_eq!(PageSize::A4.dimensions(), (595.28, 841.89));
        assert_eq!(PageSize::A5.dimensions(), (419.53, 595.28));
        assert_eq!(PageSize::Letter.dimensions(), (612.0, 792.0));
        assert_eq!(PageSize::Legal.dimensions(), (612.0, 1008.0));
        assert_eq!(
            PageSize::Custom {
                width: 10.0,
                height: 20.0
            }
            .dimensions(),
            (10.0, 20.0)
        );
    }

    #[test]
    fn by_name_parses_the_five_named_sizes_case_insensitively() {
        for (name, expected) in [
            ("a3", PageSize::A3),
            ("A4", PageSize::A4),
            ("a5", PageSize::A5),
            ("Letter", PageSize::Letter),
            ("LEGAL", PageSize::Legal),
        ] {
            assert_eq!(PageSize::by_name(name), Some(expected), "{name}");
        }
    }

    #[test]
    fn by_name_rejects_anything_else() {
        assert_eq!(PageSize::by_name("tabloid"), None);
        assert_eq!(PageSize::by_name(""), None);
    }

    #[test]
    fn landscape_swaps_into_custom() {
        assert_eq!(
            PageSize::A4.landscape(),
            PageSize::Custom {
                width: 841.89,
                height: 595.28
            }
        );
        assert_eq!(
            PageSize::Custom {
                width: 1.0,
                height: 2.0
            }
            .landscape(),
            PageSize::Custom {
                width: 2.0,
                height: 1.0
            }
        );
        assert_eq!(PageSize::Letter.landscape().dimensions(), (792.0, 612.0));
    }

    #[test]
    fn date_utc_formats_with_z() {
        let date = Date {
            year: 2026,
            month: 8,
            day: 27,
            hour: 12,
            minute: 30,
            second: 15,
            utc_offset_minutes: 0,
        };
        assert_eq!(date.to_pdf_string(), "D:20260827123015Z");
    }

    #[test]
    fn date_positive_offset_pads_single_digits() {
        let date = Date {
            year: 987,
            month: 1,
            day: 2,
            hour: 3,
            minute: 4,
            second: 5,
            utc_offset_minutes: 120,
        };
        assert_eq!(date.to_pdf_string(), "D:09870102030405+02'00");
    }

    #[test]
    fn date_negative_offset_keeps_minutes() {
        let date = Date {
            year: 1999,
            month: 12,
            day: 31,
            hour: 23,
            minute: 59,
            second: 58,
            utc_offset_minutes: -330,
        };
        assert_eq!(date.to_pdf_string(), "D:19991231235958-05'30");
    }

    #[test]
    fn iso8601_utc_formats_with_z() {
        let date = Date {
            year: 2026,
            month: 8,
            day: 27,
            hour: 12,
            minute: 30,
            second: 15,
            utc_offset_minutes: 0,
        };
        assert_eq!(date.to_iso8601(), "2026-08-27T12:30:15Z");
    }

    #[test]
    fn iso8601_positive_offset_pads_single_digits() {
        let date = Date {
            year: 987,
            month: 1,
            day: 2,
            hour: 3,
            minute: 4,
            second: 5,
            utc_offset_minutes: 120,
        };
        assert_eq!(date.to_iso8601(), "0987-01-02T03:04:05+02:00");
    }

    #[test]
    fn iso8601_negative_offset_keeps_minutes() {
        let date = Date {
            year: 1999,
            month: 12,
            day: 31,
            hour: 23,
            minute: 59,
            second: 58,
            utc_offset_minutes: -330,
        };
        assert_eq!(date.to_iso8601(), "1999-12-31T23:59:58-05:30");
    }

    /// Two pages with text and an image — enough to exercise fonts,
    /// XObjects and the reserved page tree through every write path.
    fn two_page_doc() -> Pdf {
        let mut first = Page::new(PageSize::A4);
        first
            .canvas
            .text("Streamed parity", 72.0, 720.0, Standard14::Helvetica, 14.0)
            .expect("ASCII encodes");
        let image = crate::image::ImageData::gray8(2, 2, vec![0, 85, 170, 255])
            .expect("2x2 grayscale builds");
        let handle = first.canvas.add_image(image);
        first.canvas.draw_image(handle, 72.0, 400.0, 144.0, 144.0);
        let mut second = Page::new(PageSize::Letter);
        second
            .canvas
            .text("Page two", 72.0, 700.0, Standard14::TimesRoman, 12.0)
            .expect("ASCII encodes");
        Pdf {
            pages: vec![first, second],
            ..Pdf::default()
        }
    }

    /// The three write paths are one assembly and one emission: identical
    /// bytes whether buffered, streamed into an `io::Write`, or streamed
    /// into an async sink.
    #[test]
    fn write_into_and_write_into_with_match_to_bytes() {
        let bytes = two_page_doc().to_bytes().expect("to_bytes succeeds");
        let mut via_io = Vec::new();
        two_page_doc()
            .write_into(&mut via_io)
            .expect("write_into succeeds");
        assert_eq!(via_io, bytes);
        let via_sink = pdfboss_core::block_on(two_page_doc().write_into_with(Vec::new()))
            .expect("write_into_with succeeds");
        assert_eq!(via_sink, bytes);
    }

    #[test]
    fn zero_page_document_is_an_error() {
        let err = Pdf::default()
            .to_bytes()
            .expect_err("a page-less document must not serialize");
        assert!(err.to_string().contains("at least one page"), "{err}");
    }
}