rpdfium-doc 7676.6.2

Document-level features for rpdfium
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
//! Viewer preferences (ISO 32000-2 section 12.2).
//!
//! Parses the `/ViewerPreferences` dictionary from the document catalog
//! to control how a PDF viewer should display the document.

use std::collections::HashMap;

use rpdfium_core::{Name, PdfSource};
use rpdfium_parser::object::Object;
use rpdfium_parser::store::ObjectStore;

/// Reading direction for the document.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReadingDirection {
    /// Left to right (default).
    L2R,
    /// Right to left.
    R2L,
}

/// Duplex printing mode.
///
/// Corresponds to the `/Duplex` entry in the viewer preferences dictionary
/// and to `CPDF_ViewerPreferences::Duplex()` in PDFium.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DuplexMode {
    /// Simplex (single-sided) printing.
    #[default]
    Simplex,
    /// Duplex printing, flipping on the short edge.
    DuplexFlipShortEdge,
    /// Duplex printing, flipping on the long edge.
    DuplexFlipLongEdge,
}

/// Parsed viewer preferences from the `/ViewerPreferences` dictionary.
#[derive(Debug, Clone)]
pub struct ViewerPreferences {
    /// Whether to hide the toolbar when the document is active.
    pub hide_toolbar: bool,
    /// Whether to hide the menu bar when the document is active.
    pub hide_menubar: bool,
    /// Whether to hide UI elements in the document's window.
    pub hide_window_ui: bool,
    /// Whether to resize the document's window to fit the first page.
    pub fit_window: bool,
    /// Whether to position the document's window in the center of the screen.
    pub center_window: bool,
    /// Whether the window's title bar should display the document title.
    pub display_doc_title: bool,
    /// The predominant reading order for text.
    pub direction: ReadingDirection,
    /// Page scaling option (e.g., "None", "AppDefault").
    pub print_scaling: Option<String>,
    /// Number of copies to print.
    pub num_copies: Option<u32>,
    /// Duplex mode (e.g., "Simplex", "DuplexFlipShortEdge", "DuplexFlipLongEdge").
    pub duplex: Option<String>,
    /// Page ranges to print, as pairs `[start, end]` (0-based page indices).
    pub print_page_range: Option<Vec<i64>>,
}

impl Default for ViewerPreferences {
    fn default() -> Self {
        Self {
            hide_toolbar: false,
            hide_menubar: false,
            hide_window_ui: false,
            fit_window: false,
            center_window: false,
            display_doc_title: false,
            direction: ReadingDirection::L2R,
            print_scaling: None,
            num_copies: None,
            duplex: None,
            print_page_range: None,
        }
    }
}

impl ViewerPreferences {
    /// Parse viewer preferences from a dictionary.
    pub fn from_dict<S: PdfSource>(dict: &HashMap<Name, Object>, store: &ObjectStore<S>) -> Self {
        let get_bool = |name: &Name| -> bool {
            dict.get(name)
                .and_then(|o| store.deep_resolve(o).ok())
                .and_then(|o| o.as_bool())
                .unwrap_or(false)
        };

        let get_name_string = |name: &Name| -> Option<String> {
            dict.get(name)
                .and_then(|o| store.deep_resolve(o).ok())
                .and_then(|o| o.as_name().map(|n| n.as_str().into_owned()))
        };

        let get_string = |name: &Name| -> Option<String> {
            dict.get(name)
                .and_then(|o| store.deep_resolve(o).ok())
                .and_then(|o| {
                    if let Some(s) = o.as_string() {
                        Some(s.to_string_lossy())
                    } else {
                        o.as_name().map(|n| n.as_str().into_owned())
                    }
                })
        };

        let direction = match get_name_string(&Name::direction()).as_deref() {
            Some("R2L") => ReadingDirection::R2L,
            _ => ReadingDirection::L2R,
        };

        let num_copies = dict
            .get(&Name::num_copies())
            .and_then(|o| store.deep_resolve(o).ok())
            .and_then(|o| o.as_i64())
            .map(|n| n.max(1) as u32);

        // /PrintPageRange — array of page range pairs
        let print_page_range = dict
            .get(&Name::print_page_range())
            .and_then(|o| store.deep_resolve(o).ok())
            .and_then(|o| {
                o.as_array().map(|arr| {
                    arr.iter()
                        .filter_map(|item| item.as_i64())
                        .collect::<Vec<i64>>()
                })
            })
            .filter(|v| !v.is_empty());

        Self {
            hide_toolbar: get_bool(&Name::hide_toolbar()),
            hide_menubar: get_bool(&Name::hide_menubar()),
            hide_window_ui: get_bool(&Name::hide_window_ui()),
            fit_window: get_bool(&Name::fit_window()),
            center_window: get_bool(&Name::center_window()),
            display_doc_title: get_bool(&Name::display_doc_title()),
            direction,
            print_scaling: get_string(&Name::print_scaling()),
            num_copies,
            duplex: get_string(&Name::duplex()),
            print_page_range,
        }
    }

    /// Returns `true` if the reading direction is right-to-left.
    ///
    /// Corresponds to `CPDF_ViewerPreferences::IsDirectionR2L()` in PDFium.
    pub fn is_direction_r2l(&self) -> bool {
        self.direction == ReadingDirection::R2L
    }

    /// Returns `true` if print scaling is enabled (not suppressed).
    ///
    /// Returns `false` when `/PrintScaling` is `"None"` (the viewer should not
    /// scale the document for printing). This is the primary with the real logic.
    ///
    /// Corresponds to upstream `CPDF_ViewerPreferences::PrintScaling()`.
    pub fn print_scaling(&self) -> bool {
        self.print_scaling.as_deref() != Some("None")
    }

    /// Returns `true` if print scaling is suppressed (`/PrintScaling None`).
    ///
    /// This is a convenience inverse of [`print_scaling()`](Self::print_scaling).
    /// Corresponds to upstream `CPDF_ViewerPreferences::IsPrintScalingSuppressed()`.
    pub fn is_print_scaling_suppressed(&self) -> bool {
        !self.print_scaling()
    }

    /// Returns the number of copies to print.
    ///
    /// Returns `None` if the `/NumCopies` entry is absent.
    /// Corresponds to `CPDF_ViewerPreferences::NumCopies()` in PDFium.
    pub fn num_copies(&self) -> Option<u32> {
        self.num_copies
    }

    /// Deprecated: use [`num_copies()`](Self::num_copies) directly (its name already matches
    /// `CPDF_ViewerPreferences::NumCopies()`).
    #[deprecated(since = "0.1.0", note = "use num_copies() instead")]
    #[inline]
    pub fn get_num_copies(&self) -> Option<u32> {
        self.num_copies()
    }

    /// Returns the page ranges to print.
    ///
    /// Returns `None` if the `/PrintPageRange` entry is absent.
    /// The range is stored as pairs `[start, end]` (0-based page indices).
    ///
    /// Corresponds to `CPDF_ViewerPreferences::PrintPageRange()` in PDFium.
    pub fn print_page_range(&self) -> Option<&[i64]> {
        self.print_page_range.as_deref()
    }

    /// Returns the duplex printing mode.
    ///
    /// Parses the `/Duplex` entry from the viewer preferences dictionary.
    /// Returns `DuplexMode::Simplex` if the entry is absent or unrecognised.
    ///
    /// Corresponds to `CPDF_ViewerPreferences::Duplex()` in PDFium.
    pub fn duplex_mode(&self) -> DuplexMode {
        match self.duplex.as_deref() {
            Some("DuplexFlipShortEdge") => DuplexMode::DuplexFlipShortEdge,
            Some("DuplexFlipLongEdge") => DuplexMode::DuplexFlipLongEdge,
            _ => DuplexMode::Simplex,
        }
    }

    /// Upstream-aligned alias for [`duplex_mode()`](Self::duplex_mode).
    ///
    /// Corresponds to `CPDF_ViewerPreferences::Duplex()` in PDFium.
    #[inline]
    pub fn duplex(&self) -> DuplexMode {
        self.duplex_mode()
    }

    /// Returns the value of an arbitrary viewer preference entry by name.
    ///
    /// Looks up the given `key` in the viewer preferences dictionary and
    /// returns the value as a string if the entry is a PDF name or string
    /// object. Returns `None` if the key is absent or the value is not a
    /// name/string.
    ///
    /// Corresponds to `CPDF_ViewerPreferences::GenericName()` in PDFium.
    pub fn generic_name(&self, key: &str) -> Option<&str> {
        match key {
            "HideToolbar" => self.hide_toolbar.then_some("true"),
            "HideMenubar" => self.hide_menubar.then_some("true"),
            "HideWindowUI" => self.hide_window_ui.then_some("true"),
            "FitWindow" => self.fit_window.then_some("true"),
            "CenterWindow" => self.center_window.then_some("true"),
            "DisplayDocTitle" => self.display_doc_title.then_some("true"),
            "Direction" => match self.direction {
                ReadingDirection::R2L => Some("R2L"),
                ReadingDirection::L2R => Some("L2R"),
            },
            "PrintScaling" => self.print_scaling.as_deref(),
            "Duplex" => self.duplex.as_deref(),
            _ => None,
        }
    }
}

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

    fn build_store() -> ObjectStore<Vec<u8>> {
        let pdf = build_minimal_pdf();
        ObjectStore::open(pdf, rpdfium_core::ParsingMode::Lenient).unwrap()
    }

    fn build_minimal_pdf() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");
        let obj1_offset = pdf.len();
        pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
        let obj2_offset = pdf.len();
        pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [] /Count 0 >>\nendobj\n");
        let xref_offset = pdf.len();
        pdf.extend_from_slice(b"xref\n0 3\n");
        pdf.extend_from_slice(b"0000000000 65535 f \r\n");
        pdf.extend_from_slice(format!("{:010} 00000 n \r\n", obj1_offset).as_bytes());
        pdf.extend_from_slice(format!("{:010} 00000 n \r\n", obj2_offset).as_bytes());
        pdf.extend_from_slice(b"trailer\n<< /Size 3 /Root 1 0 R >>\n");
        pdf.extend_from_slice(format!("startxref\n{}\n%%EOF", xref_offset).as_bytes());
        pdf
    }

    #[test]
    fn test_default_preferences() {
        let prefs = ViewerPreferences::default();
        assert!(!prefs.hide_toolbar);
        assert!(!prefs.hide_menubar);
        assert!(!prefs.hide_window_ui);
        assert!(!prefs.fit_window);
        assert!(!prefs.center_window);
        assert!(!prefs.display_doc_title);
        assert_eq!(prefs.direction, ReadingDirection::L2R);
        assert!(prefs.print_scaling.is_none());
        assert!(prefs.num_copies.is_none());
        assert!(prefs.duplex.is_none());
        assert!(prefs.print_page_range.is_none());
    }

    #[test]
    fn test_parse_all_fields() {
        let store = build_store();
        let mut dict = HashMap::new();
        dict.insert(Name::hide_toolbar(), Object::Boolean(true));
        dict.insert(Name::hide_menubar(), Object::Boolean(true));
        dict.insert(Name::hide_window_ui(), Object::Boolean(true));
        dict.insert(Name::fit_window(), Object::Boolean(true));
        dict.insert(Name::center_window(), Object::Boolean(true));
        dict.insert(Name::display_doc_title(), Object::Boolean(true));
        dict.insert(Name::direction(), Object::Name(Name::from("R2L")));
        dict.insert(Name::print_scaling(), Object::Name(Name::from("None")));
        dict.insert(Name::num_copies(), Object::Integer(3));
        dict.insert(
            Name::duplex(),
            Object::Name(Name::from("DuplexFlipLongEdge")),
        );

        let prefs = ViewerPreferences::from_dict(&dict, &store);
        assert!(prefs.hide_toolbar);
        assert!(prefs.hide_menubar);
        assert!(prefs.hide_window_ui);
        assert!(prefs.fit_window);
        assert!(prefs.center_window);
        assert!(prefs.display_doc_title);
        assert_eq!(prefs.direction, ReadingDirection::R2L);
        assert_eq!(prefs.print_scaling.as_deref(), Some("None"));
        assert_eq!(prefs.num_copies, Some(3));
        assert_eq!(prefs.duplex.as_deref(), Some("DuplexFlipLongEdge"));
    }

    #[test]
    fn test_parse_empty_dict() {
        let store = build_store();
        let dict = HashMap::new();
        let prefs = ViewerPreferences::from_dict(&dict, &store);
        assert!(!prefs.hide_toolbar);
        assert_eq!(prefs.direction, ReadingDirection::L2R);
        assert!(prefs.print_scaling.is_none());
    }

    #[test]
    fn test_print_page_range_parsed() {
        let store = build_store();
        let mut dict = HashMap::new();
        dict.insert(
            Name::print_page_range(),
            Object::Array(vec![
                Object::Integer(0),
                Object::Integer(3),
                Object::Integer(5),
                Object::Integer(7),
            ]),
        );
        let prefs = ViewerPreferences::from_dict(&dict, &store);
        let range = prefs.print_page_range.unwrap();
        assert_eq!(range, vec![0, 3, 5, 7]);
    }

    #[test]
    fn test_print_page_range_empty_is_none() {
        let store = build_store();
        let mut dict = HashMap::new();
        dict.insert(Name::print_page_range(), Object::Array(vec![]));
        let prefs = ViewerPreferences::from_dict(&dict, &store);
        assert!(prefs.print_page_range.is_none());
    }

    #[test]
    fn test_direction_default_l2r() {
        let store = build_store();
        let mut dict = HashMap::new();
        dict.insert(Name::direction(), Object::Name(Name::from("L2R")));
        let prefs = ViewerPreferences::from_dict(&dict, &store);
        assert_eq!(prefs.direction, ReadingDirection::L2R);
    }

    #[test]
    fn test_direction_r2l() {
        let store = build_store();
        let mut dict = HashMap::new();
        dict.insert(Name::direction(), Object::Name(Name::from("R2L")));
        let prefs = ViewerPreferences::from_dict(&dict, &store);
        assert_eq!(prefs.direction, ReadingDirection::R2L);
    }

    #[test]
    fn test_is_print_scaling_suppressed_none_value() {
        let store = build_store();
        let mut dict = HashMap::new();
        dict.insert(Name::print_scaling(), Object::Name(Name::from("None")));
        let prefs = ViewerPreferences::from_dict(&dict, &store);
        assert!(prefs.is_print_scaling_suppressed());
    }

    #[test]
    fn test_is_print_scaling_suppressed_app_default() {
        let store = build_store();
        let mut dict = HashMap::new();
        dict.insert(
            Name::print_scaling(),
            Object::Name(Name::from("AppDefault")),
        );
        let prefs = ViewerPreferences::from_dict(&dict, &store);
        assert!(!prefs.is_print_scaling_suppressed());
    }

    #[test]
    fn test_is_print_scaling_suppressed_absent() {
        let store = build_store();
        let prefs = ViewerPreferences::from_dict(&HashMap::new(), &store);
        assert!(!prefs.is_print_scaling_suppressed());
    }

    #[test]
    fn test_generic_name_direction() {
        let store = build_store();
        let mut dict = HashMap::new();
        dict.insert(Name::direction(), Object::Name(Name::from("R2L")));
        let prefs = ViewerPreferences::from_dict(&dict, &store);
        assert_eq!(prefs.generic_name("Direction"), Some("R2L"));
    }

    #[test]
    fn test_generic_name_print_scaling() {
        let store = build_store();
        let mut dict = HashMap::new();
        dict.insert(Name::print_scaling(), Object::Name(Name::from("None")));
        let prefs = ViewerPreferences::from_dict(&dict, &store);
        assert_eq!(prefs.generic_name("PrintScaling"), Some("None"));
    }

    #[test]
    fn test_generic_name_unknown_key_is_none() {
        let prefs = ViewerPreferences::default();
        assert_eq!(prefs.generic_name("SomeUnknownKey"), None);
    }

    #[test]
    fn test_generic_name_duplex() {
        let store = build_store();
        let mut dict = HashMap::new();
        dict.insert(
            Name::duplex(),
            Object::Name(Name::from("DuplexFlipShortEdge")),
        );
        let prefs = ViewerPreferences::from_dict(&dict, &store);
        assert_eq!(prefs.generic_name("Duplex"), Some("DuplexFlipShortEdge"));
    }

    #[test]
    fn test_duplex_mode_simplex_by_default() {
        let prefs = ViewerPreferences::default();
        assert_eq!(prefs.duplex_mode(), DuplexMode::Simplex);
    }

    #[test]
    fn test_duplex_mode_flip_short_edge() {
        let store = build_store();
        let mut dict = HashMap::new();
        dict.insert(
            Name::duplex(),
            Object::Name(Name::from("DuplexFlipShortEdge")),
        );
        let prefs = ViewerPreferences::from_dict(&dict, &store);
        assert_eq!(prefs.duplex_mode(), DuplexMode::DuplexFlipShortEdge);
    }

    #[test]
    fn test_duplex_mode_flip_long_edge() {
        let store = build_store();
        let mut dict = HashMap::new();
        dict.insert(
            Name::duplex(),
            Object::Name(Name::from("DuplexFlipLongEdge")),
        );
        let prefs = ViewerPreferences::from_dict(&dict, &store);
        assert_eq!(prefs.duplex_mode(), DuplexMode::DuplexFlipLongEdge);
    }

    #[test]
    fn test_duplex_mode_unknown_is_simplex() {
        let store = build_store();
        let mut dict = HashMap::new();
        dict.insert(Name::duplex(), Object::Name(Name::from("Unknown")));
        let prefs = ViewerPreferences::from_dict(&dict, &store);
        assert_eq!(prefs.duplex_mode(), DuplexMode::Simplex);
    }
}