blitz-pdf 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/README.md +300 -10
  2. package/THIRD_PARTY_NOTICES.md +4 -2
  3. package/dist/browser.d.ts +1 -1
  4. package/dist/browser.d.ts.map +1 -1
  5. package/dist/document-options.d.ts +36 -0
  6. package/dist/document-options.d.ts.map +1 -0
  7. package/dist/document-options.js +236 -0
  8. package/dist/document-options.js.map +1 -0
  9. package/dist/node.d.ts +1 -1
  10. package/dist/node.d.ts.map +1 -1
  11. package/dist/options.d.ts +35 -1
  12. package/dist/options.d.ts.map +1 -1
  13. package/dist/options.js +21 -14
  14. package/dist/options.js.map +1 -1
  15. package/dist/types.d.ts +71 -1
  16. package/dist/types.d.ts.map +1 -1
  17. package/dist/validation.d.ts +2 -0
  18. package/dist/validation.d.ts.map +1 -0
  19. package/dist/validation.js +7 -0
  20. package/dist/validation.js.map +1 -0
  21. package/examples/zugferd.mjs +41 -0
  22. package/licenses/RUST_DEPENDENCIES.txt +27 -0
  23. package/package.json +3 -2
  24. package/src/browser.ts +1 -1
  25. package/src/document-options.ts +218 -0
  26. package/src/node.ts +1 -1
  27. package/src/options.ts +18 -13
  28. package/src/types.ts +76 -1
  29. package/src/validation.ts +6 -0
  30. package/vendor/README.md +27 -2
  31. package/vendor/krilla/.cargo-ok +1 -0
  32. package/vendor/krilla/.cargo_vcs_info.json +6 -0
  33. package/vendor/krilla/Cargo.lock +1357 -0
  34. package/vendor/krilla/Cargo.toml +165 -0
  35. package/vendor/krilla/LICENSE_APACHE +202 -0
  36. package/vendor/krilla/LICENSE_MIT +21 -0
  37. package/vendor/krilla/README.md +156 -0
  38. package/vendor/krilla/examples/basic.rs +117 -0
  39. package/vendor/krilla/examples/empty_document.rs +25 -0
  40. package/vendor/krilla/examples/parley.rs +174 -0
  41. package/vendor/krilla/examples/simple_text.rs +118 -0
  42. package/vendor/krilla/examples/stream_builder.rs +93 -0
  43. package/vendor/krilla/icc/LICENSE +116 -0
  44. package/vendor/krilla/icc/README.md +1 -0
  45. package/vendor/krilla/icc/sGrey-v2-magic.icc +0 -0
  46. package/vendor/krilla/icc/sGrey-v4.icc +0 -0
  47. package/vendor/krilla/icc/sRGB-v2-magic.icc +0 -0
  48. package/vendor/krilla/icc/sRGB-v4.icc +0 -0
  49. package/vendor/krilla/src/chunk_container.rs +503 -0
  50. package/vendor/krilla/src/configure/PDF_A1.md +227 -0
  51. package/vendor/krilla/src/configure/PDF_A2.md +269 -0
  52. package/vendor/krilla/src/configure/PDF_A3.md +31 -0
  53. package/vendor/krilla/src/configure/PDF_A4.md +211 -0
  54. package/vendor/krilla/src/configure/PDF_UA1.md +202 -0
  55. package/vendor/krilla/src/configure/README.md +23 -0
  56. package/vendor/krilla/src/configure/mod.rs +197 -0
  57. package/vendor/krilla/src/configure/validate.rs +1244 -0
  58. package/vendor/krilla/src/configure/version.rs +134 -0
  59. package/vendor/krilla/src/content.rs +1352 -0
  60. package/vendor/krilla/src/data.rs +49 -0
  61. package/vendor/krilla/src/document.rs +156 -0
  62. package/vendor/krilla/src/error.rs +170 -0
  63. package/vendor/krilla/src/geom.rs +341 -0
  64. package/vendor/krilla/src/graphics/blend.rs +46 -0
  65. package/vendor/krilla/src/graphics/color.rs +552 -0
  66. package/vendor/krilla/src/graphics/graphic.rs +30 -0
  67. package/vendor/krilla/src/graphics/graphics_state.rs +251 -0
  68. package/vendor/krilla/src/graphics/icc.rs +218 -0
  69. package/vendor/krilla/src/graphics/image.rs +835 -0
  70. package/vendor/krilla/src/graphics/mask.rs +128 -0
  71. package/vendor/krilla/src/graphics/mod.rs +14 -0
  72. package/vendor/krilla/src/graphics/paint.rs +434 -0
  73. package/vendor/krilla/src/graphics/separation.rs +86 -0
  74. package/vendor/krilla/src/graphics/shading_function.rs +865 -0
  75. package/vendor/krilla/src/graphics/shading_pattern.rs +60 -0
  76. package/vendor/krilla/src/graphics/tiling_pattern.rs +119 -0
  77. package/vendor/krilla/src/graphics/xobject.rs +150 -0
  78. package/vendor/krilla/src/interactive/action.rs +68 -0
  79. package/vendor/krilla/src/interactive/annotation.rs +283 -0
  80. package/vendor/krilla/src/interactive/destination.rs +289 -0
  81. package/vendor/krilla/src/interactive/mod.rs +3 -0
  82. package/vendor/krilla/src/interchange/embed.rs +240 -0
  83. package/vendor/krilla/src/interchange/metadata.rs +564 -0
  84. package/vendor/krilla/src/interchange/mod.rs +4 -0
  85. package/vendor/krilla/src/interchange/outline.rs +263 -0
  86. package/vendor/krilla/src/interchange/tagging/fmt.rs +733 -0
  87. package/vendor/krilla/src/interchange/tagging/generate.toml +474 -0
  88. package/vendor/krilla/src/interchange/tagging/generated.rs +4754 -0
  89. package/vendor/krilla/src/interchange/tagging/mod.rs +1324 -0
  90. package/vendor/krilla/src/interchange/tagging/tag.rs +686 -0
  91. package/vendor/krilla/src/lib.rs +179 -0
  92. package/vendor/krilla/src/num.rs +26 -0
  93. package/vendor/krilla/src/page.rs +612 -0
  94. package/vendor/krilla/src/pdf.rs +313 -0
  95. package/vendor/krilla/src/resource.rs +436 -0
  96. package/vendor/krilla/src/serialize.rs +1101 -0
  97. package/vendor/krilla/src/stream.rs +368 -0
  98. package/vendor/krilla/src/surface.rs +664 -0
  99. package/vendor/krilla/src/text/cid.rs +488 -0
  100. package/vendor/krilla/src/text/font.rs +351 -0
  101. package/vendor/krilla/src/text/glyph/bitmap.rs +81 -0
  102. package/vendor/krilla/src/text/glyph/colr.rs +581 -0
  103. package/vendor/krilla/src/text/glyph/mod.rs +205 -0
  104. package/vendor/krilla/src/text/glyph/outline.rs +72 -0
  105. package/vendor/krilla/src/text/glyph/svg.rs +34 -0
  106. package/vendor/krilla/src/text/group.rs +463 -0
  107. package/vendor/krilla/src/text/mod.rs +232 -0
  108. package/vendor/krilla/src/text/shape.rs +102 -0
  109. package/vendor/krilla/src/text/type3.rs +514 -0
  110. package/vendor/krilla/src/util.rs +286 -0
  111. package/vendor/stylo/properties/longhands.toml +0 -1
  112. package/vendor/stylo/stylesheets/rule_parser.rs +1 -1
  113. package/wasm/blitz_pdf.js +10 -5
  114. package/wasm/blitz_pdf_bg.wasm +0 -0
@@ -0,0 +1,612 @@
1
+ //! Working with pages of a PDF document.
2
+
3
+ use std::cell::OnceCell;
4
+ use std::num::NonZeroU32;
5
+ use std::ops::DerefMut;
6
+
7
+ use pdf_writer::types::TabOrder;
8
+ use pdf_writer::writers::NumberTree;
9
+ use pdf_writer::{Chunk, Finish, Ref, TextStr};
10
+
11
+ use crate::chunk_container::ChunkContainer;
12
+ use crate::configure::validate::VersionedFeature;
13
+ use crate::configure::ValidationError;
14
+ use crate::content::ContentBuilder;
15
+ use crate::error::KrillaResult;
16
+ use crate::geom::{Rect, Size, Transform};
17
+ use crate::interactive::annotation::Annotation;
18
+ use crate::interchange::tagging::{Identifier, PageTagIdentifier};
19
+ use crate::resource::ResourceDictionary;
20
+ use crate::serialize::{PageInfo, SerializeContext};
21
+ use crate::stream::{FilterStreamBuilder, Stream};
22
+ use crate::surface::Surface;
23
+ use crate::tagging::AnnotationIdentifier;
24
+ use crate::util::Deferred;
25
+
26
+ #[derive(Clone, Debug)]
27
+ /// The settings of a page.
28
+ pub struct PageSettings {
29
+ /// The media box of the page, which defines the visible area of the surface.
30
+ media_box: Option<Rect>,
31
+ /// The page label of the page.
32
+ page_label: PageLabel,
33
+ /// The size of the surface.
34
+ surface_size: Size,
35
+ /// The crop box of the page
36
+ crop_box: Option<Rect>,
37
+ /// The bleed box of the page
38
+ bleed_box: Option<Rect>,
39
+ /// The trim box of the page
40
+ trim_box: Option<Rect>,
41
+ /// The actual content boundaries
42
+ art_box: Option<Rect>,
43
+ }
44
+
45
+ impl PageSettings {
46
+ /// Create new page settings and define the size of the page surface.
47
+ pub fn new(size: Size) -> Self {
48
+ Self {
49
+ media_box: Some(Rect::from_xywh(0.0, 0.0, size.width(), size.height()).unwrap()),
50
+ surface_size: size,
51
+ ..Default::default()
52
+ }
53
+ }
54
+
55
+ /// Try to create new page settings with the specified width and height.
56
+ ///
57
+ /// Returns `None` if either the width or the height is not > 0.
58
+ pub fn from_wh(width: f32, height: f32) -> Option<Self> {
59
+ Some(Self::new(Size::from_wh(width, height)?))
60
+ }
61
+
62
+ /// Change the media box.
63
+ ///
64
+ /// The media box defines the visible area of the page when opening the PDF,
65
+ /// so it can be distinct from the size of the surface, but in the majority
66
+ /// of the cases you want them to match in size and align the media box
67
+ /// at the origin of the coordinate system.
68
+ ///
69
+ /// If set to `None`, the dimensions will be chosen in such a way that all
70
+ /// contents fit on the page.
71
+ pub fn with_media_box(mut self, media_box: Option<Rect>) -> PageSettings {
72
+ self.media_box = media_box;
73
+ self
74
+ }
75
+
76
+ /// Change the page label.
77
+ pub fn with_page_label(mut self, page_label: PageLabel) -> PageSettings {
78
+ self.page_label = page_label;
79
+ self
80
+ }
81
+
82
+ /// The current media box.
83
+ pub(crate) fn media_box(&self) -> Option<Rect> {
84
+ self.media_box
85
+ }
86
+
87
+ /// The current surface size.
88
+ pub(crate) fn surface_size(&self) -> Size {
89
+ self.surface_size
90
+ }
91
+
92
+ /// The current page label.
93
+ pub(crate) fn page_label(&self) -> &PageLabel {
94
+ &self.page_label
95
+ }
96
+
97
+ /// Change the crop box.
98
+ ///
99
+ /// The crop box defines the region to which the page contents are to be clipped
100
+ /// when displayed or printed. Default is the media box.
101
+ ///
102
+ /// If `None`, no /CropBox attribute will be written to the page.
103
+ pub fn with_crop_box(mut self, crop_box: Option<Rect>) -> PageSettings {
104
+ self.crop_box = crop_box;
105
+ self
106
+ }
107
+
108
+ /// The current crop box.
109
+ pub(crate) fn crop_box(&self) -> Option<Rect> {
110
+ self.crop_box
111
+ }
112
+
113
+ /// Change the bleed box.
114
+ ///
115
+ /// The bleed box defines the region to which the page contents needs to be clipped
116
+ /// when output in a production environment. It includes any extra bleed area needed
117
+ /// for printing.
118
+ ///
119
+ /// If `None`, no /BleedBox attribute will be written to the page.
120
+ pub fn with_bleed_box(mut self, bleed_box: Option<Rect>) -> PageSettings {
121
+ self.bleed_box = bleed_box;
122
+ self
123
+ }
124
+
125
+ /// The current bleed box.
126
+ pub(crate) fn bleed_box(&self) -> Option<Rect> {
127
+ self.bleed_box
128
+ }
129
+
130
+ /// Change the trim box.
131
+ ///
132
+ /// The trim box defines the intended dimensions of the finished page after trimming.
133
+ /// It may be smaller than the media box and bleed box to accommodate bleed for printing.
134
+ ///
135
+ /// If `None`, no /TrimBox attribute will be written to the page.
136
+ pub fn with_trim_box(mut self, trim_box: Option<Rect>) -> PageSettings {
137
+ self.trim_box = trim_box;
138
+ self
139
+ }
140
+
141
+ /// The current trim box.
142
+ pub(crate) fn trim_box(&self) -> Option<Rect> {
143
+ self.trim_box
144
+ }
145
+
146
+ /// Change the art box.
147
+ ///
148
+ /// The art box defines the extent of the page's meaningful content (including
149
+ /// potential white space) as intended by the page's creator.
150
+ ///
151
+ /// If `None`, no /ArtBox attribute will be written to the page.
152
+ pub fn with_art_box(mut self, art_box: Option<Rect>) -> PageSettings {
153
+ self.art_box = art_box;
154
+ self
155
+ }
156
+
157
+ /// The current art box.
158
+ pub(crate) fn art_box(&self) -> Option<Rect> {
159
+ self.art_box
160
+ }
161
+ }
162
+
163
+ impl Default for PageSettings {
164
+ fn default() -> Self {
165
+ // Default for A4.
166
+ let width = 595.0;
167
+ let height = 842.0;
168
+
169
+ Self {
170
+ media_box: Some(Rect::from_xywh(0.0, 0.0, width, height).unwrap()),
171
+ surface_size: Size::from_wh(width, height).unwrap(),
172
+ page_label: PageLabel::default(),
173
+ crop_box: None,
174
+ bleed_box: None,
175
+ trim_box: None,
176
+ art_box: None,
177
+ }
178
+ }
179
+ }
180
+
181
+ /// A single page.
182
+ ///
183
+ /// You cannot create an instance of this type yourself. Instead, you should use the
184
+ /// [`Document::start_page`] (or a related method) to add a new page to a document. In most cases, all
185
+ /// you need to do is to call the [`Page::surface`] method, so you can start drawing on the page.
186
+ /// However, there are a few other operations you can perform, such as adding annotations
187
+ /// to a page.
188
+ ///
189
+ /// [`Document::start_page`]: crate::Document::start_page
190
+ pub struct Page<'a> {
191
+ sc: &'a mut SerializeContext,
192
+ chunk_container: &'a mut ChunkContainer,
193
+ page_settings: PageSettings,
194
+ page_index: usize,
195
+ page_stream: Stream,
196
+ num_mcids: i32,
197
+ annotations: Vec<Annotation>,
198
+ }
199
+
200
+ impl<'a> Page<'a> {
201
+ pub(crate) fn new(
202
+ sc: &'a mut SerializeContext,
203
+ chunk_container: &'a mut ChunkContainer,
204
+ page_index: usize,
205
+ page_settings: PageSettings,
206
+ ) -> Self {
207
+ Self {
208
+ sc,
209
+ chunk_container,
210
+ page_settings,
211
+ page_index,
212
+ num_mcids: 0,
213
+ page_stream: Stream::empty(),
214
+ annotations: vec![],
215
+ }
216
+ }
217
+
218
+ pub(crate) fn root_transform(&self) -> Transform {
219
+ page_root_transform(self.page_settings.surface_size().height())
220
+ }
221
+
222
+ /// Add an annotation to the page.
223
+ pub fn add_annotation(&mut self, annotation: Annotation) {
224
+ self.annotations.push(annotation);
225
+ }
226
+
227
+ /// Add a tagged annotation to the page.
228
+ pub fn add_tagged_annotation(&mut self, mut annotation: Annotation) -> Identifier {
229
+ let annot_index = self.annotations.len();
230
+ let ai = AnnotationIdentifier::new(self.page_index, annot_index);
231
+ let struct_parent = self.sc.register_annotation_parent(ai);
232
+ annotation.struct_parent = struct_parent;
233
+ self.add_annotation(annotation);
234
+
235
+ match struct_parent {
236
+ None => Identifier::dummy(),
237
+ Some(_) => Identifier::new_annotation(self.page_index, annot_index),
238
+ }
239
+ }
240
+
241
+ /// Get the surface of the page to draw on. Calling this multiple times
242
+ /// on the same page will reset any previous drawings.
243
+ pub fn surface(&mut self) -> Surface<'_> {
244
+ let root_builder = ContentBuilder::new(
245
+ self.root_transform(),
246
+ self.page_settings.media_box.is_none(),
247
+ self.sc,
248
+ );
249
+
250
+ let finish_fn = Box::new(|stream, num_mcids| {
251
+ self.page_stream = stream;
252
+ self.num_mcids = num_mcids;
253
+ });
254
+
255
+ let page_identifier = if self.sc.serialize_settings().enable_tagging {
256
+ Some(PageTagIdentifier::new(self.page_index, 0))
257
+ } else {
258
+ None
259
+ };
260
+
261
+ Surface::new(
262
+ self.sc,
263
+ self.chunk_container,
264
+ root_builder,
265
+ page_identifier,
266
+ finish_fn,
267
+ )
268
+ }
269
+
270
+ /// A shorthand for `std::mem::drop`.
271
+ pub fn finish(self) {}
272
+ }
273
+
274
+ pub(crate) fn page_root_transform(height: f32) -> Transform {
275
+ Transform::from_row(1.0, 0.0, 0.0, -1.0, 0.0, height)
276
+ }
277
+
278
+ impl Drop for Page<'_> {
279
+ fn drop(&mut self) {
280
+ // Since we cannot take ownership in `drop`, just make use `mem::take` to pick
281
+ // what we need.
282
+ let annotations = std::mem::take(&mut self.annotations);
283
+ let page_settings = std::mem::take(&mut self.page_settings);
284
+
285
+ let struct_parent = self
286
+ .sc
287
+ .register_page_struct_parent(self.page_index, self.num_mcids);
288
+
289
+ let stream = std::mem::replace(&mut self.page_stream, Stream::empty());
290
+ let page = InternalPage::new(
291
+ stream,
292
+ self.sc,
293
+ annotations,
294
+ struct_parent,
295
+ page_settings,
296
+ self.page_index,
297
+ );
298
+ self.sc.register_page(page);
299
+ }
300
+ }
301
+
302
+ /// The numbering style of a page label.
303
+ #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
304
+ pub enum NumberingStyle {
305
+ /// Arabic numerals.
306
+ Arabic,
307
+ /// Lowercase Roman numerals.
308
+ LowerRoman,
309
+ /// Uppercase Roman numerals.
310
+ UpperRoman,
311
+ /// Lowercase letters (a-z, then aa-zz, ...).
312
+ LowerAlpha,
313
+ /// Uppercase letters (A-Z, then AA-ZZ, ...).
314
+ UpperAlpha,
315
+ }
316
+
317
+ impl NumberingStyle {
318
+ fn to_pdf(self) -> pdf_writer::types::NumberingStyle {
319
+ match self {
320
+ NumberingStyle::Arabic => pdf_writer::types::NumberingStyle::Arabic,
321
+ NumberingStyle::LowerRoman => pdf_writer::types::NumberingStyle::LowerRoman,
322
+ NumberingStyle::UpperRoman => pdf_writer::types::NumberingStyle::UpperRoman,
323
+ NumberingStyle::LowerAlpha => pdf_writer::types::NumberingStyle::LowerAlpha,
324
+ NumberingStyle::UpperAlpha => pdf_writer::types::NumberingStyle::UpperAlpha,
325
+ }
326
+ }
327
+ }
328
+
329
+ pub(crate) struct InternalPage {
330
+ pub stream_ref: Ref,
331
+ pub stream_resources: ResourceDictionary,
332
+ pub stream_chunk: Deferred<Chunk>,
333
+ pub page_settings: PageSettings,
334
+ pub page_index: usize,
335
+ pub struct_parent: Option<i32>,
336
+ pub bbox: Rect,
337
+ pub annotations: Vec<Annotation>,
338
+ }
339
+
340
+ impl InternalPage {
341
+ pub(crate) fn new(
342
+ mut stream: Stream,
343
+ sc: &mut SerializeContext,
344
+ annotations: Vec<Annotation>,
345
+ struct_parent: Option<i32>,
346
+ page_settings: PageSettings,
347
+ page_index: usize,
348
+ ) -> Self {
349
+ for validation_error in stream.validation_errors {
350
+ sc.register_validation_error(validation_error)
351
+ }
352
+
353
+ let stream_ref = sc.new_ref();
354
+ let serialize_settings = sc.serialize_settings().clone();
355
+ let stream_resources = std::mem::take(&mut stream.resource_dictionary);
356
+ let mut chunk = sc.new_chunk();
357
+
358
+ let stream_chunk = Deferred::new(move || {
359
+ let page_stream =
360
+ FilterStreamBuilder::new_from_content_stream(&stream.content, &serialize_settings)
361
+ .finish(&serialize_settings.clone());
362
+
363
+ let mut stream = chunk.stream(stream_ref, page_stream.encoded_data());
364
+ page_stream.write_filters(stream.deref_mut());
365
+
366
+ stream.finish();
367
+ chunk
368
+ });
369
+
370
+ Self {
371
+ stream_resources,
372
+ stream_ref,
373
+ stream_chunk,
374
+ struct_parent,
375
+ bbox: stream.bbox,
376
+ annotations,
377
+ page_settings,
378
+ page_index,
379
+ }
380
+ }
381
+
382
+ pub(crate) fn serialize(
383
+ self,
384
+ sc: &mut SerializeContext,
385
+ chunk_container: &mut ChunkContainer,
386
+ root_ref: Ref,
387
+ ) -> KrillaResult<()> {
388
+ let mut annotation_refs = vec![];
389
+
390
+ if !self.annotations.is_empty() {
391
+ for annotation in &self.annotations {
392
+ let annot_ref = sc.new_ref();
393
+
394
+ annotation.serialize(
395
+ sc,
396
+ chunk_container,
397
+ annot_ref,
398
+ self.page_settings.surface_size().height(),
399
+ )?;
400
+ annotation_refs.push((annot_ref, OnceCell::new()));
401
+ }
402
+ }
403
+
404
+ let chunk = &mut chunk_container.non_stream.pages;
405
+ let mut page = chunk.page(root_ref);
406
+ self.stream_resources.to_pdf_resources(
407
+ &mut page,
408
+ sc,
409
+ &mut chunk_container.non_stream.resource_dictionaries,
410
+ );
411
+
412
+ let transform_rect = |rect: Rect| {
413
+ rect.transform(page_root_transform(
414
+ self.page_settings.surface_size().height(),
415
+ ))
416
+ .unwrap()
417
+ };
418
+
419
+ // media box is mandatory, so we need to fall back to the default bbox
420
+ let media_box = transform_rect(self.page_settings.media_box().unwrap_or(self.bbox));
421
+ page.media_box(media_box.to_pdf_rect());
422
+
423
+ // the remaining type of box are not mandatory, so we only set them if they are present
424
+ if let Some(crop_box) = self.page_settings.crop_box() {
425
+ let crop_box = transform_rect(crop_box);
426
+ page.crop_box(crop_box.to_pdf_rect());
427
+ }
428
+
429
+ if let Some(bleed_box) = self.page_settings.bleed_box() {
430
+ let bleed_box = transform_rect(bleed_box);
431
+ page.bleed_box(bleed_box.to_pdf_rect());
432
+ }
433
+
434
+ if let Some(trim_box) = self.page_settings.trim_box() {
435
+ let trim_box = transform_rect(trim_box);
436
+ page.trim_box(trim_box.to_pdf_rect());
437
+ }
438
+
439
+ if let Some(art_box) = self.page_settings.art_box() {
440
+ let art_box = transform_rect(art_box);
441
+ page.art_box(art_box.to_pdf_rect());
442
+ }
443
+
444
+ if let Some(struct_parent) = self.struct_parent {
445
+ page.struct_parents(struct_parent);
446
+ }
447
+
448
+ // Only required for PDF/UA, but might as well always set it if there
449
+ // are annotations.
450
+ //
451
+ // Since the navigation order of annotations only has an effect if there
452
+ // are annotations, we usually only set the key in that case. However,
453
+ // the accessibility audit in Adobe Acrobat always [requires the key to
454
+ // be set][1], even if there are no annotations (perhaps the rationale
455
+ // is that the user can add some). Hence, we check if there is an
456
+ // accessibility validator or one requiring tags to decide whether to
457
+ // force the key.
458
+ //
459
+ // Since forcing `/Tabs S` unconditionally for PDF/A and PDF/UA files
460
+ // targeting PDF 1.4 and below would unconditionally raise a
461
+ // `RequiresNewerPdfVersion(StructureOrderTabbing, _)` error, we also
462
+ // check the target version.
463
+ //
464
+ // [1]: https://helpx.adobe.com/acrobat/using/create-verify-pdf-accessibility.html#TabOrder "Create and verify PDF accessibility (Acrobat Pro): Tab order"
465
+ if (!self.annotations.is_empty()
466
+ || ((sc
467
+ .serialize_settings()
468
+ .validators()
469
+ .accessibility()
470
+ .is_some()
471
+ || sc.serialize_settings().validators().requires_tagging())
472
+ && sc.serialize_settings().pdf_version()
473
+ >= VersionedFeature::StructureOrderTabbing.minimum_pdf_version()))
474
+ && sc.serialize_settings().enable_tagging
475
+ {
476
+ if sc.serialize_settings().pdf_version()
477
+ >= VersionedFeature::StructureOrderTabbing.minimum_pdf_version()
478
+ {
479
+ page.tab_order(TabOrder::StructureOrder);
480
+ } else {
481
+ sc.register_validation_error(ValidationError::RequiresNewerPdfVersion(
482
+ VersionedFeature::StructureOrderTabbing,
483
+ sc.location,
484
+ ));
485
+ }
486
+ }
487
+
488
+ page.parent(sc.page_tree_ref());
489
+ page.contents(self.stream_ref);
490
+
491
+ if !annotation_refs.is_empty() {
492
+ page.annotations(annotation_refs.iter().map(|(r, _)| *r));
493
+ }
494
+
495
+ // Populate the refs for each annotation in page infos.
496
+ let PageInfo::Krilla { annotations, .. } = &mut sc.page_infos_mut()[self.page_index] else {
497
+ unreachable!()
498
+ };
499
+ *annotations = annotation_refs;
500
+
501
+ page.finish();
502
+ chunk_container.streams.pages.push(self.stream_chunk);
503
+
504
+ Ok(())
505
+ }
506
+ }
507
+
508
+ /// A page label.
509
+ #[derive(Debug, Hash, Eq, PartialEq, Default, Clone)]
510
+ pub struct PageLabel {
511
+ /// The numbering style of the page label.
512
+ pub(crate) style: Option<NumberingStyle>,
513
+ /// The prefix of the page label.
514
+ pub(crate) prefix: Option<String>,
515
+ /// The numeric value of the page label.
516
+ pub(crate) offset: Option<NonZeroU32>,
517
+ }
518
+
519
+ impl PageLabel {
520
+ /// Create a new page label.
521
+ pub fn new(
522
+ style: Option<NumberingStyle>,
523
+ prefix: Option<String>,
524
+ offset: Option<NonZeroU32>,
525
+ ) -> Self {
526
+ Self {
527
+ style,
528
+ prefix,
529
+ offset,
530
+ }
531
+ }
532
+
533
+ pub(crate) fn is_empty(&self) -> bool {
534
+ self.style.is_none() && self.prefix.is_none() && self.offset.is_none()
535
+ }
536
+
537
+ pub(crate) fn serialize(&self, chunk_container: &mut ChunkContainer, root_ref: Ref) {
538
+ let chunk = &mut chunk_container.non_stream.page_labels;
539
+ let mut label = chunk
540
+ .indirect(root_ref)
541
+ .start::<pdf_writer::writers::PageLabel>();
542
+
543
+ if let Some(style) = self.style {
544
+ label.style(style.to_pdf());
545
+ }
546
+
547
+ if let Some(prefix) = &self.prefix {
548
+ label.prefix(TextStr(prefix));
549
+ }
550
+
551
+ if let Some(offset) = self.offset.and_then(|o| i32::try_from(o.get()).ok()) {
552
+ label.offset(offset);
553
+ }
554
+
555
+ label.finish();
556
+ }
557
+ }
558
+
559
+ #[derive(Hash)]
560
+ pub(crate) struct PageLabelContainer<'a> {
561
+ labels: &'a [PageLabel],
562
+ }
563
+
564
+ impl<'a> PageLabelContainer<'a> {
565
+ pub(crate) fn new(labels: &'a [PageLabel]) -> Option<Self> {
566
+ if labels.iter().all(|f| f.is_empty()) {
567
+ None
568
+ } else {
569
+ Some(PageLabelContainer { labels })
570
+ }
571
+ }
572
+
573
+ pub(crate) fn serialize(
574
+ &self,
575
+ sc: &mut SerializeContext,
576
+ chunk_container: &mut ChunkContainer,
577
+ root_ref: Ref,
578
+ ) {
579
+ // Will always contain at least one entry, since we ensured that a PageLabelContainer cannot
580
+ // be empty
581
+ let mut filtered_entries = vec![];
582
+ let mut prev: Option<PageLabel> = None;
583
+
584
+ for (i, label) in self.labels.iter().enumerate() {
585
+ if let Some(n_prev) = &prev {
586
+ if n_prev.style != label.style
587
+ || n_prev.prefix != label.prefix
588
+ || n_prev.offset.map(|n| n.get()) != label.offset.map(|n| n.get() + 1)
589
+ {
590
+ filtered_entries.push((i, label.clone()));
591
+ prev = Some(label.clone());
592
+ }
593
+ } else {
594
+ filtered_entries.push((i, label.clone()));
595
+ prev = Some(label.clone());
596
+ }
597
+ }
598
+
599
+ let mut chunk = sc.new_chunk();
600
+ let mut num_tree = chunk.indirect(root_ref).start::<NumberTree<Ref>>();
601
+ let mut nums = num_tree.nums();
602
+
603
+ for (page_num, label) in filtered_entries {
604
+ let label_ref = sc.register_page_label(chunk_container, label);
605
+ nums.insert(page_num as i32, label_ref);
606
+ }
607
+
608
+ nums.finish();
609
+ num_tree.finish();
610
+ chunk_container.non_stream.page_label_tree = Some((root_ref, chunk));
611
+ }
612
+ }