skia_safe/docs/
pdf_document.rs

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
pub mod pdf {
    use std::{ffi::CString, fmt, io, mem, ptr};

    use crate::Canvas;

    use skia_bindings::{
        self as sb, SkPDF_AttributeList, SkPDF_DateTime, SkPDF_Metadata, SkPDF_StructureElementNode,
    };

    use crate::{
        interop::{AsStr, RustWStream, SetStr},
        prelude::*,
        scalar, Document, MILESTONE,
    };

    pub type AttributeList = Handle<SkPDF_AttributeList>;
    unsafe_send_sync!(AttributeList);

    impl NativeDrop for SkPDF_AttributeList {
        fn drop(&mut self) {
            unsafe { sb::C_SkPDF_AttributeList_destruct(self) }
        }
    }

    impl Default for AttributeList {
        fn default() -> Self {
            AttributeList::from_native_c(unsafe { SkPDF_AttributeList::new() })
        }
    }

    impl fmt::Debug for AttributeList {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.debug_struct("AttributeList").finish()
        }
    }

    /// Attributes for nodes in the PDF tree.
    ///
    /// Each attribute must have an owner (e.g. "Layout", "List", "Table", etc)
    /// and an attribute name (e.g. "BBox", "RowSpan", etc.) from PDF32000_2008 14.8.5,
    /// and then a value of the proper type according to the spec.
    impl AttributeList {
        pub fn append_int(
            &mut self,
            owner: impl AsRef<str>,
            name: impl AsRef<str>,
            value: i32,
        ) -> &mut Self {
            let owner = CString::new(owner.as_ref()).unwrap();
            let name = CString::new(name.as_ref()).unwrap();
            unsafe {
                self.native_mut()
                    .appendInt(owner.as_ptr(), name.as_ptr(), value)
            }
            self
        }

        pub fn append_float(
            &mut self,
            owner: impl AsRef<str>,
            name: impl AsRef<str>,
            value: f32,
        ) -> &mut Self {
            let owner = CString::new(owner.as_ref()).unwrap();
            let name = CString::new(name.as_ref()).unwrap();
            unsafe {
                self.native_mut()
                    .appendFloat(owner.as_ptr(), name.as_ptr(), value)
            }
            self
        }

        pub fn append_float_array(
            &mut self,
            owner: impl AsRef<str>,
            name: impl AsRef<str>,
            value: &[f32],
        ) -> &mut Self {
            let owner = CString::new(owner.as_ref()).unwrap();
            let name = CString::new(name.as_ref()).unwrap();
            unsafe {
                sb::C_SkPDF_AttributeList_appendFloatArray(
                    self.native_mut(),
                    owner.as_ptr(),
                    name.as_ptr(),
                    value.as_ptr(),
                    value.len(),
                )
            }
            self
        }
    }

    #[repr(transparent)]
    pub struct StructureElementNode(ptr::NonNull<SkPDF_StructureElementNode>);

    impl NativeAccess for StructureElementNode {
        type Native = SkPDF_StructureElementNode;

        fn native(&self) -> &SkPDF_StructureElementNode {
            unsafe { self.0.as_ref() }
        }
        fn native_mut(&mut self) -> &mut SkPDF_StructureElementNode {
            unsafe { self.0.as_mut() }
        }
    }

    impl Drop for StructureElementNode {
        fn drop(&mut self) {
            unsafe { sb::C_SkPDF_StructureElementNode_delete(self.native_mut()) }
        }
    }

    impl Default for StructureElementNode {
        fn default() -> Self {
            Self(ptr::NonNull::new(unsafe { sb::C_SkPDF_StructureElementNode_new() }).unwrap())
        }
    }

    impl fmt::Debug for StructureElementNode {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.debug_struct("StructureElementNode")
                .field("type_string", &self.type_string())
                .field("child_vector", &self.child_vector())
                .field("node_id", &self.node_id())
                .field("attributes", &self.attributes())
                .field("alt", &self.alt())
                .field("lang", &self.lang())
                .finish()
        }
    }

    /// A node in a PDF structure tree, giving a semantic representation
    /// of the content.  Each node ID is associated with content
    /// by passing the [`crate::Canvas`] and node ID to [`set_node_id()`] when drawing.
    /// NodeIDs should be unique within each tree.
    impl StructureElementNode {
        pub fn new(type_string: impl AsRef<str>) -> Self {
            let mut node = Self::default();
            node.set_type_string(type_string);
            node
        }

        pub fn set_type_string(&mut self, type_string: impl AsRef<str>) -> &mut Self {
            self.native_mut().fTypeString.set_str(type_string);
            self
        }

        pub fn type_string(&self) -> &str {
            self.native().fTypeString.as_str()
        }

        pub fn set_child_vector(
            &mut self,
            mut child_vector: Vec<StructureElementNode>,
        ) -> &mut Self {
            // strategy is to move them out by setting them to nullptr (drop() will handle a nullptr on the rust side)
            unsafe {
                sb::C_SkPDF_StructureElementNode_setChildVector(
                    self.native_mut(),
                    child_vector.as_mut_ptr() as _,
                    child_vector.len(),
                )
            }
            self
        }

        pub fn append_child(&mut self, node: StructureElementNode) -> &mut Self {
            unsafe {
                sb::C_SkPDF_StructElementNode_appendChild(self.native_mut(), node.0.as_ptr());
            }
            mem::forget(node);
            self
        }

        pub fn child_vector(&self) -> &[StructureElementNode] {
            let mut ptr = ptr::null();
            unsafe {
                let len = sb::C_SkPDF_StructureElementNode_getChildVector(self.native(), &mut ptr);
                safer::from_raw_parts(ptr as _, len)
            }
        }

        pub fn set_node_id(&mut self, node_id: i32) -> &mut Self {
            self.native_mut().fNodeId = node_id;
            self
        }

        pub fn node_id(&self) -> i32 {
            self.native().fNodeId
        }

        pub fn attributes(&self) -> &AttributeList {
            AttributeList::from_native_ref(&self.native().fAttributes)
        }

        pub fn attributes_mut(&mut self) -> &mut AttributeList {
            AttributeList::from_native_ref_mut(&mut self.native_mut().fAttributes)
        }

        pub fn set_alt(&mut self, alt: impl AsRef<str>) -> &mut Self {
            self.native_mut().fAlt.set_str(alt);
            self
        }

        pub fn alt(&self) -> &str {
            self.native().fAlt.as_str()
        }

        pub fn set_lang(&mut self, lang: impl AsRef<str>) -> &mut Self {
            self.native_mut().fLang.set_str(lang);
            self
        }

        pub fn lang(&self) -> &str {
            self.native().fLang.as_str()
        }
    }

    #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
    #[repr(C)]
    pub struct DateTime {
        /// The number of minutes that this is ahead of or behind UTC.
        pub time_zone_minutes: i16,
        /// e.g. 2005
        pub year: u16,
        /// 1..12
        pub month: u8,
        /// 0..6, 0==Sunday
        pub day_of_week: u8,
        /// 1..31
        pub day: u8,
        /// 0..23
        pub hour: u8,
        /// 0..59
        pub minute: u8,
        /// 0..59
        pub second: u8,
    }

    native_transmutable!(SkPDF_DateTime, DateTime, date_time_layout);

    /// Optional metadata to be passed into the PDF factory function.
    #[derive(Debug)]
    pub struct Metadata {
        /// The document's title.
        pub title: String,
        /// The name of the person who created the document.
        pub author: String,
        /// The subject of the document.
        pub subject: String,
        /// Keywords associated with the document. Commas may be used to delineate keywords within
        /// the string.
        pub keywords: String,
        /// If the document was converted to PDF from another format, the name of the conforming
        /// product that created the original document from which it was converted.
        pub creator: String,
        /// The product that is converting this document to PDF.
        pub producer: String,
        /// The date and time the document was created.
        pub creation: Option<DateTime>,
        /// The date and time the document was most recently modified.
        pub modified: Option<DateTime>,
        /// The natural language of the text in the PDF. If `lang` is empty, the root
        /// StructureElementNode::lang will be used (if not empty). Text not in
        /// this language should be marked with StructureElementNode::lang.
        pub lang: String,
        /// The DPI (pixels-per-inch) at which features without native PDF support
        /// will be rasterized (e.g. draw image with perspective, draw text with
        /// perspective, ...)  A larger DPI would create a PDF that reflects the
        /// original intent with better fidelity, but it can make for larger PDF
        /// files too, which would use more memory while rendering, and it would be
        /// slower to be processed or sent online or to printer.
        pub raster_dpi: Option<scalar>,
        /// If `true`, include XMP metadata, a document UUID, and `s_rgb` output intent
        /// information.  This adds length to the document and makes it
        /// non-reproducible, but are necessary features for PDF/A-2b conformance
        pub pdf_a: bool,
        /// Encoding quality controls the trade-off between size and quality. By default this is set
        /// to 101 percent, which corresponds to lossless encoding. If this value is set to a value
        /// <= 100, and the image is opaque, it will be encoded (using JPEG) with that quality
        /// setting.
        pub encoding_quality: Option<i32>,

        pub structure_element_tree_root: Option<StructureElementNode>,

        /// PDF streams may be compressed to save space.
        /// Use this to specify the desired compression vs time tradeoff.
        pub compression_level: CompressionLevel,
    }

    impl Default for Metadata {
        fn default() -> Self {
            Self {
                title: Default::default(),
                author: Default::default(),
                subject: Default::default(),
                keywords: Default::default(),
                creator: Default::default(),
                producer: format!("Skia/PDF m{}", MILESTONE),
                creation: Default::default(),
                modified: Default::default(),
                lang: Default::default(),
                raster_dpi: Default::default(),
                pdf_a: Default::default(),
                encoding_quality: Default::default(),
                structure_element_tree_root: None,
                compression_level: Default::default(),
            }
        }
    }

    pub type CompressionLevel = skia_bindings::SkPDF_Metadata_CompressionLevel;
    variant_name!(CompressionLevel::HighButSlow);

    /// Create a PDF-backed document.
    ///
    /// PDF pages are sized in point units. 1 pt == 1/72 inch == 127/360 mm.
    ///
    /// * `metadata` - a PDFmetadata object.  Any fields may be left empty.
    ///
    /// @returns `None` if there is an error, otherwise a newly created PDF-backed [`Document`].
    pub fn new_document<'a>(
        writer: &'a mut impl io::Write,
        metadata: Option<&Metadata>,
    ) -> Document<'a> {
        let mut md = InternalMetadata::default();
        if let Some(metadata) = metadata {
            let internal = md.native_mut();
            internal.fTitle.set_str(&metadata.title);
            internal.fAuthor.set_str(&metadata.author);
            internal.fSubject.set_str(&metadata.subject);
            internal.fKeywords.set_str(&metadata.keywords);
            internal.fCreator.set_str(&metadata.creator);
            internal.fProducer.set_str(&metadata.producer);
            if let Some(creation) = metadata.creation {
                internal.fCreation = creation.into_native();
            }
            if let Some(modified) = metadata.modified {
                internal.fModified = modified.into_native();
            }
            internal.fLang.set_str(&metadata.lang);
            if let Some(raster_dpi) = metadata.raster_dpi {
                internal.fRasterDPI = raster_dpi;
            }
            internal.fPDFA = metadata.pdf_a;
            if let Some(encoding_quality) = metadata.encoding_quality {
                internal.fEncodingQuality = encoding_quality
            }
            if let Some(structure_element_tree) = &metadata.structure_element_tree_root {
                internal.fStructureElementTreeRoot = structure_element_tree.0.as_ptr();
            }
            internal.fCompressionLevel = metadata.compression_level
        }

        // We enable harfbuzz font sub-setting in PDF documents if textlayout is enabled.
        #[cfg(all(feature = "textlayout", feature = "embed-icudtl"))]
        crate::icu::init();

        let mut stream = RustWStream::new(writer);
        let document = RCHandle::from_ptr(unsafe {
            sb::C_SkPDF_MakeDocument(stream.stream_mut(), md.native())
        })
        .unwrap();

        Document::new(stream, document)
    }

    //
    // Helper for constructing the internal metadata struct and setting associated strings.
    //

    type InternalMetadata = Handle<SkPDF_Metadata>;

    impl NativeDrop for SkPDF_Metadata {
        fn drop(&mut self) {
            unsafe { sb::C_SkPDF_Metadata_destruct(self) }
        }
    }

    impl Default for Handle<SkPDF_Metadata> {
        fn default() -> Self {
            Self::construct(|pdf_md| unsafe { sb::C_SkPDF_Metadata_Construct(pdf_md) })
        }
    }

    pub fn set_node_id(canvas: &Canvas, node_id: i32) {
        unsafe {
            sb::C_SkPDF_SetNodeId(canvas.native_mut(), node_id);
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::pdf::StructureElementNode;

    use super::pdf;

    #[test]
    fn create_attribute_list() {
        let mut _al = pdf::AttributeList::default();
        _al.append_float_array("Owner", "Name", &[1.0, 2.0, 3.0]);
    }

    #[test]
    fn structure_element_node_child_vector() {
        let mut root = StructureElementNode::new("root");
        root.append_child(StructureElementNode::new("nested"));
        root.append_child(StructureElementNode::new("nested2"));
        let v = root.child_vector();
        assert_eq!(v[0].type_string(), "nested");
        assert_eq!(v[1].type_string(), "nested2");
    }
}