pdf-manip 1.2.0

PDF manipulation: pages, encryption, watermarks, optimization, bookmarks
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
//! PDF bookmarks (outlines) — read, create, modify, import/export.
//!
//! Bookmarks in PDF are stored as an outline tree using linked-list
//! dictionaries with /First, /Last, /Next, /Prev, /Parent pointers.

// Copyright (c) 2026 Innovation Trigger B.V.
//
// PDFluent is available under two licences, at your option: the GNU AGPLv3, or
// the PDFluent Commercial Licence. See the LICENSE file in this repository --
// that file travels with the copy you received, which a URL does not.

use crate::error::{ManipError, Result};
use lopdf::{dictionary, Document, Object, ObjectId};

/// A bookmark action (where clicking the bookmark navigates to).
#[derive(Debug, Clone)]
pub enum BookmarkAction {
    /// Navigate to a page in this document.
    /// Page number is 1-based.
    GoTo {
        /// 1-based target page number within this document.
        page: u32,
        /// Fit type: "Fit", "FitH", "FitV", "XYZ", etc.
        fit: FitType,
    },
    /// Navigate to a page in an external document.
    GoToR {
        /// Path or URL of the external PDF document.
        file: String,
        /// 1-based target page number within the external document.
        page: u32,
    },
    /// Open a URI.
    Uri(String),
    /// Named action (e.g., "NextPage", "PrevPage").
    Named(String),
}

/// Destination fit types.
#[derive(Debug, Clone, Default)]
pub enum FitType {
    /// Fit the entire page in the window.
    #[default]
    Fit,
    /// Fit the width of the page.
    FitH(f32),
    /// Fit the height of the page.
    FitV(f32),
    /// Display at specific position and zoom.
    Xyz {
        /// Horizontal scroll position in PDF user-space points.
        /// `None` preserves the current viewer setting.
        x: Option<f32>,
        /// Vertical scroll position in PDF user-space points.
        /// `None` preserves the current viewer setting.
        y: Option<f32>,
        /// Zoom factor (1.0 == 100%). `None` preserves current zoom.
        zoom: Option<f32>,
    },
}

/// Text style flags for bookmarks.
#[derive(Debug, Clone, Copy, Default)]
pub struct BookmarkStyle {
    /// Italic text.
    pub italic: bool,
    /// Bold text.
    pub bold: bool,
    /// Text color (RGB, 0.0–1.0). None = default (black).
    pub color: Option<(f32, f32, f32)>,
}

/// A bookmark node in the outline tree.
#[derive(Debug, Clone)]
pub struct Bookmark {
    /// Display title.
    pub title: String,
    /// Action when clicked.
    pub action: BookmarkAction,
    /// Text style.
    pub style: BookmarkStyle,
    /// Whether the bookmark is initially open (showing children).
    pub open: bool,
    /// Child bookmarks.
    pub children: Vec<Bookmark>,
}

impl Bookmark {
    /// Create a simple bookmark to a page.
    pub fn new(title: impl Into<String>, page: u32) -> Self {
        Self {
            title: title.into(),
            action: BookmarkAction::GoTo {
                page,
                fit: FitType::Fit,
            },
            style: BookmarkStyle::default(),
            open: false,
            children: Vec::new(),
        }
    }

    /// Create a bookmark with children.
    pub fn with_children(title: impl Into<String>, page: u32, children: Vec<Bookmark>) -> Self {
        Self {
            title: title.into(),
            action: BookmarkAction::GoTo {
                page,
                fit: FitType::Fit,
            },
            style: BookmarkStyle::default(),
            open: true,
            children,
        }
    }
}

/// One entry of the document outline, as read by [`read_outline`] and
/// written by [`write_outline`].
///
/// The same tree as [`Bookmark`], except that the action is optional: an
/// outline item may carry no destination at all (neither `/Dest` nor `/A`),
/// for instance after its target page was deleted. [`Bookmark`] cannot say
/// that, so [`read_bookmarks`] substitutes a page-1 `GoTo` for it; this type
/// keeps the difference.
///
/// Build one with [`OutlineEntry::new`]; the fields stay public for reading
/// and changing.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct OutlineEntry {
    /// Display title.
    pub title: String,
    /// Action when clicked; `None` when the entry has no destination.
    pub action: Option<BookmarkAction>,
    /// Text style.
    pub style: BookmarkStyle,
    /// Whether the entry is initially open (showing children).
    pub open: bool,
    /// Child entries.
    pub children: Vec<OutlineEntry>,
}

impl OutlineEntry {
    /// Create a closed entry without children, in the default style.
    ///
    /// `action` is `None` for an entry without a destination.
    pub fn new(title: impl Into<String>, action: Option<BookmarkAction>) -> Self {
        Self {
            title: title.into(),
            action,
            style: BookmarkStyle::default(),
            open: false,
            children: Vec::new(),
        }
    }

    /// Convert to a [`Bookmark`] tree.
    ///
    /// An entry without a destination becomes a `GoTo` to page 1 with
    /// [`FitType::Fit`], the value [`read_bookmarks`] has always returned
    /// for such an entry.
    pub fn to_bookmark(&self) -> Bookmark {
        Bookmark {
            title: self.title.clone(),
            action: self.action.clone().unwrap_or(BookmarkAction::GoTo {
                page: 1,
                fit: FitType::Fit,
            }),
            style: self.style,
            open: self.open,
            children: self
                .children
                .iter()
                .map(OutlineEntry::to_bookmark)
                .collect(),
        }
    }
}

impl From<&Bookmark> for OutlineEntry {
    /// Every [`Bookmark`] has a destination, so the action is always `Some`.
    fn from(bm: &Bookmark) -> Self {
        Self {
            title: bm.title.clone(),
            action: Some(bm.action.clone()),
            style: bm.style,
            open: bm.open,
            children: bm.children.iter().map(OutlineEntry::from).collect(),
        }
    }
}

/// Read all bookmarks from a document.
///
/// An entry without a destination reads as a `GoTo` to page 1; use
/// [`read_outline`] to tell those apart.
pub fn read_bookmarks(doc: &Document) -> Result<Vec<Bookmark>> {
    Ok(read_outline(doc)?
        .iter()
        .map(OutlineEntry::to_bookmark)
        .collect())
}

/// Read the document outline, keeping entries without a destination.
///
/// Returns an empty `Vec` for a document without an outline. An entry's
/// `action` is `None` when it has neither `/Dest` nor a readable `/A`
/// action dictionary.
pub fn read_outline(doc: &Document) -> Result<Vec<OutlineEntry>> {
    let catalog_ref = doc
        .trailer
        .get(b"Root")
        .map_err(|_| ManipError::Other("no Root in trailer".into()))?
        .as_reference()
        .map_err(|_| ManipError::Other("Root is not a reference".into()))?;

    let catalog = doc
        .get_dictionary(catalog_ref)
        .map_err(|_| ManipError::Other("cannot read catalog".into()))?;

    let outlines_ref = match catalog.get(b"Outlines") {
        Ok(obj) => match obj.as_reference() {
            Ok(r) => r,
            Err(_) => return Ok(Vec::new()),
        },
        Err(_) => return Ok(Vec::new()),
    };

    let outlines = doc
        .get_dictionary(outlines_ref)
        .map_err(|_| ManipError::Other("cannot read Outlines".into()))?;

    let first_ref = match outlines.get(b"First") {
        Ok(obj) => obj
            .as_reference()
            .map_err(|_| ManipError::Other("First is not a reference".into()))?,
        Err(_) => return Ok(Vec::new()),
    };

    let pages = doc.get_pages();
    let page_id_to_num: std::collections::HashMap<ObjectId, u32> =
        pages.iter().map(|(&num, &id)| (id, num)).collect();

    read_siblings(doc, first_ref, &page_id_to_num)
}

/// Read a linked list of sibling bookmark nodes.
fn read_siblings(
    doc: &Document,
    first_ref: ObjectId,
    page_map: &std::collections::HashMap<ObjectId, u32>,
) -> Result<Vec<OutlineEntry>> {
    let mut bookmarks = Vec::new();
    let mut current_ref = Some(first_ref);
    let mut visited = std::collections::HashSet::new();

    while let Some(ref_id) = current_ref {
        // Guard against circular references.
        if !visited.insert(ref_id) {
            break;
        }

        let dict = match doc.get_dictionary(ref_id) {
            Ok(d) => d,
            Err(_) => break,
        };

        let title = dict
            .get(b"Title")
            .ok()
            .and_then(|t| match t {
                Object::String(bytes, _) => String::from_utf8(bytes.clone()).ok(),
                _ => None,
            })
            .unwrap_or_default();

        let action = parse_bookmark_action(doc, dict, page_map);
        let style = parse_bookmark_style(dict);

        // Read children.
        let children = if let Ok(child_ref) = dict.get(b"First").and_then(|o| {
            o.as_reference()
                .map_err(|_| lopdf::Error::DictKey("First".into()))
        }) {
            read_siblings(doc, child_ref, page_map)?
        } else {
            Vec::new()
        };

        // Check if open (Count > 0 means open).
        let open = dict
            .get(b"Count")
            .ok()
            .and_then(|o| o.as_i64().ok())
            .map(|c| c > 0)
            .unwrap_or(false);

        bookmarks.push(OutlineEntry {
            title,
            action,
            style,
            open,
            children,
        });

        // Move to next sibling.
        current_ref = dict.get(b"Next").ok().and_then(|o| o.as_reference().ok());
    }

    Ok(bookmarks)
}

/// Parse a bookmark's destination/action; `None` when it has none.
fn parse_bookmark_action(
    doc: &Document,
    dict: &lopdf::Dictionary,
    page_map: &std::collections::HashMap<ObjectId, u32>,
) -> Option<BookmarkAction> {
    // Check for /Dest (direct destination).
    let has_dest = dict.get(b"Dest").is_ok();
    if has_dest {
        if let Ok(dest) = dict.get(b"Dest") {
            if let Some(action) = parse_dest(dest, page_map) {
                return Some(action);
            }
        }
    }

    // Check for /A (action dictionary).
    if let Ok(action_obj) = dict.get(b"A") {
        if let Ok(action_ref) = action_obj.as_reference() {
            if let Ok(action_dict) = doc.get_dictionary(action_ref) {
                return Some(parse_action_dict(action_dict, page_map));
            }
        }
        if let Object::Dictionary(ref action_dict) = action_obj {
            return Some(parse_action_dict(action_dict, page_map));
        }
    }

    if has_dest {
        // A destination key is present but not an explicit array (a name or
        // string): named-destination resolution owns these; until then keep
        // the legacy page-1 fallback.
        return Some(BookmarkAction::GoTo {
            page: 1,
            fit: FitType::Fit,
        });
    }

    // Neither /Dest nor /A: the entry has no destination.
    None
}

fn parse_dest(
    dest: &Object,
    page_map: &std::collections::HashMap<ObjectId, u32>,
) -> Option<BookmarkAction> {
    if let Object::Array(arr) = dest {
        if let Some(page_ref) = arr.first().and_then(|o| o.as_reference().ok()) {
            let page = page_map.get(&page_ref).copied().unwrap_or(1);
            let fit = parse_fit_from_array(arr);
            return Some(BookmarkAction::GoTo { page, fit });
        }
    }
    None
}

fn parse_action_dict(
    dict: &lopdf::Dictionary,
    page_map: &std::collections::HashMap<ObjectId, u32>,
) -> BookmarkAction {
    let s = dict
        .get(b"S")
        .ok()
        .and_then(|o| {
            if let Object::Name(n) = o {
                Some(n.clone())
            } else {
                None
            }
        })
        .unwrap_or_default();

    match s.as_slice() {
        b"URI" => {
            let uri = dict
                .get(b"URI")
                .ok()
                .and_then(|o| match o {
                    Object::String(bytes, _) => String::from_utf8(bytes.clone()).ok(),
                    _ => None,
                })
                .unwrap_or_default();
            BookmarkAction::Uri(uri)
        }
        b"GoToR" => {
            let file = dict
                .get(b"F")
                .ok()
                .and_then(|o| match o {
                    Object::String(bytes, _) => String::from_utf8(bytes.clone()).ok(),
                    _ => None,
                })
                .unwrap_or_default();
            BookmarkAction::GoToR { file, page: 1 }
        }
        b"Named" => {
            let name = dict
                .get(b"N")
                .ok()
                .and_then(|o| {
                    if let Object::Name(n) = o {
                        String::from_utf8(n.clone()).ok()
                    } else {
                        None
                    }
                })
                .unwrap_or_default();
            BookmarkAction::Named(name)
        }
        _ => {
            // Try GoTo with /D destination.
            if let Ok(dest) = dict.get(b"D") {
                if let Some(action) = parse_dest(dest, page_map) {
                    return action;
                }
            }
            BookmarkAction::GoTo {
                page: 1,
                fit: FitType::Fit,
            }
        }
    }
}

fn parse_fit_from_array(arr: &[Object]) -> FitType {
    let fit_name = arr.get(1).and_then(|o| {
        if let Object::Name(n) = o {
            Some(n.as_slice())
        } else {
            None
        }
    });

    match fit_name {
        Some(b"Fit") | Some(b"FitB") => FitType::Fit,
        Some(b"FitH") | Some(b"FitBH") => {
            let top = arr.get(2).and_then(obj_to_f32).unwrap_or(0.0);
            FitType::FitH(top)
        }
        Some(b"FitV") | Some(b"FitBV") => {
            let left = arr.get(2).and_then(obj_to_f32).unwrap_or(0.0);
            FitType::FitV(left)
        }
        Some(b"XYZ") => FitType::Xyz {
            x: arr.get(2).and_then(obj_to_f32),
            y: arr.get(3).and_then(obj_to_f32),
            zoom: arr.get(4).and_then(obj_to_f32),
        },
        _ => FitType::Fit,
    }
}

fn parse_bookmark_style(dict: &lopdf::Dictionary) -> BookmarkStyle {
    let flags = dict
        .get(b"F")
        .ok()
        .and_then(|o| o.as_i64().ok())
        .unwrap_or(0);

    let color = dict.get(b"C").ok().and_then(|o| {
        if let Object::Array(arr) = o {
            if arr.len() >= 3 {
                let r = obj_to_f32(&arr[0])?;
                let g = obj_to_f32(&arr[1])?;
                let b = obj_to_f32(&arr[2])?;
                return Some((r, g, b));
            }
        }
        None
    });

    BookmarkStyle {
        italic: flags & 1 != 0,
        bold: flags & 2 != 0,
        color,
    }
}

fn obj_to_f32(obj: &Object) -> Option<f32> {
    match obj {
        Object::Integer(n) => Some(*n as f32),
        Object::Real(n) => Some(*n),
        _ => None,
    }
}

/// Write bookmarks into a document, replacing any existing outlines.
pub fn write_bookmarks(doc: &mut Document, bookmarks: &[Bookmark]) -> Result<()> {
    let entries: Vec<OutlineEntry> = bookmarks.iter().map(OutlineEntry::from).collect();
    write_outline(doc, &entries)
}

/// Write an outline into a document, replacing any existing outlines.
///
/// An empty slice removes the outline. An entry whose `action` is `None` is
/// written without `/Dest` and without `/A`.
pub fn write_outline(doc: &mut Document, bookmarks: &[OutlineEntry]) -> Result<()> {
    if bookmarks.is_empty() {
        // Remove outlines.
        let catalog_ref = doc
            .trailer
            .get(b"Root")
            .map_err(|_| ManipError::Other("no Root".into()))?
            .as_reference()
            .map_err(|_| ManipError::Other("Root not a ref".into()))?;
        if let Some(Object::Dictionary(ref mut cat)) = doc.objects.get_mut(&catalog_ref) {
            cat.remove(b"Outlines");
        }
        return Ok(());
    }

    let pages = doc.get_pages();
    let outlines_id = doc.new_object_id();
    let total_count = count_bookmarks(bookmarks);

    // Build the outline tree.
    let (first_id, last_id) = write_bookmark_siblings(doc, bookmarks, outlines_id, &pages)?;

    let outlines = dictionary! {
        "Type" => "Outlines",
        "First" => Object::Reference(first_id),
        "Last" => Object::Reference(last_id),
        "Count" => Object::Integer(total_count as i64),
    };
    doc.objects
        .insert(outlines_id, Object::Dictionary(outlines));

    // Set in catalog.
    let catalog_ref = doc
        .trailer
        .get(b"Root")
        .map_err(|_| ManipError::Other("no Root".into()))?
        .as_reference()
        .map_err(|_| ManipError::Other("Root not a ref".into()))?;
    if let Some(Object::Dictionary(ref mut cat)) = doc.objects.get_mut(&catalog_ref) {
        cat.set("Outlines", Object::Reference(outlines_id));
    }

    Ok(())
}

/// Write a list of sibling bookmarks and return (first_id, last_id).
fn write_bookmark_siblings(
    doc: &mut Document,
    bookmarks: &[OutlineEntry],
    parent_id: ObjectId,
    pages: &std::collections::BTreeMap<u32, ObjectId>,
) -> Result<(ObjectId, ObjectId)> {
    let mut ids: Vec<ObjectId> = Vec::new();

    for bm in bookmarks {
        let bm_id = doc.new_object_id();
        ids.push(bm_id);

        let mut dict = lopdf::Dictionary::new();
        dict.set(
            "Title",
            Object::String(bm.title.as_bytes().to_vec(), lopdf::StringFormat::Literal),
        );
        dict.set("Parent", Object::Reference(parent_id));

        // Set destination.
        match &bm.action {
            None => {
                // No destination keys are written.
            }
            Some(BookmarkAction::GoTo { page, fit }) => {
                if let Some(&page_id) = pages.get(page) {
                    let dest = build_dest_array(page_id, fit);
                    dict.set("Dest", Object::Array(dest));
                }
            }
            Some(BookmarkAction::Uri(uri)) => {
                let action = dictionary! {
                    "S" => "URI",
                    "URI" => Object::String(uri.as_bytes().to_vec(), lopdf::StringFormat::Literal),
                };
                dict.set("A", Object::Dictionary(action));
            }
            Some(BookmarkAction::GoToR { file, page }) => {
                let action = dictionary! {
                    "S" => "GoToR",
                    "F" => Object::String(file.as_bytes().to_vec(), lopdf::StringFormat::Literal),
                    "D" => Object::Array(vec![Object::Integer((*page as i64) - 1), Object::Name(b"Fit".to_vec())]),
                };
                dict.set("A", Object::Dictionary(action));
            }
            Some(BookmarkAction::Named(name)) => {
                let action = dictionary! {
                    "S" => "Named",
                    "N" => Object::Name(name.as_bytes().to_vec()),
                };
                dict.set("A", Object::Dictionary(action));
            }
        }

        // Style.
        let flags = (if bm.style.italic { 1 } else { 0 }) | (if bm.style.bold { 2 } else { 0 });
        if flags != 0 {
            dict.set("F", Object::Integer(flags));
        }
        if let Some((r, g, b)) = bm.style.color {
            dict.set(
                "C",
                Object::Array(vec![Object::Real(r), Object::Real(g), Object::Real(b)]),
            );
        }

        // Children.
        if !bm.children.is_empty() {
            let (first_child, last_child) =
                write_bookmark_siblings(doc, &bm.children, bm_id, pages)?;
            dict.set("First", Object::Reference(first_child));
            dict.set("Last", Object::Reference(last_child));
            let child_count = count_bookmarks(&bm.children) as i64;
            dict.set(
                "Count",
                Object::Integer(if bm.open { child_count } else { -child_count }),
            );
        }

        doc.objects.insert(bm_id, Object::Dictionary(dict));
    }

    // Set Next/Prev pointers.
    for i in 0..ids.len() {
        if i > 0 {
            if let Some(Object::Dictionary(ref mut dict)) = doc.objects.get_mut(&ids[i]) {
                dict.set("Prev", Object::Reference(ids[i - 1]));
            }
        }
        if i + 1 < ids.len() {
            if let Some(Object::Dictionary(ref mut dict)) = doc.objects.get_mut(&ids[i]) {
                dict.set("Next", Object::Reference(ids[i + 1]));
            }
        }
    }

    Ok((
        ids[0],
        // SAFETY: ids mirrors bookmarks (one entry per bm), and this function is
        // only called when bookmarks is non-empty (guarded by caller).
        *ids.last()
            .expect("ids mirrors bookmarks which is non-empty"),
    ))
}

fn build_dest_array(page_id: ObjectId, fit: &FitType) -> Vec<Object> {
    let mut arr = vec![Object::Reference(page_id)];
    match fit {
        FitType::Fit => {
            arr.push(Object::Name(b"Fit".to_vec()));
        }
        FitType::FitH(top) => {
            arr.push(Object::Name(b"FitH".to_vec()));
            arr.push(Object::Real(*top));
        }
        FitType::FitV(left) => {
            arr.push(Object::Name(b"FitV".to_vec()));
            arr.push(Object::Real(*left));
        }
        FitType::Xyz { x, y, zoom } => {
            arr.push(Object::Name(b"XYZ".to_vec()));
            arr.push(x.map(Object::Real).unwrap_or(Object::Null));
            arr.push(y.map(Object::Real).unwrap_or(Object::Null));
            arr.push(zoom.map(Object::Real).unwrap_or(Object::Null));
        }
    }
    arr
}

fn count_bookmarks(bookmarks: &[OutlineEntry]) -> usize {
    let mut count = bookmarks.len();
    for bm in bookmarks {
        count += count_bookmarks(&bm.children);
    }
    count
}

/// Export bookmarks to JSON.
#[cfg(feature = "serde")]
pub fn export_bookmarks_json(bookmarks: &[Bookmark]) -> Result<String> {
    let json_bookmarks: Vec<JsonBookmark> = bookmarks.iter().map(to_json_bookmark).collect();
    serde_json::to_string_pretty(&json_bookmarks)
        .map_err(|e| ManipError::Other(format!("JSON serialization error: {e}")))
}

/// Import bookmarks from JSON.
#[cfg(feature = "serde")]
pub fn import_bookmarks_json(json: &str) -> Result<Vec<Bookmark>> {
    let json_bookmarks: Vec<JsonBookmark> = serde_json::from_str(json)
        .map_err(|e| ManipError::Other(format!("JSON parse error: {e}")))?;
    Ok(json_bookmarks.iter().map(from_json_bookmark).collect())
}

#[cfg(feature = "serde")]
#[derive(serde::Serialize, serde::Deserialize)]
struct JsonBookmark {
    title: String,
    page: Option<u32>,
    uri: Option<String>,
    open: bool,
    bold: bool,
    italic: bool,
    children: Vec<JsonBookmark>,
}

#[cfg(feature = "serde")]
fn to_json_bookmark(bm: &Bookmark) -> JsonBookmark {
    let (page, uri) = match &bm.action {
        BookmarkAction::GoTo { page, .. } => (Some(*page), None),
        BookmarkAction::Uri(uri) => (None, Some(uri.clone())),
        _ => (None, None),
    };
    JsonBookmark {
        title: bm.title.clone(),
        page,
        uri,
        open: bm.open,
        bold: bm.style.bold,
        italic: bm.style.italic,
        children: bm.children.iter().map(to_json_bookmark).collect(),
    }
}

#[cfg(feature = "serde")]
fn from_json_bookmark(jb: &JsonBookmark) -> Bookmark {
    let action = if let Some(uri) = &jb.uri {
        BookmarkAction::Uri(uri.clone())
    } else {
        BookmarkAction::GoTo {
            page: jb.page.unwrap_or(1),
            fit: FitType::Fit,
        }
    };
    Bookmark {
        title: jb.title.clone(),
        action,
        style: BookmarkStyle {
            bold: jb.bold,
            italic: jb.italic,
            color: None,
        },
        open: jb.open,
        children: jb.children.iter().map(from_json_bookmark).collect(),
    }
}

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

    fn make_test_doc(num_pages: usize) -> Document {
        let mut doc = Document::with_version("1.7");
        let pages_id = doc.new_object_id();
        let mut kids = Vec::new();

        for _ in 0..num_pages {
            let page = dictionary! {
                "Type" => "Page",
                "Parent" => Object::Reference(pages_id),
                "MediaBox" => Object::Array(vec![
                    Object::Integer(0), Object::Integer(0),
                    Object::Integer(612), Object::Integer(792),
                ]),
            };
            let page_id = doc.add_object(Object::Dictionary(page));
            kids.push(Object::Reference(page_id));
        }

        let pages = dictionary! {
            "Type" => "Pages",
            "Count" => Object::Integer(num_pages as i64),
            "Kids" => Object::Array(kids),
        };
        doc.objects.insert(pages_id, Object::Dictionary(pages));

        let catalog = dictionary! {
            "Type" => "Catalog",
            "Pages" => Object::Reference(pages_id),
        };
        let catalog_id = doc.add_object(Object::Dictionary(catalog));
        doc.trailer.set("Root", Object::Reference(catalog_id));

        doc
    }

    #[test]
    fn test_read_empty_bookmarks() {
        let doc = make_test_doc(3);
        let bookmarks = read_bookmarks(&doc).unwrap();
        assert!(bookmarks.is_empty());
    }

    #[test]
    fn test_count_bookmarks() {
        let bookmarks = [
            Bookmark::new("A", 1),
            Bookmark::with_children(
                "B",
                2,
                vec![Bookmark::new("B.1", 3), Bookmark::new("B.2", 4)],
            ),
        ];
        let entries: Vec<OutlineEntry> = bookmarks.iter().map(OutlineEntry::from).collect();
        assert_eq!(count_bookmarks(&entries), 4);
    }

    #[test]
    fn test_build_dest_array_fit() {
        let page_id = (1, 0);
        let arr = build_dest_array(page_id, &FitType::Fit);
        assert_eq!(arr.len(), 2);
    }

    #[test]
    fn test_build_dest_array_xyz() {
        let page_id = (1, 0);
        let arr = build_dest_array(
            page_id,
            &FitType::Xyz {
                x: Some(100.0),
                y: Some(200.0),
                zoom: Some(1.5),
            },
        );
        assert_eq!(arr.len(), 5);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_json_roundtrip() {
        let bookmarks = vec![
            Bookmark::new("Chapter 1", 1),
            Bookmark::with_children("Chapter 2", 5, vec![Bookmark::new("Section 2.1", 6)]),
        ];
        let json = export_bookmarks_json(&bookmarks).unwrap();
        let restored = import_bookmarks_json(&json).unwrap();
        assert_eq!(restored.len(), 2);
        assert_eq!(restored[0].title, "Chapter 1");
        assert_eq!(restored[1].children.len(), 1);
    }
}