blitz-pdf 0.1.1 → 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.
- package/README.md +266 -12
- package/THIRD_PARTY_NOTICES.md +4 -2
- package/dist/browser.d.ts +1 -1
- package/dist/browser.d.ts.map +1 -1
- package/dist/document-options.d.ts +36 -0
- package/dist/document-options.d.ts.map +1 -0
- package/dist/document-options.js +236 -0
- package/dist/document-options.js.map +1 -0
- package/dist/node.d.ts +1 -1
- package/dist/node.d.ts.map +1 -1
- package/dist/options.d.ts +35 -1
- package/dist/options.d.ts.map +1 -1
- package/dist/options.js +21 -14
- package/dist/options.js.map +1 -1
- package/dist/types.d.ts +71 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/validation.d.ts +2 -0
- package/dist/validation.d.ts.map +1 -0
- package/dist/validation.js +7 -0
- package/dist/validation.js.map +1 -0
- package/examples/zugferd.mjs +41 -0
- package/licenses/RUST_DEPENDENCIES.txt +27 -0
- package/package.json +3 -2
- package/src/browser.ts +1 -1
- package/src/document-options.ts +218 -0
- package/src/node.ts +1 -1
- package/src/options.ts +18 -13
- package/src/types.ts +76 -1
- package/src/validation.ts +6 -0
- package/vendor/README.md +27 -2
- package/vendor/krilla/.cargo-ok +1 -0
- package/vendor/krilla/.cargo_vcs_info.json +6 -0
- package/vendor/krilla/Cargo.lock +1357 -0
- package/vendor/krilla/Cargo.toml +165 -0
- package/vendor/krilla/LICENSE_APACHE +202 -0
- package/vendor/krilla/LICENSE_MIT +21 -0
- package/vendor/krilla/README.md +156 -0
- package/vendor/krilla/examples/basic.rs +117 -0
- package/vendor/krilla/examples/empty_document.rs +25 -0
- package/vendor/krilla/examples/parley.rs +174 -0
- package/vendor/krilla/examples/simple_text.rs +118 -0
- package/vendor/krilla/examples/stream_builder.rs +93 -0
- package/vendor/krilla/icc/LICENSE +116 -0
- package/vendor/krilla/icc/README.md +1 -0
- package/vendor/krilla/icc/sGrey-v2-magic.icc +0 -0
- package/vendor/krilla/icc/sGrey-v4.icc +0 -0
- package/vendor/krilla/icc/sRGB-v2-magic.icc +0 -0
- package/vendor/krilla/icc/sRGB-v4.icc +0 -0
- package/vendor/krilla/src/chunk_container.rs +503 -0
- package/vendor/krilla/src/configure/PDF_A1.md +227 -0
- package/vendor/krilla/src/configure/PDF_A2.md +269 -0
- package/vendor/krilla/src/configure/PDF_A3.md +31 -0
- package/vendor/krilla/src/configure/PDF_A4.md +211 -0
- package/vendor/krilla/src/configure/PDF_UA1.md +202 -0
- package/vendor/krilla/src/configure/README.md +23 -0
- package/vendor/krilla/src/configure/mod.rs +197 -0
- package/vendor/krilla/src/configure/validate.rs +1244 -0
- package/vendor/krilla/src/configure/version.rs +134 -0
- package/vendor/krilla/src/content.rs +1352 -0
- package/vendor/krilla/src/data.rs +49 -0
- package/vendor/krilla/src/document.rs +156 -0
- package/vendor/krilla/src/error.rs +170 -0
- package/vendor/krilla/src/geom.rs +341 -0
- package/vendor/krilla/src/graphics/blend.rs +46 -0
- package/vendor/krilla/src/graphics/color.rs +552 -0
- package/vendor/krilla/src/graphics/graphic.rs +30 -0
- package/vendor/krilla/src/graphics/graphics_state.rs +251 -0
- package/vendor/krilla/src/graphics/icc.rs +218 -0
- package/vendor/krilla/src/graphics/image.rs +835 -0
- package/vendor/krilla/src/graphics/mask.rs +128 -0
- package/vendor/krilla/src/graphics/mod.rs +14 -0
- package/vendor/krilla/src/graphics/paint.rs +434 -0
- package/vendor/krilla/src/graphics/separation.rs +86 -0
- package/vendor/krilla/src/graphics/shading_function.rs +865 -0
- package/vendor/krilla/src/graphics/shading_pattern.rs +60 -0
- package/vendor/krilla/src/graphics/tiling_pattern.rs +119 -0
- package/vendor/krilla/src/graphics/xobject.rs +150 -0
- package/vendor/krilla/src/interactive/action.rs +68 -0
- package/vendor/krilla/src/interactive/annotation.rs +283 -0
- package/vendor/krilla/src/interactive/destination.rs +289 -0
- package/vendor/krilla/src/interactive/mod.rs +3 -0
- package/vendor/krilla/src/interchange/embed.rs +240 -0
- package/vendor/krilla/src/interchange/metadata.rs +564 -0
- package/vendor/krilla/src/interchange/mod.rs +4 -0
- package/vendor/krilla/src/interchange/outline.rs +263 -0
- package/vendor/krilla/src/interchange/tagging/fmt.rs +733 -0
- package/vendor/krilla/src/interchange/tagging/generate.toml +474 -0
- package/vendor/krilla/src/interchange/tagging/generated.rs +4754 -0
- package/vendor/krilla/src/interchange/tagging/mod.rs +1324 -0
- package/vendor/krilla/src/interchange/tagging/tag.rs +686 -0
- package/vendor/krilla/src/lib.rs +179 -0
- package/vendor/krilla/src/num.rs +26 -0
- package/vendor/krilla/src/page.rs +612 -0
- package/vendor/krilla/src/pdf.rs +313 -0
- package/vendor/krilla/src/resource.rs +436 -0
- package/vendor/krilla/src/serialize.rs +1101 -0
- package/vendor/krilla/src/stream.rs +368 -0
- package/vendor/krilla/src/surface.rs +664 -0
- package/vendor/krilla/src/text/cid.rs +488 -0
- package/vendor/krilla/src/text/font.rs +351 -0
- package/vendor/krilla/src/text/glyph/bitmap.rs +81 -0
- package/vendor/krilla/src/text/glyph/colr.rs +581 -0
- package/vendor/krilla/src/text/glyph/mod.rs +205 -0
- package/vendor/krilla/src/text/glyph/outline.rs +72 -0
- package/vendor/krilla/src/text/glyph/svg.rs +34 -0
- package/vendor/krilla/src/text/group.rs +463 -0
- package/vendor/krilla/src/text/mod.rs +232 -0
- package/vendor/krilla/src/text/shape.rs +102 -0
- package/vendor/krilla/src/text/type3.rs +514 -0
- package/vendor/krilla/src/util.rs +286 -0
- package/vendor/stylo/properties/longhands.toml +0 -1
- package/vendor/stylo/stylesheets/rule_parser.rs +1 -1
- package/wasm/blitz_pdf.js +10 -5
- package/wasm/blitz_pdf_bg.wasm +0 -0
|
@@ -0,0 +1,1101 @@
|
|
|
1
|
+
use std::cell::{OnceCell, RefCell};
|
|
2
|
+
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
|
|
3
|
+
use std::num::NonZeroU16;
|
|
4
|
+
use std::ops::{Deref, DerefMut};
|
|
5
|
+
use std::rc::Rc;
|
|
6
|
+
use std::sync::Arc;
|
|
7
|
+
|
|
8
|
+
use indexmap::IndexMap;
|
|
9
|
+
use pdf_writer::types::{StructRole, StructRole2};
|
|
10
|
+
use pdf_writer::writers::{OutputIntent, StructTreeRoot};
|
|
11
|
+
use pdf_writer::{Chunk, Content, Finish, Limits, Name, Pdf, Ref, Settings, Str, TextStr};
|
|
12
|
+
|
|
13
|
+
use crate::chunk_container::ChunkContainer;
|
|
14
|
+
use crate::color::{CieBasedColorSpace, DeviceColorSpace, SpecialColorSpace};
|
|
15
|
+
use crate::configure::validate::ValidationStore;
|
|
16
|
+
use crate::configure::{Configuration, PdfVersion, ValidationError, Validators};
|
|
17
|
+
use crate::error::{KrillaError, KrillaResult, LimitError};
|
|
18
|
+
use crate::geom::Size;
|
|
19
|
+
use crate::graphics::color::{rgb, ColorSpace};
|
|
20
|
+
use crate::graphics::icc::{ICCBasedColorSpace, ICCProfile};
|
|
21
|
+
#[cfg(feature = "raster-images")]
|
|
22
|
+
use crate::graphics::image::Image;
|
|
23
|
+
use crate::graphics::separation::SeparationColorSpace;
|
|
24
|
+
use crate::interactive::destination::{NamedDestination, XyzDestination};
|
|
25
|
+
use crate::interchange::embed::EmbeddedFile;
|
|
26
|
+
use crate::interchange::outline::Outline;
|
|
27
|
+
use crate::interchange::tagging::{AnnotationIdentifier, PageTagIdentifier, TagTree};
|
|
28
|
+
use crate::page::{InternalPage, PageLabel, PageLabelContainer};
|
|
29
|
+
#[cfg(feature = "pdf")]
|
|
30
|
+
use crate::pdf::{PdfDocument, PdfSerializerContext};
|
|
31
|
+
use crate::resource;
|
|
32
|
+
use crate::resource::{Resource, Resourceable};
|
|
33
|
+
use crate::surface::{Location, Surface};
|
|
34
|
+
use crate::text::GlyphId;
|
|
35
|
+
use crate::text::{Font, FontContainer, FontIdentifier};
|
|
36
|
+
use crate::util::SipHashable;
|
|
37
|
+
|
|
38
|
+
const STR_LEN: usize = 32767;
|
|
39
|
+
const NAME_LEN: usize = 127;
|
|
40
|
+
|
|
41
|
+
// These only apply to PDF 1.4 and PDF/A-1.
|
|
42
|
+
const MAX_FLOAT: f32 = 32767.0;
|
|
43
|
+
const DICT_LEN: usize = 4095;
|
|
44
|
+
const ARRAY_LEN: usize = 8191;
|
|
45
|
+
|
|
46
|
+
/// Settings that should be applied when creating a PDF document.
|
|
47
|
+
#[derive(Clone, Debug)]
|
|
48
|
+
pub struct SerializeSettings {
|
|
49
|
+
/// Whether to write PDFs in a way that is easier to inspect manually. This
|
|
50
|
+
/// will result in larger file sizes.
|
|
51
|
+
pub pretty: bool,
|
|
52
|
+
/// Whether content streams should be compressed. Leads to significantly smaller file sizes,
|
|
53
|
+
/// but also longer running times. It is highly recommended that you set this to `true`.
|
|
54
|
+
pub compress_content_streams: bool,
|
|
55
|
+
/// Whether device-independent colors should be used instead of
|
|
56
|
+
/// device-dependent ones.
|
|
57
|
+
///
|
|
58
|
+
/// Note that this value might be overridden depending on which validator
|
|
59
|
+
/// you use. For example, when exporting to PDF/A, this value will be set to
|
|
60
|
+
/// true, regardless of what value will be passed.
|
|
61
|
+
pub no_device_cs: bool,
|
|
62
|
+
/// Whether the PDF should be ASCII-compatible, i.e. only consist of
|
|
63
|
+
/// characters in the ASCII range.
|
|
64
|
+
///
|
|
65
|
+
/// Note that this only on a best-effort basis. For example, XMP metadata always
|
|
66
|
+
/// contains a binary marker. In addition to that, some validators,
|
|
67
|
+
/// like PDF/A, require that the file header be a binary marker, meaning
|
|
68
|
+
/// that the header itself will not be ASCII-compatible. Finally, embedded PDFs will
|
|
69
|
+
/// be embedded as is and not re-encoded with ASCII-compatible encoding.
|
|
70
|
+
pub ascii_compatible: bool,
|
|
71
|
+
/// Whether the PDF should include XMP metadata.
|
|
72
|
+
///
|
|
73
|
+
/// Note that this value might be overridden depending on which validator
|
|
74
|
+
/// you use. For example, when exporting to PDF/A, this value will be set to
|
|
75
|
+
/// true, regardless of what value will be passed.
|
|
76
|
+
pub xmp_metadata: bool,
|
|
77
|
+
/// The ICC profile that should be used for CMYK colors
|
|
78
|
+
/// when `no_device_cs` is enabled.
|
|
79
|
+
///
|
|
80
|
+
/// This is usually not required, but it is for example required when exporting
|
|
81
|
+
/// to PDF/A and using a CMYK color, since they have to be device-independent.
|
|
82
|
+
pub cmyk_profile: Option<ICCProfile<4>>,
|
|
83
|
+
/// A validator and PDF version used for export.
|
|
84
|
+
///
|
|
85
|
+
/// In case validation fails, export will fail, and a list of validation errors that
|
|
86
|
+
/// occurred will be returned instead of the PDF.
|
|
87
|
+
///
|
|
88
|
+
/// **Important**: Make sure to carefully read the documentation of the [`validate`] module
|
|
89
|
+
/// before using this feature! Just setting a validator might not be enough to ensure that
|
|
90
|
+
/// your output conforms to the given standard, as some requirements are semantic in nature
|
|
91
|
+
/// and cannot possibly be verified by krilla!
|
|
92
|
+
///
|
|
93
|
+
/// However, as long as you carefully read and follow the documentation,
|
|
94
|
+
/// you can be certain that the resulting document will conform to the standard (unless there
|
|
95
|
+
/// is a bug).
|
|
96
|
+
///
|
|
97
|
+
/// [`validate`]: crate::configure::validate
|
|
98
|
+
pub configuration: Configuration,
|
|
99
|
+
/// Whether to enable the creation of tagged documents. See the module documentation
|
|
100
|
+
/// of [`tagging`] for more information about tagged PDF documents.
|
|
101
|
+
///
|
|
102
|
+
/// Note that enabling this does not automatically make your documents tagged, as tagging implies
|
|
103
|
+
/// enriching the document with semantic information, which krilla cannot do
|
|
104
|
+
/// for you, since it's content-agnostic. All this setting does is to allow you
|
|
105
|
+
/// to dynamically disable tagging if you wish to do so. This allows you to write
|
|
106
|
+
/// your code primarily with tagging in mind, but still allows you to
|
|
107
|
+
/// disable it dynamically, without having to make any changes to your code.
|
|
108
|
+
///
|
|
109
|
+
/// Note that this value might be overridden depending on which validator
|
|
110
|
+
/// you use. For example, when exporting with PDF/UA, this value will always
|
|
111
|
+
/// be set to `true`.
|
|
112
|
+
///
|
|
113
|
+
/// [`tagging`]: crate::interchange::tagging
|
|
114
|
+
pub enable_tagging: bool,
|
|
115
|
+
/// A function that should be used to render SVG glyphs. If you don't need this, yu can
|
|
116
|
+
/// just use the default function which doesn't render them at all. If you do want this, it
|
|
117
|
+
/// is recommended that you use the function provided by the `krilla-svg` crate.
|
|
118
|
+
pub render_svg_glyph_fn: RenderSvgGlyphFn,
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
pub type RenderSvgGlyphFn = fn(&[u8], rgb::Color, GlyphId, (f32, f32), &mut Surface) -> Option<()>;
|
|
122
|
+
|
|
123
|
+
impl SerializeSettings {
|
|
124
|
+
pub(crate) fn pdf_version(&self) -> PdfVersion {
|
|
125
|
+
self.configuration.version()
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
pub(crate) fn validators(&self) -> Validators {
|
|
129
|
+
self.configuration.validators()
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/// Whether the `/AF` key is supported, accounting for the PDF version and active standards.
|
|
133
|
+
pub(crate) fn supports_associated_files(&self) -> bool {
|
|
134
|
+
self.configuration.version().specifies_associated_files()
|
|
135
|
+
|| self.configuration.validators().specifies_associated_files()
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
impl Default for SerializeSettings {
|
|
140
|
+
fn default() -> Self {
|
|
141
|
+
Self {
|
|
142
|
+
pretty: false,
|
|
143
|
+
ascii_compatible: false,
|
|
144
|
+
compress_content_streams: true,
|
|
145
|
+
no_device_cs: false,
|
|
146
|
+
xmp_metadata: true,
|
|
147
|
+
cmyk_profile: None,
|
|
148
|
+
configuration: Configuration::default(),
|
|
149
|
+
enable_tagging: true,
|
|
150
|
+
render_svg_glyph_fn: |_, _, _, _, _| None,
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
pub(crate) enum PageInfo {
|
|
156
|
+
/// A page built with krilla.
|
|
157
|
+
Krilla {
|
|
158
|
+
/// The reference of the page in the chunk.
|
|
159
|
+
ref_: Ref,
|
|
160
|
+
/// The page size, necessary so that we can convert from PDF coordinates to
|
|
161
|
+
/// krilla coordinates.
|
|
162
|
+
surface_size: Size,
|
|
163
|
+
/// The refs of the annotations that are used by that page, and optionally
|
|
164
|
+
/// a ref to their struct parent in the tag tree.
|
|
165
|
+
///
|
|
166
|
+
/// Note that this will be empty be default when adding a new `PageInfo` to
|
|
167
|
+
/// `page_infos` in `SerializeContext`, and only once we actually serialize
|
|
168
|
+
/// the page will the annotations be populated.
|
|
169
|
+
annotations: Vec<(Ref, OnceCell<Ref>)>,
|
|
170
|
+
/// The page label of the page.
|
|
171
|
+
page_label: PageLabel,
|
|
172
|
+
},
|
|
173
|
+
/// A page embedded from an external PDF file.
|
|
174
|
+
#[allow(dead_code)]
|
|
175
|
+
Pdf {
|
|
176
|
+
ref_: Ref,
|
|
177
|
+
size: Size,
|
|
178
|
+
page_label: PageLabel,
|
|
179
|
+
},
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
impl PageInfo {
|
|
183
|
+
pub(crate) fn ref_(&self) -> Ref {
|
|
184
|
+
match self {
|
|
185
|
+
PageInfo::Krilla { ref_, .. } => *ref_,
|
|
186
|
+
PageInfo::Pdf { ref_, .. } => *ref_,
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
pub(crate) fn size(&self) -> Size {
|
|
191
|
+
match self {
|
|
192
|
+
PageInfo::Krilla { surface_size, .. } => *surface_size,
|
|
193
|
+
PageInfo::Pdf { size, .. } => *size,
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
pub(crate) fn page_label(&self) -> &PageLabel {
|
|
198
|
+
match self {
|
|
199
|
+
PageInfo::Krilla { page_label, .. } => page_label,
|
|
200
|
+
PageInfo::Pdf { page_label, .. } => page_label,
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
pub(crate) fn annotations(&self) -> &[(Ref, OnceCell<Ref>)] {
|
|
205
|
+
match self {
|
|
206
|
+
PageInfo::Krilla { annotations, .. } => annotations,
|
|
207
|
+
PageInfo::Pdf { .. } => &[],
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
pub(crate) fn annotations_mut(&mut self) -> &mut [(Ref, OnceCell<Ref>)] {
|
|
212
|
+
match self {
|
|
213
|
+
PageInfo::Krilla { annotations, .. } => annotations,
|
|
214
|
+
PageInfo::Pdf { .. } => &mut [],
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
enum StructParentElement {
|
|
220
|
+
/// The index of the page and the number of marked content IDs present on that page.
|
|
221
|
+
Page(usize, i32),
|
|
222
|
+
/// The index of the page where the annotation is present, as well as the index of the
|
|
223
|
+
/// annotation within that one page.
|
|
224
|
+
Annotation(AnnotationIdentifier),
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
#[derive(Debug)]
|
|
228
|
+
pub(crate) enum MaybeDeviceColorSpace {
|
|
229
|
+
DeviceRgb,
|
|
230
|
+
DeviceGray,
|
|
231
|
+
DeviceCMYK,
|
|
232
|
+
ColorSpace(resource::ColorSpace),
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/// The serializer context is more or less the core piece of krilla. It is passed around
|
|
236
|
+
/// throughout pretty much the whole conversion process, and contains all mutable state
|
|
237
|
+
/// that is needed when writing a PDF file. This includes for example:
|
|
238
|
+
/// - Storing all chunks that are produced.
|
|
239
|
+
/// - The mappings from OTF fonts to CID/Type 3 fonts.
|
|
240
|
+
/// - Annotations used in the document.
|
|
241
|
+
/// etc.
|
|
242
|
+
pub(crate) struct SerializeContext {
|
|
243
|
+
/// The ref of the page tree.
|
|
244
|
+
page_tree_ref: Ref,
|
|
245
|
+
/// PDF 2.0 namespaces.
|
|
246
|
+
pub(crate) pdf2_ns: Pdf2Namespaces,
|
|
247
|
+
/// All global objects, such as PDF fonts, that are populated over time.
|
|
248
|
+
pub(crate) global_objects: GlobalObjects,
|
|
249
|
+
/// Information for each page written so far, index by the page index.
|
|
250
|
+
page_infos: Vec<PageInfo>,
|
|
251
|
+
/// Keep track of object hashes and their corresponding reference. This is used for
|
|
252
|
+
/// caching, so that for example same images will not be embedded twice in the document.
|
|
253
|
+
cached_mappings: HashMap<u128, Ref>,
|
|
254
|
+
/// The current ref in use. All serializers should use the `new_ref` method (which indirectly
|
|
255
|
+
/// is based on this field) to generate a new Ref, instead of creating one manually with
|
|
256
|
+
/// `Ref::new`.
|
|
257
|
+
pub(crate) cur_ref: Ref,
|
|
258
|
+
/// All validation errors that are collected as part of the export process
|
|
259
|
+
/// alongside the validators that raised the error.
|
|
260
|
+
validation_errors: Vec<(ValidationError, Validators)>,
|
|
261
|
+
/// Settings used for serialization.
|
|
262
|
+
serialize_settings: Arc<SerializeSettings>,
|
|
263
|
+
/// Settings used for all PDF object chunks.
|
|
264
|
+
chunk_settings: Settings,
|
|
265
|
+
/// The limits created as part of the serialization process. In principle, we could
|
|
266
|
+
/// just keep track of this in `ChunkContainer`, where all used chunks are stored.
|
|
267
|
+
/// The only reason why `SerializeContext` needs to know about them is that we also
|
|
268
|
+
/// need to merge limits from postscript functions, which are not directly accessible
|
|
269
|
+
/// from the chunk they are written to.
|
|
270
|
+
limits: Limits,
|
|
271
|
+
/// Additional information stored during serialization that allows us to
|
|
272
|
+
/// raise standards errors later.
|
|
273
|
+
validation_store: ValidationStore,
|
|
274
|
+
/// The current location, if set.
|
|
275
|
+
pub(crate) location: Option<Location>,
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
impl SerializeContext {
|
|
279
|
+
pub(crate) fn new(mut serialize_settings: SerializeSettings) -> Self {
|
|
280
|
+
// Override flags as required by the validator
|
|
281
|
+
serialize_settings.no_device_cs |= serialize_settings.validators().requires_no_device_cs();
|
|
282
|
+
serialize_settings.enable_tagging |= serialize_settings.validators().requires_tagging();
|
|
283
|
+
serialize_settings.xmp_metadata |= serialize_settings.validators().requires_xmp_metadata();
|
|
284
|
+
|
|
285
|
+
let mut cur_ref = Ref::new(1);
|
|
286
|
+
let page_tree_ref = cur_ref.bump();
|
|
287
|
+
let pdf2_ns = Pdf2Namespaces {
|
|
288
|
+
ssn_ref: cur_ref.bump(),
|
|
289
|
+
krilla_ref: cur_ref.bump(),
|
|
290
|
+
};
|
|
291
|
+
|
|
292
|
+
let chunk_settings = Settings {
|
|
293
|
+
pretty: serialize_settings.pretty,
|
|
294
|
+
};
|
|
295
|
+
|
|
296
|
+
Self {
|
|
297
|
+
cached_mappings: HashMap::new(),
|
|
298
|
+
pdf2_ns,
|
|
299
|
+
global_objects: GlobalObjects::default(),
|
|
300
|
+
cur_ref,
|
|
301
|
+
page_tree_ref,
|
|
302
|
+
page_infos: vec![],
|
|
303
|
+
location: None,
|
|
304
|
+
validation_errors: vec![],
|
|
305
|
+
serialize_settings: Arc::new(serialize_settings),
|
|
306
|
+
chunk_settings,
|
|
307
|
+
limits: Limits::new(),
|
|
308
|
+
validation_store: ValidationStore::new(),
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
pub(crate) fn page_infos(&self) -> &[PageInfo] {
|
|
313
|
+
&self.page_infos
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
pub(crate) fn page_infos_mut(&mut self) -> &mut [PageInfo] {
|
|
317
|
+
&mut self.page_infos
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
pub(crate) fn set_outline(&mut self, outline: Outline) {
|
|
321
|
+
// Only set it if it's not empty or if the current validator requires an
|
|
322
|
+
// outline.
|
|
323
|
+
if !outline.is_empty()
|
|
324
|
+
|| self
|
|
325
|
+
.serialize_settings
|
|
326
|
+
.validators()
|
|
327
|
+
.prohibits(&ValidationError::MissingDocumentOutline)
|
|
328
|
+
.is_some()
|
|
329
|
+
{
|
|
330
|
+
self.global_objects.outline = MaybeTaken::new(Some(outline));
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
pub(crate) fn set_location(&mut self, location: Location) {
|
|
335
|
+
self.location = Some(location)
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
pub(crate) fn reset_location(&mut self) {
|
|
339
|
+
self.location = None
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
pub(crate) fn embed_file(
|
|
343
|
+
&mut self,
|
|
344
|
+
chunk_container: &mut ChunkContainer,
|
|
345
|
+
file: EmbeddedFile,
|
|
346
|
+
) -> Option<()> {
|
|
347
|
+
let name = file.path.clone();
|
|
348
|
+
let ref_ = self.register_cacheable(chunk_container, file);
|
|
349
|
+
if self
|
|
350
|
+
.global_objects
|
|
351
|
+
.embedded_files
|
|
352
|
+
.insert(name, ref_)
|
|
353
|
+
.is_some()
|
|
354
|
+
{
|
|
355
|
+
None
|
|
356
|
+
} else {
|
|
357
|
+
Some(())
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
pub(crate) fn set_tag_tree(&mut self, root: TagTree) {
|
|
362
|
+
// Only set the tag tree if the user actually enabled tagging.
|
|
363
|
+
if self.serialize_settings.enable_tagging {
|
|
364
|
+
self.global_objects.tag_tree = MaybeTaken::new(Some(root))
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
pub(crate) fn new_ref(&mut self) -> Ref {
|
|
369
|
+
self.cur_ref.bump()
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
pub(crate) fn serialize_settings(&self) -> Arc<SerializeSettings> {
|
|
373
|
+
self.serialize_settings.clone()
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// IMPORTANT: DO NEVER CALL `Chunk::new`, `Pdf::new` or `Content::new` directly! Instead,
|
|
377
|
+
// always make sure to use the methods on `SerializeContext`, to ensure the
|
|
378
|
+
// flags are applied consistently across all chunks.
|
|
379
|
+
|
|
380
|
+
pub(crate) fn new_chunk(&self) -> Chunk {
|
|
381
|
+
Chunk::with_settings(self.chunk_settings)
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
pub(crate) fn new_content(&self) -> Content {
|
|
385
|
+
Content::with_settings(self.chunk_settings)
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
pub(crate) fn new_pdf_with_capacity(&self, capacity: usize) -> Pdf {
|
|
389
|
+
Pdf::with_settings_and_capacity(self.chunk_settings, capacity)
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
#[cfg(feature = "pdf")]
|
|
393
|
+
pub(crate) fn chunk_settings(&self) -> Settings {
|
|
394
|
+
self.chunk_settings
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
#[cfg(feature = "pdf")]
|
|
398
|
+
pub(crate) fn embed_pdf_pages(&mut self, pdf: &PdfDocument, page_indices: &[usize]) {
|
|
399
|
+
for page_idx in page_indices {
|
|
400
|
+
let page_ref = self.new_ref();
|
|
401
|
+
let size = pdf
|
|
402
|
+
.pages()
|
|
403
|
+
.get(*page_idx)
|
|
404
|
+
.and_then(|p| {
|
|
405
|
+
let (x, y) = p.render_dimensions();
|
|
406
|
+
Size::from_wh(x, y)
|
|
407
|
+
})
|
|
408
|
+
// In case the page doesn't exist, we will catch the error later, so just use
|
|
409
|
+
// a dummy size.
|
|
410
|
+
.unwrap_or(Size::from_wh(1.0, 1.0).unwrap());
|
|
411
|
+
self.global_objects
|
|
412
|
+
.pdf_ctx
|
|
413
|
+
.add_page(pdf, *page_idx, page_ref, self.location);
|
|
414
|
+
self.page_infos.push(PageInfo::Pdf {
|
|
415
|
+
ref_: page_ref,
|
|
416
|
+
size,
|
|
417
|
+
// TODO: Maybe this should be configurable.
|
|
418
|
+
page_label: PageLabel::default(),
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
#[cfg(feature = "pdf")]
|
|
424
|
+
pub(crate) fn embed_pdf_page_as_xobject(&mut self, pdf: &PdfDocument, page_idx: usize) -> Ref {
|
|
425
|
+
let xobj_ref = self.new_ref();
|
|
426
|
+
|
|
427
|
+
// Note that `add_xobject` might return a different ref than the one we created.
|
|
428
|
+
self.global_objects
|
|
429
|
+
.pdf_ctx
|
|
430
|
+
.add_xobject(pdf, page_idx, xobj_ref, self.location)
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
pub(crate) fn page_tree_ref(&mut self) -> Ref {
|
|
434
|
+
self.page_tree_ref
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
pub(crate) fn register_font_container(&mut self, font: Font) -> Rc<RefCell<FontContainer>> {
|
|
438
|
+
self.global_objects
|
|
439
|
+
.font_map
|
|
440
|
+
.entry(font.clone())
|
|
441
|
+
.or_insert_with(|| Rc::new(RefCell::new(FontContainer::new(font.clone()))))
|
|
442
|
+
.clone()
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
pub(crate) fn validation_store(&mut self) -> &mut ValidationStore {
|
|
446
|
+
&mut self.validation_store
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
pub(crate) fn finish(mut self, mut chunk_container: ChunkContainer) -> KrillaResult<Pdf> {
|
|
450
|
+
// We need to be careful here that we serialize the objects in the right order,
|
|
451
|
+
// as in some cases we use MaybeTake::take to remove an object, which means that
|
|
452
|
+
// no object that is serialized afterwards must depend on it.
|
|
453
|
+
|
|
454
|
+
// Serialize all objects that can only be written in the end.
|
|
455
|
+
self.serialize_destination_profiles(&mut chunk_container);
|
|
456
|
+
self.serialize_page_label_tree(&mut chunk_container);
|
|
457
|
+
self.serialize_outline(&mut chunk_container);
|
|
458
|
+
self.serialize_fonts(&mut chunk_container)?;
|
|
459
|
+
self.serialize_pages(&mut chunk_container)?;
|
|
460
|
+
self.serialize_page_tree(&mut chunk_container);
|
|
461
|
+
#[cfg(feature = "pdf")]
|
|
462
|
+
self.serialize_embedded_pdfs(&mut chunk_container)?;
|
|
463
|
+
self.serialize_xyz_destinations(&mut chunk_container)?;
|
|
464
|
+
// It is important that we serialize the tags AFTER we have serialized the pages,
|
|
465
|
+
// because page serialization will update the annotation refs of the page infos,
|
|
466
|
+
// and when serializing the parent tree map we need to know the refs of the annotations
|
|
467
|
+
self.serialize_tag_tree(&mut chunk_container)?;
|
|
468
|
+
|
|
469
|
+
// Create the final PDF.
|
|
470
|
+
let pdf = chunk_container.finish(&mut self)?;
|
|
471
|
+
self.register_limits(pdf.limits());
|
|
472
|
+
|
|
473
|
+
self.check_validator_limits();
|
|
474
|
+
|
|
475
|
+
if !self.validation_errors.is_empty() {
|
|
476
|
+
// Deduplicate errors, while still preserving order.
|
|
477
|
+
let mut errors = vec![];
|
|
478
|
+
let mut seen = HashSet::new();
|
|
479
|
+
|
|
480
|
+
for error in self.validation_errors {
|
|
481
|
+
if !seen.contains(&error) {
|
|
482
|
+
seen.insert(error.clone());
|
|
483
|
+
errors.push(error);
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
return Err(KrillaError::Validation(errors));
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
if let Some(limit_error) = self.check_version_limits() {
|
|
491
|
+
return Err(KrillaError::Limit(limit_error));
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
// Just a sanity check that we've actually processed all items.
|
|
495
|
+
self.global_objects.assert_all_taken();
|
|
496
|
+
|
|
497
|
+
Ok(pdf)
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
/// Various registration methods.
|
|
502
|
+
impl SerializeContext {
|
|
503
|
+
pub(crate) fn register_validation_error(&mut self, error: ValidationError) {
|
|
504
|
+
if let Some(validators) = self.serialize_settings().validators().prohibits(&error) {
|
|
505
|
+
self.validation_errors.push((error, validators))
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
pub(crate) fn register_limits(&mut self, limits: &Limits) {
|
|
510
|
+
self.limits.merge(limits);
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
pub(crate) fn register_page_struct_parent(
|
|
514
|
+
&mut self,
|
|
515
|
+
page_index: usize,
|
|
516
|
+
num_mcids: i32,
|
|
517
|
+
) -> Option<i32> {
|
|
518
|
+
if self.serialize_settings.enable_tagging {
|
|
519
|
+
if num_mcids == 0 {
|
|
520
|
+
return None;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
let id = self.global_objects.struct_parents.len();
|
|
524
|
+
self.global_objects
|
|
525
|
+
.struct_parents
|
|
526
|
+
.push(StructParentElement::Page(page_index, num_mcids));
|
|
527
|
+
Some(i32::try_from(id).unwrap())
|
|
528
|
+
} else {
|
|
529
|
+
None
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
/// Register the struct parent integer in the parent tree.
|
|
534
|
+
/// The annotation parent must be later set using [`Self::set_annotation_parent`].
|
|
535
|
+
pub(crate) fn register_annotation_parent(&mut self, ai: AnnotationIdentifier) -> Option<i32> {
|
|
536
|
+
if self.serialize_settings.enable_tagging {
|
|
537
|
+
let id = self.global_objects.struct_parents.len();
|
|
538
|
+
self.global_objects
|
|
539
|
+
.struct_parents
|
|
540
|
+
.push(StructParentElement::Annotation(ai));
|
|
541
|
+
Some(i32::try_from(id).unwrap())
|
|
542
|
+
} else {
|
|
543
|
+
None
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
pub(crate) fn register_named_destination(&mut self, nd: NamedDestination) -> Option<Ref> {
|
|
548
|
+
if let Some((dest_ref, existing)) =
|
|
549
|
+
self.global_objects.named_destinations.get(nd.name.as_ref())
|
|
550
|
+
{
|
|
551
|
+
return (existing == nd.xyz_dest.as_ref()).then_some(*dest_ref);
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
let dest_ref = self.register_xyz_destination((*nd.xyz_dest).clone());
|
|
555
|
+
self.global_objects
|
|
556
|
+
.named_destinations
|
|
557
|
+
.insert(nd.name.clone(), (dest_ref, (*nd.xyz_dest).clone()));
|
|
558
|
+
Some(dest_ref)
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
pub(crate) fn register_page(&mut self, page: InternalPage) {
|
|
562
|
+
let ref_ = self.new_ref();
|
|
563
|
+
self.page_infos.push(PageInfo::Krilla {
|
|
564
|
+
ref_,
|
|
565
|
+
surface_size: page.page_settings.surface_size(),
|
|
566
|
+
// Will be populated when the page is serialized.
|
|
567
|
+
annotations: vec![],
|
|
568
|
+
page_label: page.page_settings.page_label().clone(),
|
|
569
|
+
});
|
|
570
|
+
self.global_objects.pages.push((ref_, page));
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
fn register_cached<T: SipHashable>(
|
|
574
|
+
&mut self,
|
|
575
|
+
item: T,
|
|
576
|
+
mut func: impl FnMut(&mut Self, T, Ref),
|
|
577
|
+
) -> Ref {
|
|
578
|
+
let hash = item.sip_hash();
|
|
579
|
+
if let Some(_ref) = self.cached_mappings.get(&hash) {
|
|
580
|
+
*_ref
|
|
581
|
+
} else {
|
|
582
|
+
let root_ref = self.new_ref();
|
|
583
|
+
func(self, item, root_ref);
|
|
584
|
+
self.cached_mappings.insert(hash, root_ref);
|
|
585
|
+
root_ref
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
pub(crate) fn register_cacheable<T>(
|
|
590
|
+
&mut self,
|
|
591
|
+
chunk_container: &mut ChunkContainer,
|
|
592
|
+
object: T,
|
|
593
|
+
) -> Ref
|
|
594
|
+
where
|
|
595
|
+
T: Cacheable,
|
|
596
|
+
{
|
|
597
|
+
self.register_cached(object, |sc, object, root_ref| {
|
|
598
|
+
object.serialize(sc, chunk_container, root_ref);
|
|
599
|
+
})
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
pub(crate) fn register_resourceable<T>(
|
|
603
|
+
&mut self,
|
|
604
|
+
chunk_container: &mut ChunkContainer,
|
|
605
|
+
object: T,
|
|
606
|
+
) -> T::Resource
|
|
607
|
+
where
|
|
608
|
+
T: Resourceable,
|
|
609
|
+
{
|
|
610
|
+
Resource::new(self.register_cacheable(chunk_container, object))
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
#[cfg(feature = "raster-images")]
|
|
614
|
+
pub(crate) fn register_image(
|
|
615
|
+
&mut self,
|
|
616
|
+
chunk_container: &mut ChunkContainer,
|
|
617
|
+
image: Image,
|
|
618
|
+
) -> Ref {
|
|
619
|
+
self.register_cached(image, |sc, object, root_ref| {
|
|
620
|
+
object.serialize(sc, chunk_container, root_ref);
|
|
621
|
+
})
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
pub(crate) fn register_xyz_destination(&mut self, dest: XyzDestination) -> Ref {
|
|
625
|
+
self.register_cached(dest, |sc, dest, root_ref| {
|
|
626
|
+
sc.global_objects.xyz_destinations.push((root_ref, dest));
|
|
627
|
+
})
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
pub(crate) fn register_page_label(
|
|
631
|
+
&mut self,
|
|
632
|
+
chunk_container: &mut ChunkContainer,
|
|
633
|
+
page_label: PageLabel,
|
|
634
|
+
) -> Ref {
|
|
635
|
+
let ref_ = self.new_ref();
|
|
636
|
+
page_label.serialize(chunk_container, ref_);
|
|
637
|
+
ref_
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
pub(crate) fn register_font_identifier(&mut self, f: FontIdentifier) -> resource::Font {
|
|
641
|
+
let hash = f.sip_hash();
|
|
642
|
+
if let Some(_ref) = self.cached_mappings.get(&hash) {
|
|
643
|
+
resource::Font::new(*_ref)
|
|
644
|
+
} else {
|
|
645
|
+
let root_ref = self.new_ref();
|
|
646
|
+
self.cached_mappings.insert(hash, root_ref);
|
|
647
|
+
resource::Font::new(root_ref)
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
pub(crate) fn register_colorspace(
|
|
652
|
+
&mut self,
|
|
653
|
+
chunk_container: &mut ChunkContainer,
|
|
654
|
+
cs: ColorSpace,
|
|
655
|
+
) -> MaybeDeviceColorSpace {
|
|
656
|
+
match cs {
|
|
657
|
+
ColorSpace::CieBased(CieBasedColorSpace::Srgb) => {
|
|
658
|
+
MaybeDeviceColorSpace::ColorSpace(self.register_resourceable(
|
|
659
|
+
chunk_container,
|
|
660
|
+
ICCBasedColorSpace(self.serialize_settings.pdf_version().rgb_icc()),
|
|
661
|
+
))
|
|
662
|
+
}
|
|
663
|
+
ColorSpace::CieBased(CieBasedColorSpace::Luma) => {
|
|
664
|
+
MaybeDeviceColorSpace::ColorSpace(self.register_resourceable(
|
|
665
|
+
chunk_container,
|
|
666
|
+
ICCBasedColorSpace(self.serialize_settings.pdf_version().grey_icc()),
|
|
667
|
+
))
|
|
668
|
+
}
|
|
669
|
+
ColorSpace::CieBased(CieBasedColorSpace::Cmyk(cs)) => {
|
|
670
|
+
MaybeDeviceColorSpace::ColorSpace(self.register_resourceable(chunk_container, cs))
|
|
671
|
+
}
|
|
672
|
+
ColorSpace::Device(DeviceColorSpace::Gray) => MaybeDeviceColorSpace::DeviceGray,
|
|
673
|
+
ColorSpace::Device(DeviceColorSpace::Rgb) => MaybeDeviceColorSpace::DeviceRgb,
|
|
674
|
+
ColorSpace::Device(DeviceColorSpace::Cmyk) => MaybeDeviceColorSpace::DeviceCMYK,
|
|
675
|
+
ColorSpace::Special(SpecialColorSpace::Separation(s)) => {
|
|
676
|
+
MaybeDeviceColorSpace::ColorSpace(
|
|
677
|
+
self.register_resourceable(chunk_container, SeparationColorSpace::new(s)),
|
|
678
|
+
)
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
/// Various serialization methods.
|
|
685
|
+
/// All methods are supposed to only be called once in `SerializeContext::finish`!
|
|
686
|
+
impl SerializeContext {
|
|
687
|
+
fn serialize_destination_profiles(&mut self, chunk_container: &mut ChunkContainer) {
|
|
688
|
+
let validators = self.serialize_settings.validators();
|
|
689
|
+
chunk_container.non_stream.destination_profiles =
|
|
690
|
+
validators.output_intent().map(|subtype| {
|
|
691
|
+
let root_ref = self.new_ref();
|
|
692
|
+
let mut chunk = self.new_chunk();
|
|
693
|
+
|
|
694
|
+
let oi_ref = self.new_ref();
|
|
695
|
+
let mut oi = chunk.indirect(oi_ref).start::<OutputIntent>();
|
|
696
|
+
let icc_profile = self.serialize_settings.pdf_version().rgb_icc();
|
|
697
|
+
|
|
698
|
+
oi.dest_output_profile(
|
|
699
|
+
self.register_cacheable(chunk_container, icc_profile.clone()),
|
|
700
|
+
)
|
|
701
|
+
.subtype(subtype)
|
|
702
|
+
.output_condition_identifier(TextStr("Custom"))
|
|
703
|
+
.output_condition(TextStr("sRGB"))
|
|
704
|
+
.registry_name(TextStr(""))
|
|
705
|
+
.info(TextStr(
|
|
706
|
+
format!(
|
|
707
|
+
"sRGB v{}.{}",
|
|
708
|
+
icc_profile.metadata().major,
|
|
709
|
+
icc_profile.metadata().minor
|
|
710
|
+
)
|
|
711
|
+
.as_str(),
|
|
712
|
+
));
|
|
713
|
+
oi.finish();
|
|
714
|
+
|
|
715
|
+
let mut array = chunk.indirect(root_ref).array();
|
|
716
|
+
array.item(oi_ref);
|
|
717
|
+
array.finish();
|
|
718
|
+
|
|
719
|
+
(root_ref, chunk)
|
|
720
|
+
});
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
fn serialize_page_label_tree(&mut self, chunk_container: &mut ChunkContainer) {
|
|
724
|
+
if let Some(container) = PageLabelContainer::new(
|
|
725
|
+
&self
|
|
726
|
+
.page_infos
|
|
727
|
+
.iter()
|
|
728
|
+
.map(|page| page.page_label().clone())
|
|
729
|
+
.collect::<Vec<_>>(),
|
|
730
|
+
) {
|
|
731
|
+
let page_label_tree_ref = self.new_ref();
|
|
732
|
+
container.serialize(self, chunk_container, page_label_tree_ref);
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
fn serialize_outline(&mut self, chunk_container: &mut ChunkContainer) {
|
|
737
|
+
let outline = self.global_objects.outline.take();
|
|
738
|
+
if let Some(outline) = &outline {
|
|
739
|
+
let outline_ref = self.new_ref();
|
|
740
|
+
outline.serialize(self, chunk_container, outline_ref);
|
|
741
|
+
} else {
|
|
742
|
+
self.register_validation_error(ValidationError::MissingDocumentOutline);
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
#[cfg(feature = "pdf")]
|
|
747
|
+
fn serialize_embedded_pdfs(
|
|
748
|
+
&mut self,
|
|
749
|
+
chunk_container: &mut ChunkContainer,
|
|
750
|
+
) -> KrillaResult<()> {
|
|
751
|
+
let pdf_ctx = self.global_objects.pdf_ctx.take();
|
|
752
|
+
|
|
753
|
+
pdf_ctx.serialize(self, chunk_container)
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
fn serialize_fonts(&mut self, chunk_container: &mut ChunkContainer) -> KrillaResult<()> {
|
|
757
|
+
let fonts = self.global_objects.font_map.take();
|
|
758
|
+
for font_container in fonts.values() {
|
|
759
|
+
let borrowed = font_container.borrow();
|
|
760
|
+
|
|
761
|
+
if !borrowed.type3_mapper().is_empty() {
|
|
762
|
+
for t3_font in borrowed.type3_mapper().fonts() {
|
|
763
|
+
let f = self.register_font_identifier(t3_font.identifier());
|
|
764
|
+
t3_font.serialize(self, chunk_container, f.get_ref());
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
if !borrowed.cid_font().is_empty() {
|
|
769
|
+
let f = self.register_font_identifier(borrowed.cid_font().identifier());
|
|
770
|
+
borrowed
|
|
771
|
+
.cid_font()
|
|
772
|
+
.serialize(self, chunk_container, f.get_ref())?;
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
Ok(())
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
fn serialize_pages(&mut self, chunk_container: &mut ChunkContainer) -> KrillaResult<()> {
|
|
780
|
+
let pages = self.global_objects.pages.take();
|
|
781
|
+
for (ref_, page) in pages {
|
|
782
|
+
page.serialize(self, chunk_container, ref_)?;
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
Ok(())
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
fn serialize_page_tree(&mut self, chunk_container: &mut ChunkContainer) {
|
|
789
|
+
let mut page_tree_chunk = self.new_chunk();
|
|
790
|
+
page_tree_chunk
|
|
791
|
+
.pages(self.page_tree_ref)
|
|
792
|
+
.count(self.page_infos.len() as i32)
|
|
793
|
+
.kids(self.page_infos.iter().map(|i| i.ref_()));
|
|
794
|
+
chunk_container.non_stream.page_tree = Some((self.page_tree_ref, page_tree_chunk));
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
fn serialize_xyz_destinations(
|
|
798
|
+
&mut self,
|
|
799
|
+
chunk_container: &mut ChunkContainer,
|
|
800
|
+
) -> KrillaResult<()> {
|
|
801
|
+
let xyz_destinations = self.global_objects.xyz_destinations.take();
|
|
802
|
+
for (ref_, dest) in &xyz_destinations {
|
|
803
|
+
dest.serialize(self, chunk_container, *ref_);
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
Ok(())
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
fn serialize_tag_tree(&mut self, chunk_container: &mut ChunkContainer) -> KrillaResult<()> {
|
|
810
|
+
let tag_tree = self.global_objects.tag_tree.take();
|
|
811
|
+
let struct_parents = self.global_objects.struct_parents.take();
|
|
812
|
+
if let Some(root) = &tag_tree {
|
|
813
|
+
let mut parent_tree_map = HashMap::new();
|
|
814
|
+
let mut id_tree_map = BTreeMap::new();
|
|
815
|
+
let struct_tree_root_ref = self.new_ref();
|
|
816
|
+
let document_ref = root.serialize(
|
|
817
|
+
self,
|
|
818
|
+
chunk_container,
|
|
819
|
+
&mut parent_tree_map,
|
|
820
|
+
&mut id_tree_map,
|
|
821
|
+
struct_tree_root_ref,
|
|
822
|
+
)?;
|
|
823
|
+
|
|
824
|
+
root.validate(&id_tree_map)?;
|
|
825
|
+
|
|
826
|
+
let mut chunk = self.new_chunk();
|
|
827
|
+
let mut tree = chunk
|
|
828
|
+
.indirect(struct_tree_root_ref)
|
|
829
|
+
.start::<StructTreeRoot>();
|
|
830
|
+
|
|
831
|
+
let mut sub_chunks = vec![];
|
|
832
|
+
|
|
833
|
+
if self.serialize_settings.pdf_version() < PdfVersion::Pdf20 {
|
|
834
|
+
let mut role_map = tree.role_map();
|
|
835
|
+
// Custom structure elements.
|
|
836
|
+
role_map.insert(Name(b"Datetime"), StructRole::Span);
|
|
837
|
+
role_map.insert(Name(b"Terms"), StructRole::Part);
|
|
838
|
+
|
|
839
|
+
// PDF 2.0 exclusive structure elements.
|
|
840
|
+
role_map.insert(Name(b"Title"), StructRole::P);
|
|
841
|
+
role_map.insert(Name(b"Strong"), StructRole::Span);
|
|
842
|
+
role_map.insert(Name(b"Em"), StructRole::Span);
|
|
843
|
+
for level in self.global_objects.custom_heading_roles.iter() {
|
|
844
|
+
let role2 = StructRole2::Heading(*level);
|
|
845
|
+
role_map.insert(role2.to_name(&mut [0; 6]), StructRole::P);
|
|
846
|
+
}
|
|
847
|
+
} else {
|
|
848
|
+
let mut namespaces = tree.namespaces();
|
|
849
|
+
|
|
850
|
+
// PDF 2.0 standard structure namespace
|
|
851
|
+
namespaces.item(self.pdf2_ns.ssn_ref);
|
|
852
|
+
let mut ns_chunk = self.new_chunk();
|
|
853
|
+
ns_chunk.namespace(self.pdf2_ns.ssn_ref).pdf_2_ns();
|
|
854
|
+
sub_chunks.push(ns_chunk);
|
|
855
|
+
|
|
856
|
+
// Custom krilla namspace
|
|
857
|
+
namespaces.item(self.pdf2_ns.krilla_ref);
|
|
858
|
+
let mut ns_chunk = self.new_chunk();
|
|
859
|
+
let mut ns = ns_chunk.namespace(self.pdf2_ns.krilla_ref);
|
|
860
|
+
ns.ns(TextStr("https://github.com/LaurenzV/krilla"));
|
|
861
|
+
|
|
862
|
+
// Custom structure elements.
|
|
863
|
+
ns.role_map_ns()
|
|
864
|
+
.to_pdf_2_0(Name(b"Datetime"), StructRole2::Span, self.pdf2_ns.ssn_ref)
|
|
865
|
+
.to_pdf_2_0(Name(b"Terms"), StructRole2::Part, self.pdf2_ns.ssn_ref);
|
|
866
|
+
|
|
867
|
+
ns.finish();
|
|
868
|
+
sub_chunks.push(ns_chunk);
|
|
869
|
+
}
|
|
870
|
+
tree.children().item(document_ref);
|
|
871
|
+
|
|
872
|
+
if !struct_parents.is_empty() {
|
|
873
|
+
let mut parent_tree = tree.parent_tree();
|
|
874
|
+
let mut tree_nums = parent_tree.nums();
|
|
875
|
+
|
|
876
|
+
for (index, struct_parent) in struct_parents.iter().enumerate() {
|
|
877
|
+
match *struct_parent {
|
|
878
|
+
StructParentElement::Page(page_index, num_mcids) => {
|
|
879
|
+
let mut list_chunk = self.new_chunk();
|
|
880
|
+
let list_ref = self.new_ref();
|
|
881
|
+
|
|
882
|
+
let mut refs = list_chunk.indirect(list_ref).array();
|
|
883
|
+
|
|
884
|
+
for mcid in 0..num_mcids {
|
|
885
|
+
let rci = PageTagIdentifier::new(page_index, mcid);
|
|
886
|
+
refs.item(parent_tree_map.get(&rci.into()).unwrap_or_else(|| {
|
|
887
|
+
panic!(
|
|
888
|
+
"page tag identifier {rci:?} doesn't appear in the tag tree"
|
|
889
|
+
)
|
|
890
|
+
}));
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
refs.finish();
|
|
894
|
+
|
|
895
|
+
sub_chunks.push(list_chunk);
|
|
896
|
+
tree_nums.insert(index as i32, list_ref);
|
|
897
|
+
}
|
|
898
|
+
StructParentElement::Annotation(ai) => {
|
|
899
|
+
// Write a reference to the parent structure element.
|
|
900
|
+
// From the PDF 1.7 spec (14.7.5.4 Finding structure elements from content items):
|
|
901
|
+
// > For an object identified as a content item by means of an object reference
|
|
902
|
+
// > (see 14.7.5.3, "PDF objects as content items"), the value shall be an
|
|
903
|
+
// > indirect reference to the parent structure element.
|
|
904
|
+
let page_annotations = &self.page_infos[ai.page_index].annotations();
|
|
905
|
+
let parent_ref =
|
|
906
|
+
*page_annotations[ai.annot_index].1.get().unwrap_or_else(|| {
|
|
907
|
+
panic!("annotation identifier {ai:?} doesn't appear in the tag tree")
|
|
908
|
+
});
|
|
909
|
+
tree_nums.insert(index as i32, parent_ref);
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
tree_nums.finish();
|
|
915
|
+
parent_tree.finish();
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
if !id_tree_map.is_empty() {
|
|
919
|
+
let mut id_tree = tree.id_tree();
|
|
920
|
+
let mut names = id_tree.names();
|
|
921
|
+
|
|
922
|
+
for (name, ref_) in id_tree_map {
|
|
923
|
+
names.insert(Str(name.as_bytes()), ref_);
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
if !struct_parents.is_empty() {
|
|
928
|
+
tree.parent_tree_next_key(struct_parents.len() as i32);
|
|
929
|
+
}
|
|
930
|
+
tree.finish();
|
|
931
|
+
|
|
932
|
+
for sub_chunk in sub_chunks {
|
|
933
|
+
chunk.extend(&sub_chunk);
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
chunk_container.non_stream.struct_tree_root = Some((struct_tree_root_ref, chunk));
|
|
937
|
+
} else {
|
|
938
|
+
self.register_validation_error(ValidationError::MissingTagging);
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
Ok(())
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
fn check_validator_limits(&mut self) {
|
|
945
|
+
if self.cur_ref > Ref::new(8388607) {
|
|
946
|
+
self.register_validation_error(ValidationError::TooManyIndirectObjects)
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
if self.limits.str_len() > STR_LEN {
|
|
950
|
+
self.register_validation_error(ValidationError::TooLongString);
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
if self.limits.name_len() > NAME_LEN {
|
|
954
|
+
self.register_validation_error(ValidationError::TooLongName);
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
if self.limits.real() > MAX_FLOAT {
|
|
958
|
+
self.register_validation_error(ValidationError::TooLargeFloat);
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
if self.limits.array_len() > ARRAY_LEN {
|
|
962
|
+
self.register_validation_error(ValidationError::TooLongArray);
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
if self.limits.dict_entries() > DICT_LEN {
|
|
966
|
+
self.register_validation_error(ValidationError::TooLongDictionary);
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
fn check_version_limits(&self) -> Option<LimitError> {
|
|
971
|
+
if self.serialize_settings.pdf_version() != PdfVersion::Pdf14 {
|
|
972
|
+
return None;
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
if self.limits.real() > MAX_FLOAT {
|
|
976
|
+
return Some(LimitError::TooLargeFloat);
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
if self.limits.array_len() > ARRAY_LEN {
|
|
980
|
+
return Some(LimitError::TooLongArray);
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
if self.limits.dict_entries() > DICT_LEN {
|
|
984
|
+
return Some(LimitError::TooLongDictionary);
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
None
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
/// This struct is essentially a thin wrapper around `std::mem::replace`. When finishing the
|
|
992
|
+
/// document, we need to take ownership of many of the items in `GlobalObjects` in order to
|
|
993
|
+
/// prevent having to clone them. However, the problem is that we cannot easily take ownership
|
|
994
|
+
/// of them, because they are part of the SerializeContext. Because of this, what we
|
|
995
|
+
/// do is that we `std::mem::replace` the elements step by step and then serialize them.
|
|
996
|
+
/// The `MaybeTaken` struct helps us to ensure that once we have taken a value, we do not
|
|
997
|
+
/// accidentally attempt to write/read it again.
|
|
998
|
+
pub(crate) struct MaybeTaken<T>(Option<T>);
|
|
999
|
+
|
|
1000
|
+
impl<T> MaybeTaken<T> {
|
|
1001
|
+
pub(crate) fn new(item: T) -> Self {
|
|
1002
|
+
Self(Some(item))
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
pub(crate) fn is_taken(&self) -> bool {
|
|
1006
|
+
self.0.is_none()
|
|
1007
|
+
}
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
impl<T> MaybeTaken<T> {
|
|
1011
|
+
#[track_caller]
|
|
1012
|
+
pub(crate) fn take(&mut self) -> T {
|
|
1013
|
+
self.0.take().expect("value was already taken before")
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
impl<T: Default> Default for MaybeTaken<T> {
|
|
1018
|
+
fn default() -> Self {
|
|
1019
|
+
Self::new(T::default())
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
impl<T> Deref for MaybeTaken<T> {
|
|
1024
|
+
type Target = T;
|
|
1025
|
+
|
|
1026
|
+
#[track_caller]
|
|
1027
|
+
fn deref(&self) -> &Self::Target {
|
|
1028
|
+
self.0.as_ref().expect("value was taken")
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
impl<T> DerefMut for MaybeTaken<T> {
|
|
1033
|
+
#[track_caller]
|
|
1034
|
+
fn deref_mut(&mut self) -> &mut Self::Target {
|
|
1035
|
+
self.0.as_mut().expect("value was taken")
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
pub(crate) struct Pdf2Namespaces {
|
|
1040
|
+
/// The ref of the PDF 2.0 standard structure namspace (`https://www.iso.org/pdf2/ssn`).
|
|
1041
|
+
pub(crate) ssn_ref: Ref,
|
|
1042
|
+
/// The ref of the custom krilla namespace used for role mapping.
|
|
1043
|
+
pub(crate) krilla_ref: Ref,
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
#[derive(Default)]
|
|
1047
|
+
pub(crate) struct GlobalObjects {
|
|
1048
|
+
/// All named destinations that have been registered, including a Ref to their destination and
|
|
1049
|
+
/// the destination itself.
|
|
1050
|
+
// Needs to be pub(crate) because writing of named destinations happens in `ChunkContainer`.
|
|
1051
|
+
pub(crate) named_destinations: MaybeTaken<HashMap<Arc<String>, (Ref, XyzDestination)>>,
|
|
1052
|
+
/// A map from fonts to font container.
|
|
1053
|
+
font_map: MaybeTaken<IndexMap<Font, Rc<RefCell<FontContainer>>>>,
|
|
1054
|
+
/// All XYZ destinations used in the document. The reason we need to store them
|
|
1055
|
+
/// separately is that we can only serialize them in the very end, once all pages
|
|
1056
|
+
/// have been written, so that we know the Ref of the page they belong to.
|
|
1057
|
+
xyz_destinations: MaybeTaken<Vec<(Ref, XyzDestination)>>,
|
|
1058
|
+
/// All pages and their corresponding chunks. Similarly to destinations, they need
|
|
1059
|
+
/// to be written in the very end, because pages might contain annotations which in turn
|
|
1060
|
+
/// depend on future pages (not written yet), so pages must also only be written in the
|
|
1061
|
+
/// very end.
|
|
1062
|
+
pages: MaybeTaken<Vec<(Ref, InternalPage)>>,
|
|
1063
|
+
/// Stores the struct parent elements.
|
|
1064
|
+
struct_parents: MaybeTaken<Vec<StructParentElement>>,
|
|
1065
|
+
/// Stores the document outline.
|
|
1066
|
+
outline: MaybeTaken<Option<Outline>>,
|
|
1067
|
+
/// Stores the tag tree.
|
|
1068
|
+
tag_tree: MaybeTaken<Option<TagTree>>,
|
|
1069
|
+
/// Stores the association of the names of embedded files to their refs,
|
|
1070
|
+
/// for the catalog dictionary.
|
|
1071
|
+
pub(crate) embedded_files: MaybeTaken<BTreeMap<String, Ref>>,
|
|
1072
|
+
/// A list of custom headings numbers used in the document.
|
|
1073
|
+
pub(crate) custom_heading_roles: BTreeSet<NonZeroU16>,
|
|
1074
|
+
/// The context tracking all of the pdfs and their pages that have been inserted.
|
|
1075
|
+
#[cfg(feature = "pdf")]
|
|
1076
|
+
pub(crate) pdf_ctx: MaybeTaken<PdfSerializerContext>,
|
|
1077
|
+
}
|
|
1078
|
+
|
|
1079
|
+
impl GlobalObjects {
|
|
1080
|
+
pub(crate) fn assert_all_taken(&self) {
|
|
1081
|
+
assert!(self.named_destinations.is_taken());
|
|
1082
|
+
assert!(self.font_map.is_taken());
|
|
1083
|
+
assert!(self.xyz_destinations.is_taken());
|
|
1084
|
+
assert!(self.pages.is_taken());
|
|
1085
|
+
assert!(self.struct_parents.is_taken());
|
|
1086
|
+
assert!(self.outline.is_taken());
|
|
1087
|
+
assert!(self.tag_tree.is_taken());
|
|
1088
|
+
assert!(self.embedded_files.is_taken());
|
|
1089
|
+
#[cfg(feature = "pdf")]
|
|
1090
|
+
assert!(self.pdf_ctx.is_taken());
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
pub(crate) trait Cacheable: SipHashable {
|
|
1095
|
+
fn serialize(
|
|
1096
|
+
self,
|
|
1097
|
+
sc: &mut SerializeContext,
|
|
1098
|
+
chunk_container: &mut ChunkContainer,
|
|
1099
|
+
root_ref: Ref,
|
|
1100
|
+
);
|
|
1101
|
+
}
|