lightweight-pdf-writer 0.3.0

Minimal PDF object/xref/stream writer for lightweight-pdf, zero required dependencies (FlateDecode compression via the optional miniz_oxide)
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
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
use crate::writer::{fmt_num, PdfWriter, Ref};

/// `/Producer` is always set (unlike the other `/Info` fields, which are
/// opt-in) — it identifies the generator, not the document, so there's no
/// caller-supplied value to opt out of.
const PRODUCER: &str = concat!("lightweight-pdf ", env!("CARGO_PKG_VERSION"));

/// A subset, embedded TrueType font written as `/Subtype /Type0` with a
/// `/CIDFontType2` descendant (ADR-012: Identity-H, `CIDToGIDMap`,
/// `ToUnicode`). CID space equals the subset's own glyph-index space (the
/// facade assigns CIDs that way), so `CIDToGIDMap` is always `/Identity`
/// and no separate CID-to-GID stream is needed.
pub struct CidFont {
    pub base_font: String,
    /// Already-subset sfnt bytes (`lightweight-pdf-fonts::subset_font`).
    pub subset_bytes: Vec<u8>,
    /// Advance width per CID, `widths[cid]` — CIDs `0..widths.len()` are
    /// assumed consecutive (true by construction: CID == subset GID).
    pub widths: Vec<f32>,
    pub ascent: f32,
    pub descent: f32,
    pub cap_height: f32,
    pub italic_angle: f32,
    pub bbox: (f32, f32, f32, f32),
    pub is_italic: bool,
    pub is_bold: bool,
    /// `(CID, Unicode scalar)` pairs for the `ToUnicode` CMap — what makes
    /// the text copyable/searchable despite going through Identity-H CIDs.
    pub to_unicode: Vec<(u16, char)>,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ColorSpace {
    DeviceGray,
    DeviceRgb,
}

impl ColorSpace {
    fn as_pdf_name(self) -> &'static str {
        match self {
            ColorSpace::DeviceGray => "DeviceGray",
            ColorSpace::DeviceRgb => "DeviceRGB",
        }
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ImageDataFilter {
    /// Raw samples — Flate-compressed like any other stream by default
    /// (ADR-016), unlike `DctDecode` below.
    None,
    /// The original JPEG bytes, embedded byte-for-byte (`phases/
    /// phase-5-images.md` step 2: "kein Neukodieren").
    DctDecode,
}

/// One embeddable `/Subtype /Image` XObject (ISO 32000-1 8.9.5), named for
/// that specific PDF construct the same way `CidFont` is named for its
/// (`Type0`/`CIDFontType2`) construct, rather than for the generic Pdf-noun
/// pattern used by [`PdfPage`]/[`PdfDocument`]/[`PdfWriter`] (those name the
/// crate's document-structure types; this and `CidFont` name embeddable
/// resource types). `smask`, if present, is itself an `ImageXObject`
/// (always `DeviceGray`, `filter: None`, no further `smask`) — PNG alpha,
/// per ADR-013.
pub struct ImageXObject {
    pub width_px: u32,
    pub height_px: u32,
    pub color_space: ColorSpace,
    pub bits_per_component: u8,
    pub filter: ImageDataFilter,
    pub bytes: Vec<u8>,
    pub smask: Option<Box<ImageXObject>>,
}

#[derive(Clone, Debug)]
pub enum PdfLinkAction {
    /// `/A << /S /URI /URI (...) >>` — an external link.
    Uri(String),
    /// `/Dest [pageRef /XYZ null y null]` — an internal jump target.
    /// `page_index` is resolved against the writer's own `page_refs`
    /// (built before any page is written, so a forward reference to a
    /// later page is fine) at write time, not by the caller.
    GoTo { page_index: usize, y: f32 },
}

#[derive(Clone, Debug)]
pub struct PdfLinkAnnotation {
    pub rect: (f32, f32, f32, f32),
    pub action: PdfLinkAction,
}

#[derive(Default)]
pub struct PdfPage {
    pub width: f32,
    pub height: f32,
    pub content: Vec<u8>,
    pub annotations: Vec<PdfLinkAnnotation>,
}

/// One entry in the `/Outlines` bookmark tree (`Text::outline_level`,
/// resolved). `page_index`/`y` mean the same thing as `PdfLinkAction::GoTo`
/// — resolved against `page_refs` at write time, not by the caller.
#[derive(Clone, Debug)]
pub struct PdfOutlineNode {
    pub title: String,
    pub page_index: usize,
    pub y: f32,
    pub children: Vec<PdfOutlineNode>,
}

#[derive(Clone, Debug, Default)]
pub struct PdfMetadata {
    pub title: Option<String>,
    pub author: Option<String>,
    pub subject: Option<String>,
    pub keywords: Option<String>,
    pub creator: Option<String>,
    /// Already-formatted PDF date strings (`D:YYYYMMDDHHmmSSZ`) — this
    /// crate has no date logic of its own, the facade formats
    /// `lightweight_pdf_core::PdfDate` before handing it over.
    pub creation_date: Option<String>,
    pub mod_date: Option<String>,
    /// ISO 8601 versions of the two dates above, for XMP (`xmp:CreateDate`/
    /// `xmp:ModifyDate`, issue #25) — a second field rather than
    /// reformatting `creation_date`/`mod_date` here, keeping this crate's
    /// "no date logic of its own" property (see above): the facade
    /// already has `PdfDate` and formats both strings from it.
    #[cfg(feature = "pdf-a")]
    pub xmp_creation_date: Option<String>,
    #[cfg(feature = "pdf-a")]
    pub xmp_mod_date: Option<String>,
}

#[derive(Default)]
pub struct PdfDocument {
    fonts: Vec<CidFont>,
    images: Vec<ImageXObject>,
    pages: Vec<PdfPage>,
    pub metadata: PdfMetadata,
    /// Top-level bookmark entries; empty means no `/Outlines` object at
    /// all (not an empty one — a reader shouldn't see a bookmark panel
    /// with nothing in it for a document with no headings).
    pub outline: Vec<PdfOutlineNode>,
    /// Set by the facade when `Document::pdf_a3b()` was called (issue
    /// #25) — adds XMP metadata, `/OutputIntent` (embedded sRGB ICC
    /// profile) and a transparency-group colour space per page.
    #[cfg(feature = "pdf-a")]
    pub pdf_a3b: bool,
    /// Set by the facade when `Document::zugferd_xml()` was called
    /// (issue #26) — the raw ZUGFeRD/Factur-X invoice XML to embed.
    #[cfg(feature = "zugferd")]
    pub zugferd_xml: Option<Vec<u8>>,
    /// Catalog `/Lang` (issue #27) — always available, not gated on
    /// `tagged-pdf`: cheap, and meaningful to any reader/screen reader
    /// regardless of whether the rest of the document is tagged.
    pub lang: Option<String>,
    /// Set by the facade when `Document::pdf_ua()` was called (issue
    /// #27) — adds `/MarkInfo`, the `pdfuaid:*` XMP properties, and (via
    /// `struct_tree`, populated by the facade during rendering)
    /// `/StructTreeRoot`.
    #[cfg(feature = "tagged-pdf")]
    pub pdf_ua: bool,
    /// The structure tree's root `Document` element, built by the facade
    /// while rendering (mirrors how `outline` is built by
    /// `text::build_outline`) — `None` until rendering finishes filling
    /// it in, even when `pdf_ua` is set.
    #[cfg(feature = "tagged-pdf")]
    pub struct_tree: Option<crate::struct_tree::PdfStructNode>,
}

impl PdfDocument {
    pub fn new() -> Self {
        Self::default()
    }

    /// Registers a font, returning its index (used to build the resource
    /// name `F{index + 1}` referenced from content streams via
    /// [`Self::font_resource_name`]).
    pub fn add_font(&mut self, font: CidFont) -> usize {
        self.fonts.push(font);
        self.fonts.len() - 1
    }

    pub fn font_resource_name(index: usize) -> String {
        format!("F{}", index + 1)
    }

    /// Registers an image, returning its index (used to build the
    /// resource name `Im{index + 1}`).
    pub fn add_image(&mut self, image: ImageXObject) -> usize {
        self.images.push(image);
        self.images.len() - 1
    }

    pub fn image_resource_name(index: usize) -> String {
        format!("Im{}", index + 1)
    }

    pub fn add_page(&mut self, page: PdfPage) {
        self.pages.push(page);
    }

    /// `self.pdf_a3b` when the `pdf-a` feature is compiled in, `false`
    /// otherwise — one place for the `#[cfg(...)]` instead of scattering
    /// it through `write()`.
    #[cfg(feature = "pdf-a")]
    fn is_pdf_a3b(&self) -> bool {
        self.pdf_a3b
    }

    #[cfg(not(feature = "pdf-a"))]
    fn is_pdf_a3b(&self) -> bool {
        false
    }

    /// FontDescriptor `/Flags`: bit 6 (32) = Nonsymbolic, bit 7 (64) =
    /// Italic when applicable.
    fn descriptor_flags(font: &CidFont) -> u32 {
        let mut flags = 32u32;
        if font.is_italic {
            flags |= 64;
        }
        flags
    }

    /// `/ToUnicode` CMap program body: maps each CID back to its Unicode
    /// scalar so text stays copyable/searchable despite Identity-H
    /// encoding. Chunked into groups of <=100 `bfchar` entries, the
    /// conventional safe limit for CMap resources.
    fn to_unicode_cmap(font: &CidFont) -> Vec<u8> {
        let mut body = String::new();
        body.push_str("/CIDInit /ProcSet findresource begin\n");
        body.push_str("12 dict begin\n");
        body.push_str("begincmap\n");
        body.push_str("/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n");
        body.push_str("/CMapName /Adobe-Identity-UCS def\n");
        body.push_str("/CMapType 2 def\n");
        body.push_str("1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n");
        for chunk in font.to_unicode.chunks(100) {
            body.push_str(&format!("{} beginbfchar\n", chunk.len()));
            for &(cid, ch) in chunk {
                let utf16: Vec<u16> = ch.encode_utf16(&mut [0u16; 2]).to_vec();
                let hex: String = utf16.iter().map(|u| format!("{u:04X}")).collect();
                body.push_str(&format!("<{cid:04X}> <{hex}>\n"));
            }
            body.push_str("endbfchar\n");
        }
        body.push_str("endcmap\n");
        body.push_str("CMapType findresource /CMap defineresource pop\n");
        body.push_str("end\n");
        body.push_str("end");
        body.into_bytes()
    }

    /// The ICC Consortium's own reference sRGB profile (v4, `sRGB2014.icc`,
    /// 3 KiB) — "may be copied, distributed, embedded, made, used, and
    /// sold without restriction" per color.org's own license terms for
    /// this file, unaltered here. Small enough that PDF/A-3b's mandatory
    /// `/OutputIntent` (ISO 19005-3 6.2.4.3) barely moves output size —
    /// see issue #25's size-impact question.
    #[cfg(feature = "pdf-a")]
    const SRGB_ICC_PROFILE: &[u8] = include_bytes!("../assets/sRGB2014.icc");

    /// Writes the embedded-ICC-profile stream and the `/OutputIntent`
    /// dictionary that references it, returning the latter's ref (what
    /// `/OutputIntents` in the Catalog holds an array of).
    #[cfg(feature = "pdf-a")]
    fn write_output_intent(w: &mut PdfWriter) -> Ref {
        let profile_ref = w.alloc();
        w.compressed_stream(profile_ref, "/N 3", Self::SRGB_ICC_PROFILE);
        let intent_ref = w.alloc();
        w.object(
            intent_ref,
            &format!(
                "<< /Type /OutputIntent /S /GTS_PDFA1 /OutputConditionIdentifier (sRGB IEC61966-2.1) /Info (sRGB IEC61966-2.1) /DestOutputProfile {} >>",
                profile_ref.write()
            ),
        );
        intent_ref
    }

    /// Writes the XMP metadata stream (issue #25) and returns its ref —
    /// `/Type /Metadata /Subtype /XML`, left uncompressed (conventional
    /// for XMP packets: some tooling scans for `<?xpacket` directly
    /// without going through `/FlateDecode`).
    #[cfg(feature = "pdf-a")]
    fn write_xmp_metadata(w: &mut PdfWriter, metadata: &PdfMetadata, zugferd: bool, pdf_ua: bool) -> Ref {
        let xmp = build_xmp_packet(metadata, zugferd, pdf_ua);
        let id = w.alloc();
        w.stream(id, "/Type /Metadata /Subtype /XML", xmp.as_bytes());
        id
    }

    /// `self.zugferd_xml.is_some()` when the `zugferd` feature is
    /// compiled in, `false` otherwise (issue #26) — mirrors
    /// [`Self::is_pdf_a3b`].
    #[cfg(feature = "zugferd")]
    fn is_zugferd(&self) -> bool {
        self.zugferd_xml.is_some()
    }

    #[cfg(all(feature = "pdf-a", not(feature = "zugferd")))]
    fn is_zugferd(&self) -> bool {
        false
    }

    /// `self.pdf_ua` when the `tagged-pdf` feature is compiled in,
    /// `false` otherwise (issue #27) — mirrors [`Self::is_pdf_a3b`].
    #[cfg(feature = "tagged-pdf")]
    fn is_pdf_ua(&self) -> bool {
        self.pdf_ua
    }

    #[cfg(not(feature = "tagged-pdf"))]
    fn is_pdf_ua(&self) -> bool {
        false
    }

    /// Writes the embedded-file stream + file specification for the
    /// ZUGFeRD/Factur-X XML (issue #26, ISO 19005-3 6.8) and returns the
    /// file specification's ref — what `/AF` and `/Names/EmbeddedFiles`
    /// in the Catalog both point at (the same object, two different
    /// discovery mechanisms: `/AF` is PDF/A-3's own "this is associated
    /// with the document" marker, `/Names/EmbeddedFiles` is the older,
    /// universal attachments name tree most PDF viewers use for their
    /// attachments panel).
    #[cfg(feature = "zugferd")]
    fn write_zugferd_attachment(w: &mut PdfWriter, xml: &[u8]) -> Ref {
        const FILENAME: &str = "factur-x.xml";
        let file_ref = w.alloc();
        w.compressed_stream(file_ref, "/Type /EmbeddedFile /Subtype /text#2Fxml", xml);
        let filespec_ref = w.alloc();
        let name = format_pdf_string(FILENAME);
        w.object(
            filespec_ref,
            &format!(
                "<< /Type /Filespec /F {name} /UF {name} /AFRelationship /Alternative /EF << /F {file} /UF {file} >> >>",
                file = file_ref.write(),
            ),
        );
        filespec_ref
    }

    /// The Catalog-level `/AF`/`/Names/EmbeddedFiles` entries for the
    /// ZUGFeRD attachment, or an empty string if none is set — mirrors
    /// [`Self::is_pdf_a3b`]/[`Self::is_zugferd`]'s always-present-dispatch
    /// shape so the `pdf-a`-only build (no `zugferd`) needs no `#[cfg]`
    /// at the call site.
    #[cfg(feature = "zugferd")]
    fn write_zugferd_catalog_entry(&self, w: &mut PdfWriter) -> String {
        match self.zugferd_xml.as_deref() {
            Some(xml) => {
                let filespec_ref = Self::write_zugferd_attachment(w, xml);
                format!(
                    " /AF [{fs}] /Names << /EmbeddedFiles << /Names [(factur-x.xml) {fs}] >> >>",
                    fs = filespec_ref.write()
                )
            }
            None => String::new(),
        }
    }

    #[cfg(all(feature = "pdf-a", not(feature = "zugferd")))]
    fn write_zugferd_catalog_entry(&self, _w: &mut PdfWriter) -> String {
        String::new()
    }

    /// Writes one image XObject (recursing once for `smask`, PNG alpha)
    /// and returns its object reference.
    fn write_image(w: &mut PdfWriter, image: &ImageXObject) -> Ref {
        let smask_ref = image.smask.as_deref().map(|m| Self::write_image(w, m));
        let image_ref = w.alloc();
        let filter = match image.filter {
            ImageDataFilter::None => String::new(),
            ImageDataFilter::DctDecode => " /Filter /DCTDecode".to_string(),
        };
        // `smask` is a genuinely optional field (most images carry no alpha
        // mask) — omitting `/SMask` when absent is not a swallowed error.
        let smask_entry = match smask_ref {
            Some(r) => format!(" /SMask {}", r.write()),
            None => String::new(),
        };
        let dict = format!(
            "/Type /XObject /Subtype /Image /Width {w} /Height {h} /ColorSpace /{cs} /BitsPerComponent {bpc}{filter}{smask}",
            w = image.width_px,
            h = image.height_px,
            cs = image.color_space.as_pdf_name(),
            bpc = image.bits_per_component,
            filter = filter,
            smask = smask_entry,
        );
        // JPEG samples (DctDecode) are already compressed — re-deflating
        // near-random bytes wastes CPU for ~0 size benefit, so only raw
        // (None) samples go through the compressing path.
        match image.filter {
            ImageDataFilter::None => w.compressed_stream(image_ref, &dict, &image.bytes),
            ImageDataFilter::DctDecode => w.stream(image_ref, &dict, &image.bytes),
        }
        image_ref
    }

    /// Maps each item through `f` and joins the results with a single
    /// space — shared by [`Self::write_fonts`]'s glyph-width array and
    /// [`Self::write`]'s `/Kids` array.
    fn join_with_space<T>(items: &[T], f: impl Fn(&T) -> String) -> String {
        items.iter().map(f).collect::<Vec<_>>().join(" ")
    }

    /// Formats `/Name Ref` resource-dictionary entries (space-joined) for a
    /// sequence of object refs — shared by [`Self::write_fonts`]'s `/Font`
    /// entries and [`Self::write`]'s `/XObject` entries.
    fn resource_entries(refs: &[Ref], name_fn: impl Fn(usize) -> String) -> String {
        refs.iter()
            .enumerate()
            .map(|(i, r)| format!("/{} {}", name_fn(i), r.write()))
            .collect::<Vec<_>>()
            .join(" ")
    }

    /// Writes all font objects (Type0 + CIDFontType2 + FontDescriptor +
    /// embedded subset FontFile2 + ToUnicode) and returns the `/Font`
    /// resource-dictionary entries for the page objects. Zips `fonts` with
    /// their pre-allocated refs rather than indexing by position, so the
    /// pairing can't panic even if the two ever fell out of step.
    fn write_fonts(w: &mut PdfWriter, fonts: &[CidFont]) -> String {
        let font_refs: Vec<(Ref, Ref, Ref, Ref)> = fonts.iter().map(|_| (w.alloc(), w.alloc(), w.alloc(), w.alloc())).collect();

        for (font, &(type0_ref, cid_ref, descriptor_ref, file_ref)) in fonts.iter().zip(&font_refs) {
            let to_unicode_ref = w.alloc();

            let widths_str = Self::join_with_space(&font.widths, |w| fmt_num(*w));

            w.object(
                type0_ref,
                &format!(
                    "<< /Type /Font /Subtype /Type0 /BaseFont /{base} /Encoding /Identity-H /DescendantFonts [{cid}] /ToUnicode {tu} >>",
                    base = font.base_font,
                    cid = cid_ref.write(),
                    tu = to_unicode_ref.write(),
                ),
            );
            w.object(
                cid_ref,
                &format!(
                    "<< /Type /Font /Subtype /CIDFontType2 /BaseFont /{base} /CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> /FontDescriptor {desc} /DW 1000 /W [0 [{widths}]] /CIDToGIDMap /Identity >>",
                    base = font.base_font,
                    desc = descriptor_ref.write(),
                    widths = widths_str,
                ),
            );
            w.object(
                descriptor_ref,
                &format!(
                    "<< /Type /FontDescriptor /FontName /{base} /Flags {flags} /FontBBox [{bx0} {by0} {bx1} {by1}] /ItalicAngle {italic} /Ascent {ascent} /Descent {descent} /CapHeight {cap} /StemV {stemv} /FontFile2 {file} >>",
                    base = font.base_font,
                    flags = Self::descriptor_flags(font),
                    bx0 = fmt_num(font.bbox.0),
                    by0 = fmt_num(font.bbox.1),
                    bx1 = fmt_num(font.bbox.2),
                    by1 = fmt_num(font.bbox.3),
                    italic = fmt_num(font.italic_angle),
                    ascent = fmt_num(font.ascent),
                    descent = fmt_num(font.descent),
                    cap = fmt_num(font.cap_height),
                    stemv = if font.is_bold { 120 } else { 80 },
                    file = file_ref.write(),
                ),
            );
            w.compressed_stream(file_ref, &format!("/Length1 {}", font.subset_bytes.len()), &font.subset_bytes);
            w.compressed_stream(to_unicode_ref, "", &Self::to_unicode_cmap(font));
        }

        let type0_refs: Vec<Ref> = font_refs.iter().map(|&(t, ..)| t).collect();
        Self::resource_entries(&type0_refs, Self::font_resource_name)
    }

    /// Writes each page's `/Page` object and content stream and returns the
    /// page object refs (used by the caller to build the `/Pages /Kids`
    /// array). Zips `pages` with their pre-allocated refs rather than
    /// indexing by position, so the pairing can't panic even if the two
    /// ever fell out of step.
    fn write_pages(
        w: &mut PdfWriter,
        pages: &[PdfPage],
        pages_ref: Ref,
        font_resources: &str,
        image_resources: &str,
        pdf_a3b: bool,
        pdf_ua: bool,
    ) -> Vec<Ref> {
        let page_refs: Vec<Ref> = (0..pages.len()).map(|_| w.alloc()).collect();
        let content_refs: Vec<Ref> = (0..pages.len()).map(|_| w.alloc()).collect();

        for (page_index, ((page, &page_ref), &content_ref)) in pages.iter().zip(&page_refs).zip(&content_refs).enumerate() {
            let mut annot_refs = Vec::new();
            for annot in &page.annotations {
                let id = w.alloc();
                let action = match &annot.action {
                    PdfLinkAction::Uri(uri) => format!("/A << /S /URI /URI {} >>", format_pdf_string(uri)),
                    PdfLinkAction::GoTo { page_index, y } => {
                        // Falls back to this annotation's own page if
                        // `page_index` is somehow out of range — a link to
                        // itself is a harmless no-op, not a broken PDF.
                        let target = page_refs.get(*page_index).copied().unwrap_or(page_ref);
                        format!("/Dest [{} /XYZ null {} null]", target.write(), fmt_num(*y))
                    }
                };
                // PDF/A-3b (ISO 19005-3 6.5.2): every annotation needs an
                // `/F` flags entry — `4` is the Print bit alone (Hidden/
                // NoView unset, both forbidden by the same clause).
                let flags_entry = if pdf_a3b { " /F 4" } else { "" };
                w.object(
                    id,
                    &format!(
                        "<< /Type /Annot /Subtype /Link /Rect [{x0} {y0} {x1} {y1}] /Border [0 0 0]{flags} {action} >>",
                        x0 = fmt_num(annot.rect.0),
                        y0 = fmt_num(annot.rect.1),
                        x1 = fmt_num(annot.rect.2),
                        y1 = fmt_num(annot.rect.3),
                        flags = flags_entry,
                    ),
                );
                annot_refs.push(id);
            }

            let annots_entry = if !annot_refs.is_empty() {
                let refs = Self::join_with_space(&annot_refs, |r| r.write());
                format!(" /Annots [{refs}]")
            } else {
                String::new()
            };

            // PDF/A-3b (issue #25, ISO 19005-3 6.2.10): a page with a
            // transparent object (PNG alpha via `/SMask`) needs a defined
            // blending colour space — declared once per page rather than
            // only on pages that actually use transparency, since that's
            // simpler and costs a few bytes.
            let group_entry = if pdf_a3b {
                " /Group << /Type /Group /S /Transparency /CS /DeviceRGB >>"
            } else {
                ""
            };

            // Issue #27: `/StructParents` is this page's key into
            // `/ParentTree` (`struct_tree::write_struct_tree` assigns
            // every page `0..page_refs.len()`, matching `page_index` here
            // exactly).
            let struct_parents_entry = if pdf_ua {
                format!(" /StructParents {page_index}")
            } else {
                String::new()
            };

            w.object(
                page_ref,
                &format!(
                    "<< /Type /Page /Parent {parent} /MediaBox [0 0 {w} {h}] /Resources << /Font << {fonts} >> /XObject << {images} >> >>{group}{struct_parents} /Contents {content}{annots} >>",
                    parent = pages_ref.write(),
                    w = fmt_num(page.width),
                    h = fmt_num(page.height),
                    fonts = font_resources,
                    images = image_resources,
                    group = group_entry,
                    struct_parents = struct_parents_entry,
                    content = content_ref.write(),
                    annots = annots_entry,
                ),
            );
            w.compressed_stream(content_ref, "", &page.content);
        }

        page_refs
    }

    /// Writes the `/Outlines` bookmark tree and returns its object ref, or
    /// `None` if `outline` is empty — a document with no headings gets no
    /// `/Outlines` entry at all, not an empty bookmark panel. Two passes:
    /// [`alloc_outline_refs`] allocates one `Ref` per node first (so
    /// siblings/parents can reference each other regardless of write
    /// order), [`write_outline_siblings`] then writes every node's dict.
    fn write_outline(w: &mut PdfWriter, outline: &[PdfOutlineNode], page_refs: &[Ref]) -> Option<Ref> {
        if outline.is_empty() {
            return None;
        }
        let outlines_ref = w.alloc();
        let ref_tree = alloc_outline_refs(w, outline);
        write_outline_siblings(w, outline, &ref_tree, outlines_ref, page_refs);

        let total_count: i64 = outline.iter().map(|n| 1 + count_descendants(n)).sum();
        let first = ref_tree.first().map(|t| t.r);
        let last = ref_tree.last().map(|t| t.r);
        let mut entries = vec!["/Type /Outlines".to_string(), format!("/Count {total_count}")];
        if let Some(f) = first {
            entries.push(format!("/First {}", f.write()));
        }
        if let Some(l) = last {
            entries.push(format!("/Last {}", l.write()));
        }
        w.object(outlines_ref, &format!("<< {} >>", entries.join(" ")));
        Some(outlines_ref)
    }

    /// Assembles the full PDF byte stream: Catalog, Pages, Page objects,
    /// content streams, fonts (Type0 + CIDFontType2 + FontDescriptor +
    /// embedded subset FontFile2 + ToUnicode), images (XObjects + optional
    /// SMask), xref and trailer.
    pub fn write(&self) -> Vec<u8> {
        let mut w = PdfWriter::new();

        let catalog_ref = w.alloc();
        let pages_ref = w.alloc();

        let image_refs: Vec<Ref> = self.images.iter().map(|img| Self::write_image(&mut w, img)).collect();
        let image_resources = Self::resource_entries(&image_refs, Self::image_resource_name);

        let pdf_a3b = self.is_pdf_a3b();
        let pdf_ua = self.is_pdf_ua();

        let font_resources = Self::write_fonts(&mut w, &self.fonts);
        let page_refs = Self::write_pages(&mut w, &self.pages, pages_ref, &font_resources, &image_resources, pdf_a3b, pdf_ua);

        let kids = Self::join_with_space(&page_refs, |r| r.write());
        w.object(pages_ref, &format!("<< /Type /Pages /Kids [{kids}] /Count {} >>", self.pages.len()));

        let outlines_entry = match Self::write_outline(&mut w, &self.outline, &page_refs) {
            Some(outlines_ref) => format!(" /Outlines {}", outlines_ref.write()),
            None => String::new(),
        };

        #[cfg(feature = "pdf-a")]
        let pdf_a_entry = if pdf_a3b {
            let output_intent_ref = Self::write_output_intent(&mut w);
            let metadata_ref = Self::write_xmp_metadata(&mut w, &self.metadata, self.is_zugferd(), pdf_ua);
            let zugferd_entry = self.write_zugferd_catalog_entry(&mut w);
            format!(
                " /OutputIntents [{}] /Metadata {}{zugferd_entry}",
                output_intent_ref.write(),
                metadata_ref.write()
            )
        } else {
            String::new()
        };
        #[cfg(not(feature = "pdf-a"))]
        let pdf_a_entry = String::new();

        #[cfg(feature = "tagged-pdf")]
        let tagged_entry = if pdf_ua {
            use crate::struct_tree::{write_struct_tree, PdfStructNode};
            let empty_root = PdfStructNode::Elem {
                tag: "Document",
                alt: None,
                attrs: None,
                children: Vec::new(),
            };
            let root = self.struct_tree.as_ref().unwrap_or(&empty_root);
            let (struct_tree_root_ref, _struct_parents) = write_struct_tree(&mut w, root, &page_refs);
            // `/ViewerPreferences /DisplayDocTitle true` (ISO 14289-1
            // 7.1, "the DisplayDocTitle... shall be true") — found via
            // an actual veraPDF PDF/UA run, not from the spec text
            // alone.
            format!(
                " /StructTreeRoot {} /MarkInfo << /Marked true >> /ViewerPreferences << /DisplayDocTitle true >>",
                struct_tree_root_ref.write()
            )
        } else {
            String::new()
        };
        #[cfg(not(feature = "tagged-pdf"))]
        let tagged_entry = String::new();

        let lang_entry = match &self.lang {
            Some(lang) => format!(" /Lang {}", format_pdf_string(lang)),
            None => String::new(),
        };

        w.object(
            catalog_ref,
            &format!(
                "<< /Type /Catalog /Pages {}{outlines_entry}{pdf_a_entry}{tagged_entry}{lang_entry} >>",
                pages_ref.write()
            ),
        );

        let mut info_entries = Vec::new();
        if let Some(ref title) = self.metadata.title {
            info_entries.push(format!("/Title {}", format_pdf_string(title)));
        }
        if let Some(ref author) = self.metadata.author {
            info_entries.push(format!("/Author {}", format_pdf_string(author)));
        }
        if let Some(ref subject) = self.metadata.subject {
            info_entries.push(format!("/Subject {}", format_pdf_string(subject)));
        }
        if let Some(ref keywords) = self.metadata.keywords {
            info_entries.push(format!("/Keywords {}", format_pdf_string(keywords)));
        }
        if let Some(ref creator) = self.metadata.creator {
            info_entries.push(format!("/Creator {}", format_pdf_string(creator)));
        }
        if let Some(ref creation_date) = self.metadata.creation_date {
            info_entries.push(format!("/CreationDate {}", format_pdf_string(creation_date)));
        }
        if let Some(ref mod_date) = self.metadata.mod_date {
            info_entries.push(format!("/ModDate {}", format_pdf_string(mod_date)));
        }
        info_entries.push(format!("/Producer {}", format_pdf_string(PRODUCER)));

        let info_ref = {
            let id = w.alloc();
            w.object(id, &format!("<< {} >>", info_entries.join(" ")));
            Some(id)
        };

        w.finish(catalog_ref, info_ref)
    }
}

/// [`PdfOutlineNode`]'s shape, mirrored with an allocated [`Ref`] per node
/// instead of the node data — lets [`write_outline_siblings`] look up any
/// node's own/children's refs without re-allocating or borrowing `w`.
struct RefTree {
    r: Ref,
    children: Vec<RefTree>,
}

fn alloc_outline_refs(w: &mut PdfWriter, nodes: &[PdfOutlineNode]) -> Vec<RefTree> {
    nodes
        .iter()
        .map(|n| RefTree {
            r: w.alloc(),
            children: alloc_outline_refs(w, &n.children),
        })
        .collect()
}

/// Total number of descendants (not just direct children) — the PDF
/// `/Count` an always-expanded outline entry needs.
fn count_descendants(node: &PdfOutlineNode) -> i64 {
    node.children.len() as i64 + node.children.iter().map(count_descendants).sum::<i64>()
}

/// Writes every node in `nodes` (a sibling list — top-level entries or one
/// node's children) as its own indirect object: `/Title`, `/Parent`,
/// `/Prev`/`/Next` (siblings), `/First`/`/Last`/`/Count` (children), and
/// `/Dest` resolved from `page_index`/`y` against `page_refs` (falls back
/// to the entry's own object if `page_index` is somehow out of range — a
/// self-link is a harmless no-op, not a broken PDF). Recurses into each
/// node's own children afterwards.
fn write_outline_siblings(w: &mut PdfWriter, nodes: &[PdfOutlineNode], ref_nodes: &[RefTree], parent_ref: Ref, page_refs: &[Ref]) {
    for (i, (node, ref_node)) in nodes.iter().zip(ref_nodes).enumerate() {
        let prev = (i > 0).then(|| ref_nodes[i - 1].r);
        let next = (i + 1 < nodes.len()).then(|| ref_nodes[i + 1].r);
        let first = ref_node.children.first().map(|c| c.r);
        let last = ref_node.children.last().map(|c| c.r);
        let count = count_descendants(node);
        let target_page = page_refs.get(node.page_index).copied().unwrap_or(ref_node.r);

        let mut entries = vec![
            format!("/Title {}", format_pdf_string(&node.title)),
            format!("/Parent {}", parent_ref.write()),
            format!("/Dest [{} /XYZ null {} null]", target_page.write(), fmt_num(node.y)),
        ];
        if let Some(p) = prev {
            entries.push(format!("/Prev {}", p.write()));
        }
        if let Some(n) = next {
            entries.push(format!("/Next {}", n.write()));
        }
        if let Some(f) = first {
            entries.push(format!("/First {}", f.write()));
        }
        if let Some(l) = last {
            entries.push(format!("/Last {}", l.write()));
        }
        if count > 0 {
            entries.push(format!("/Count {count}"));
        }
        w.object(ref_node.r, &format!("<< {} >>", entries.join(" ")));

        write_outline_siblings(w, &node.children, &ref_node.children, ref_node.r, page_refs);
    }
}

pub(crate) fn format_pdf_string(s: &str) -> String {
    let escaped = s.replace('\\', "\\\\").replace('(', "\\(").replace(')', "\\)");
    format!("({escaped})")
}

/// Escapes the five XML predefined entities' triggers that can appear in
/// caller-supplied metadata text — enough for XMP's RDF/XML, which never
/// needs attribute-quote escaping here (everything below goes in element
/// content, not an attribute value).
#[cfg(feature = "pdf-a")]
fn xml_escape(s: &str) -> String {
    s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;")
}

/// Builds the XMP packet (issue #25): `dc:title`/`dc:creator`/
/// `dc:description`/`pdf:Keywords`/`xmp:CreatorTool`/`xmp:CreateDate`/
/// `xmp:ModifyDate` mirror `PdfMetadata`'s `/Info` fields 1:1 (ISO
/// 19005-3 6.7.3 — the two are required to stay consistent, so this
/// reads from the very same `PdfMetadata` the `/Info` dict is built
/// from, never a separately-tracked copy), plus the `pdfaid:part`/
/// `pdfaid:conformance` conformance markers every PDF/A file needs.
#[cfg(feature = "pdf-a")]
fn build_xmp_packet(metadata: &PdfMetadata, zugferd: bool, pdf_ua: bool) -> String {
    let mut props = String::new();
    if let Some(ref title) = metadata.title {
        props.push_str(&format!(
            "<dc:title><rdf:Alt><rdf:li xml:lang=\"x-default\">{}</rdf:li></rdf:Alt></dc:title>",
            xml_escape(title)
        ));
    }
    if let Some(ref author) = metadata.author {
        props.push_str(&format!(
            "<dc:creator><rdf:Seq><rdf:li>{}</rdf:li></rdf:Seq></dc:creator>",
            xml_escape(author)
        ));
    }
    if let Some(ref subject) = metadata.subject {
        props.push_str(&format!(
            "<dc:description><rdf:Alt><rdf:li xml:lang=\"x-default\">{}</rdf:li></rdf:Alt></dc:description>",
            xml_escape(subject)
        ));
    }
    if let Some(ref keywords) = metadata.keywords {
        props.push_str(&format!("<pdf:Keywords>{}</pdf:Keywords>", xml_escape(keywords)));
    }
    if let Some(ref creator) = metadata.creator {
        props.push_str(&format!("<xmp:CreatorTool>{}</xmp:CreatorTool>", xml_escape(creator)));
    }
    if let Some(ref created) = metadata.xmp_creation_date {
        props.push_str(&format!("<xmp:CreateDate>{created}</xmp:CreateDate>"));
    }
    if let Some(ref modified) = metadata.xmp_mod_date {
        props.push_str(&format!("<xmp:ModifyDate>{modified}</xmp:ModifyDate>"));
    }
    props.push_str("<pdfaid:part>3</pdfaid:part><pdfaid:conformance>B</pdfaid:conformance>");
    // PDF/UA-1 identification (issue #27) — `Document::pdf_ua()` always
    // implies `pdf_a3b()` (ADR-019), so this XMP packet already carries
    // the `pdfaid:*` markers above; PDF/UA just adds its own alongside
    // them, both correctly describing the same file.
    if pdf_ua {
        props.push_str("<pdfuaid:part>1</pdfuaid:part>");
    }

    let zugferd_block = if zugferd { ZUGFERD_XMP_EXTENSION } else { "" };
    // PDF/A-3b's own XMP validation rejects any property that isn't
    // either a predefined schema or described by a PDF/A Extension
    // Schema (exactly the rule that motivated `ZUGFERD_XMP_EXTENSION`
    // above) — `pdfuaid:part` needs the same treatment. Found via an
    // actual veraPDF PDF/A-3b run on a `pdf_ua()` document failing with
    // "XMP property is either not predefined, or is not defined in any
    // XMP extension schema" — not something the spec text alone would
    // have flagged ahead of time.
    let pdfua_block = if pdf_ua { PDFUA_XMP_EXTENSION } else { "" };

    format!(
        "<?xpacket begin=\"\u{feff}\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\
<x:xmpmeta xmlns:x=\"adobe:ns:meta/\">\
<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\
<rdf:Description rdf:about=\"\" \
xmlns:dc=\"http://purl.org/dc/elements/1.1/\" \
xmlns:pdf=\"http://ns.adobe.com/pdf/1.3/\" \
xmlns:xmp=\"http://ns.adobe.com/xap/1.0/\" \
xmlns:pdfaid=\"http://www.aiim.org/pdfa/ns/id/\" \
xmlns:pdfuaid=\"http://www.aiim.org/pdfua/ns/id/\">\
{props}\
</rdf:Description>\
{zugferd_block}\
{pdfua_block}\
</rdf:RDF>\
</x:xmpmeta>\
<?xpacket end=\"w\"?>"
    )
}

#[cfg(all(feature = "pdf-a", not(feature = "tagged-pdf")))]
const PDFUA_XMP_EXTENSION: &str = "";

/// PDF/A Extension Schema description for the `pdfuaid` namespace (issue
/// #27) — same shape as `ZUGFERD_XMP_EXTENSION`, one property
/// (`part`, `Integer`).
#[cfg(feature = "tagged-pdf")]
const PDFUA_XMP_EXTENSION: &str = "\
<rdf:Description rdf:about=\"\" \
xmlns:pdfaExtension=\"http://www.aiim.org/pdfa/ns/extension/\" \
xmlns:pdfaSchema=\"http://www.aiim.org/pdfa/ns/schema#\" \
xmlns:pdfaProperty=\"http://www.aiim.org/pdfa/ns/property#\">\
<pdfaExtension:schemas><rdf:Bag><rdf:li rdf:parseType=\"Resource\">\
<pdfaSchema:schema>PDF/UA identification schema</pdfaSchema:schema>\
<pdfaSchema:namespaceURI>http://www.aiim.org/pdfua/ns/id/</pdfaSchema:namespaceURI>\
<pdfaSchema:prefix>pdfuaid</pdfaSchema:prefix>\
<pdfaSchema:property><rdf:Seq>\
<rdf:li rdf:parseType=\"Resource\"><pdfaProperty:name>part</pdfaProperty:name><pdfaProperty:valueType>Integer</pdfaProperty:valueType><pdfaProperty:category>internal</pdfaProperty:category><pdfaProperty:description>Indicates, as an integer, the part of ISO 14289 to which the file conforms</pdfaProperty:description></rdf:li>\
</rdf:Seq></pdfaSchema:property>\
</rdf:li></rdf:Bag></pdfaExtension:schemas>\
</rdf:Description>";

/// The Factur-X/ZUGFeRD 2.x XMP extension (issue #26): the `fx:*`
/// property values (fixed for this crate's EN 16931/Comfort-only scope —
/// `factur-x.xml`, `INVOICE`, version `1.0`) plus the mandatory
/// `pdfaExtension`/`pdfaSchema`/`pdfaProperty` schema description PDF/A-3
/// requires for any custom XMP namespace. Structure taken from PDFlib's
/// own reference Factur-X sample
/// (<https://github.com/atgp/factur-x/blob/master/xmp/Factur-X_extension_schema.xmp>),
/// not reconstructed from the spec text — this block is exactly the kind
/// of thing worth getting from a working reference rather than guessing.
#[cfg(all(feature = "pdf-a", not(feature = "zugferd")))]
const ZUGFERD_XMP_EXTENSION: &str = "";

#[cfg(feature = "zugferd")]
const ZUGFERD_XMP_EXTENSION: &str = "\
<rdf:Description rdf:about=\"\" xmlns:fx=\"urn:factur-x:pdfa:CrossIndustryDocument:invoice:1p0#\">\
<fx:DocumentType>INVOICE</fx:DocumentType>\
<fx:DocumentFileName>factur-x.xml</fx:DocumentFileName>\
<fx:Version>1.0</fx:Version>\
<fx:ConformanceLevel>EN 16931</fx:ConformanceLevel>\
</rdf:Description>\
<rdf:Description rdf:about=\"\" \
xmlns:pdfaExtension=\"http://www.aiim.org/pdfa/ns/extension/\" \
xmlns:pdfaSchema=\"http://www.aiim.org/pdfa/ns/schema#\" \
xmlns:pdfaProperty=\"http://www.aiim.org/pdfa/ns/property#\">\
<pdfaExtension:schemas><rdf:Bag><rdf:li rdf:parseType=\"Resource\">\
<pdfaSchema:schema>Factur-X PDFA Extension Schema</pdfaSchema:schema>\
<pdfaSchema:namespaceURI>urn:factur-x:pdfa:CrossIndustryDocument:invoice:1p0#</pdfaSchema:namespaceURI>\
<pdfaSchema:prefix>fx</pdfaSchema:prefix>\
<pdfaSchema:property><rdf:Seq>\
<rdf:li rdf:parseType=\"Resource\"><pdfaProperty:name>DocumentFileName</pdfaProperty:name><pdfaProperty:valueType>Text</pdfaProperty:valueType><pdfaProperty:category>external</pdfaProperty:category><pdfaProperty:description>name of the embedded XML invoice file</pdfaProperty:description></rdf:li>\
<rdf:li rdf:parseType=\"Resource\"><pdfaProperty:name>DocumentType</pdfaProperty:name><pdfaProperty:valueType>Text</pdfaProperty:valueType><pdfaProperty:category>external</pdfaProperty:category><pdfaProperty:description>INVOICE</pdfaProperty:description></rdf:li>\
<rdf:li rdf:parseType=\"Resource\"><pdfaProperty:name>Version</pdfaProperty:name><pdfaProperty:valueType>Text</pdfaProperty:valueType><pdfaProperty:category>external</pdfaProperty:category><pdfaProperty:description>The actual version of the Factur-X XML schema</pdfaProperty:description></rdf:li>\
<rdf:li rdf:parseType=\"Resource\"><pdfaProperty:name>ConformanceLevel</pdfaProperty:name><pdfaProperty:valueType>Text</pdfaProperty:valueType><pdfaProperty:category>external</pdfaProperty:category><pdfaProperty:description>The conformance level of the embedded Factur-X data</pdfaProperty:description></rdf:li>\
</rdf:Seq></pdfaSchema:property>\
</rdf:li></rdf:Bag></pdfaExtension:schemas>\
</rdf:Description>";

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

    fn tiny_font() -> CidFont {
        CidFont {
            base_font: "Test".to_string(),
            subset_bytes: vec![0u8; 16],
            widths: vec![0.0, 600.0],
            ascent: 800.0,
            descent: -200.0,
            cap_height: 700.0,
            italic_angle: 0.0,
            bbox: (-100.0, -200.0, 900.0, 900.0),
            is_italic: false,
            is_bold: false,
            to_unicode: vec![(1, 'H')],
        }
    }

    #[test]
    fn writes_a_single_empty_page() {
        let mut doc = PdfDocument::new();
        doc.add_page(PdfPage {
            width: 595.0,
            height: 842.0,
            content: Vec::new(),
            annotations: Vec::new(),
        });
        let bytes = doc.write();
        let text = String::from_utf8_lossy(&bytes);
        assert!(text.contains("/Type /Page"));
        assert!(text.contains("/MediaBox [0 0 595 842]"));
        assert!(text.contains("%%EOF"));
    }

    #[test]
    fn writes_a_goto_destination_for_an_internal_link_annotation() {
        let mut doc = PdfDocument::new();
        doc.add_page(PdfPage {
            width: 595.0,
            height: 842.0,
            content: Vec::new(),
            annotations: vec![PdfLinkAnnotation {
                rect: (10.0, 20.0, 100.0, 40.0),
                action: PdfLinkAction::GoTo { page_index: 1, y: 700.0 },
            }],
        });
        doc.add_page(PdfPage {
            width: 595.0,
            height: 842.0,
            content: Vec::new(),
            annotations: Vec::new(),
        });
        let bytes = doc.write();
        let text = String::from_utf8_lossy(&bytes);
        assert!(text.contains("/Subtype /Link"));
        assert!(text.contains("/Dest ["));
        assert!(text.contains("/XYZ null 700 null"));
        assert!(!text.contains("/S /URI"), "a GoTo annotation must not also emit a URI action");
    }

    #[test]
    fn writes_type0_cid_font_structure() {
        let mut doc = PdfDocument::new();
        doc.add_font(tiny_font());
        doc.add_page(PdfPage {
            width: 595.0,
            height: 842.0,
            content: Vec::new(),
            annotations: Vec::new(),
        });
        let bytes = doc.write();
        let text = String::from_utf8_lossy(&bytes);
        assert!(text.contains("/Subtype /Type0"));
        assert!(text.contains("/Encoding /Identity-H"));
        assert!(text.contains("/Subtype /CIDFontType2"));
        assert!(text.contains("/CIDToGIDMap /Identity"));
        assert!(text.contains("/ToUnicode"));
        // The ToUnicode CMap body itself lives inside a stream, which is
        // `/FlateDecode`-compressed by default (ADR-016) — inflate every
        // stream body before checking, rather than the raw dict text.
        let decoded = stream_bodies_decoded(&bytes);
        assert!(decoded.contains("beginbfchar"));
        assert!(decoded.contains("<0001> <0048>")); // CID 1 -> U+0048 'H'
    }

    /// Every `stream\n...\nendstream` payload in `bytes`, inflated (when
    /// `compress` is enabled — a no-op passthrough otherwise, since
    /// nothing is compressed then) and concatenated, for tests that need
    /// to read stream content rather than just check the surrounding
    /// dict.
    fn stream_bodies_decoded(bytes: &[u8]) -> String {
        const START: &[u8] = b"stream\n";
        const END: &[u8] = b"\nendstream";
        let mut bodies = Vec::new();
        let mut i = 0;
        while let Some(start_rel) = bytes[i..].windows(START.len()).position(|w| w == START) {
            let start = i + start_rel + START.len();
            let Some(end_rel) = bytes[start..].windows(END.len()).position(|w| w == END) else {
                break;
            };
            let end = start + end_rel;
            bodies.push(&bytes[start..end]);
            i = end + END.len();
        }
        bodies.into_iter().map(decode_one_stream_body).collect::<Vec<_>>().join("\n")
    }

    #[cfg(feature = "compress")]
    fn decode_one_stream_body(body: &[u8]) -> String {
        match miniz_oxide::inflate::decompress_to_vec_zlib(body) {
            Ok(v) => String::from_utf8_lossy(&v).into_owned(),
            Err(_) => String::new(), // not a zlib stream (shouldn't happen for our own output) — skip, don't panic
        }
    }

    #[cfg(not(feature = "compress"))]
    fn decode_one_stream_body(body: &[u8]) -> String {
        String::from_utf8_lossy(body).into_owned()
    }

    #[test]
    fn writes_image_xobject_with_smask() {
        let mut doc = PdfDocument::new();
        doc.add_image(ImageXObject {
            width_px: 4,
            height_px: 4,
            color_space: ColorSpace::DeviceRgb,
            bits_per_component: 8,
            filter: ImageDataFilter::None,
            bytes: vec![0u8; 4 * 4 * 3],
            smask: Some(Box::new(ImageXObject {
                width_px: 4,
                height_px: 4,
                color_space: ColorSpace::DeviceGray,
                bits_per_component: 8,
                filter: ImageDataFilter::None,
                bytes: vec![255u8; 4 * 4],
                smask: None,
            })),
        });
        doc.add_page(PdfPage {
            width: 200.0,
            height: 200.0,
            content: Vec::new(),
            annotations: Vec::new(),
        });
        let bytes = doc.write();
        let text = String::from_utf8_lossy(&bytes);
        assert!(text.contains("/Subtype /Image"));
        assert!(text.contains("/ColorSpace /DeviceRGB"));
        assert!(text.contains("/ColorSpace /DeviceGray"));
        assert!(text.contains("/SMask"));
        assert!(text.contains("/XObject << /Im1"));
    }

    #[test]
    fn writes_jpeg_image_with_dct_decode_filter() {
        let mut doc = PdfDocument::new();
        doc.add_image(ImageXObject {
            width_px: 10,
            height_px: 10,
            color_space: ColorSpace::DeviceRgb,
            bits_per_component: 8,
            filter: ImageDataFilter::DctDecode,
            bytes: vec![0xFF, 0xD8, 0xFF, 0xD9], // stand-in bytes, structure only
            smask: None,
        });
        doc.add_page(PdfPage {
            width: 200.0,
            height: 200.0,
            content: Vec::new(),
            annotations: Vec::new(),
        });
        let bytes = doc.write();
        let text = String::from_utf8_lossy(&bytes);
        assert!(text.contains("/Filter /DCTDecode"));
    }

    #[cfg(feature = "pdf-a")]
    #[test]
    fn writes_output_intent_and_xmp_metadata_when_pdf_a3b_is_set() {
        let mut doc = PdfDocument::new();
        doc.pdf_a3b = true;
        doc.metadata.title = Some("Rechnung".to_string());
        doc.add_page(PdfPage {
            width: 200.0,
            height: 200.0,
            content: Vec::new(),
            annotations: Vec::new(),
        });
        let bytes = doc.write();
        let text = String::from_utf8_lossy(&bytes);
        assert!(text.contains("/OutputIntents ["));
        assert!(text.contains("/S /GTS_PDFA1"));
        assert!(text.contains("/DestOutputProfile"));
        assert!(text.contains("/Type /Metadata /Subtype /XML"));
        assert!(text.contains("<pdfaid:part>3</pdfaid:part>"));
        assert!(text.contains("<pdfaid:conformance>B</pdfaid:conformance>"));
        assert!(text.contains("<dc:title><rdf:Alt><rdf:li xml:lang=\"x-default\">Rechnung</rdf:li></rdf:Alt></dc:title>"));
    }

    #[cfg(feature = "pdf-a")]
    #[test]
    fn omits_pdf_a_entries_when_pdf_a3b_is_not_set() {
        let mut doc = PdfDocument::new();
        doc.add_page(PdfPage {
            width: 200.0,
            height: 200.0,
            content: Vec::new(),
            annotations: Vec::new(),
        });
        let bytes = doc.write();
        let text = String::from_utf8_lossy(&bytes);
        assert!(!text.contains("/OutputIntents"));
        assert!(!text.contains("/Type /Metadata"));
        assert!(!text.contains("/Group"));
    }

    #[cfg(feature = "zugferd")]
    #[test]
    fn embeds_zugferd_xml_with_af_and_xmp_extension() {
        let mut doc = PdfDocument::new();
        doc.pdf_a3b = true;
        doc.zugferd_xml = Some(b"<CrossIndustryInvoice/>".to_vec());
        doc.add_page(PdfPage {
            width: 200.0,
            height: 200.0,
            content: Vec::new(),
            annotations: Vec::new(),
        });
        let bytes = doc.write();
        let text = String::from_utf8_lossy(&bytes);
        assert!(text.contains("/Type /Filespec"));
        assert!(text.contains("/AFRelationship /Alternative"));
        assert!(text.contains("/Type /EmbeddedFile /Subtype /text#2Fxml"));
        assert!(text.contains("/AF ["));
        assert!(text.contains("/Names << /EmbeddedFiles"));
        assert!(text.contains("factur-x.xml"));
        assert!(text.contains("xmlns:fx=\"urn:factur-x:pdfa:CrossIndustryDocument:invoice:1p0#\""));
        assert!(text.contains("<fx:ConformanceLevel>EN 16931</fx:ConformanceLevel>"));
        assert!(text.contains("pdfaSchema:namespaceURI"));
    }

    #[cfg(feature = "zugferd")]
    #[test]
    fn omits_zugferd_entries_when_zugferd_xml_is_not_set() {
        let mut doc = PdfDocument::new();
        doc.pdf_a3b = true;
        doc.add_page(PdfPage {
            width: 200.0,
            height: 200.0,
            content: Vec::new(),
            annotations: Vec::new(),
        });
        let bytes = doc.write();
        let text = String::from_utf8_lossy(&bytes);
        assert!(!text.contains("/Type /Filespec"));
        assert!(!text.contains("/AF ["));
        assert!(!text.contains("xmlns:fx="));
    }

    #[cfg(feature = "tagged-pdf")]
    #[test]
    fn writes_struct_tree_mark_info_and_lang_when_pdf_ua_is_set() {
        use crate::struct_tree::PdfStructNode;

        let mut doc = PdfDocument::new();
        doc.pdf_a3b = true;
        doc.pdf_ua = true;
        doc.lang = Some("en-US".to_string());
        doc.add_page(PdfPage {
            width: 200.0,
            height: 200.0,
            content: Vec::new(),
            annotations: Vec::new(),
        });
        doc.struct_tree = Some(PdfStructNode::Elem {
            tag: "Document",
            alt: None,
            attrs: None,
            children: vec![PdfStructNode::Elem {
                tag: "H1",
                alt: None,
                attrs: None,
                children: vec![PdfStructNode::ContentRef { page_index: 0, mcid: 0 }],
            }],
        });
        let bytes = doc.write();
        let text = String::from_utf8_lossy(&bytes);
        assert!(text.contains("/MarkInfo << /Marked true >>"));
        assert!(text.contains("/Lang (en-US)"));
        assert!(text.contains("/Type /StructTreeRoot"));
        assert!(text.contains("/Type /StructElem /S /Document"));
        assert!(text.contains("/Type /StructElem /S /H1"));
        assert!(text.contains("/Type /MCR /Pg"));
        assert!(text.contains("/StructParents 0"));
        assert!(text.contains("/Nums ["));
        assert!(text.contains("<pdfuaid:part>1</pdfuaid:part>"));
    }

    #[cfg(feature = "tagged-pdf")]
    #[test]
    fn omits_struct_tree_entries_when_pdf_ua_is_not_set() {
        let mut doc = PdfDocument::new();
        doc.add_page(PdfPage {
            width: 200.0,
            height: 200.0,
            content: Vec::new(),
            annotations: Vec::new(),
        });
        let bytes = doc.write();
        let text = String::from_utf8_lossy(&bytes);
        assert!(!text.contains("/StructTreeRoot"));
        assert!(!text.contains("/MarkInfo"));
        assert!(!text.contains("/StructParents"));
    }
}