Skip to main content

easyofd_core/doc/bookmark/
bookmark.rs

1//! 单个书签。
2
3/// 对应 Java: org.ofdrw.core.pageDescription.Bookmark
4///
5/// 单个书签定义,包含书签名称和目标页码。
6#[derive(Debug, Clone)]
7pub struct Bookmark {
8    /// 书签名称。
9    pub name: String,
10    /// 目标页码(1-based)。
11    pub page: u32,
12    /// Y 偏移量(mm),可选。
13    pub y_offset: Option<f64>,
14}
15
16impl Bookmark {
17    /// 创建新的书签。
18    #[must_use]
19    pub fn new(name: impl Into<String>, page: u32) -> Self {
20        Self {
21            name: name.into(),
22            page,
23            y_offset: None,
24        }
25    }
26
27    /// 设置 Y 偏移量。
28    #[must_use]
29    pub fn with_y_offset(mut self, y_offset: f64) -> Self {
30        self.y_offset = Some(y_offset);
31        self
32    }
33
34    /// 序列化为 XML 字符串。
35    #[must_use]
36    pub fn to_xml_string(&self) -> String {
37        let mut attrs = format!("Name=\"{}\" Page=\"{}\"", self.name, self.page);
38        if let Some(y) = self.y_offset {
39            use std::fmt::Write;
40            let _ = write!(attrs, " YOffset=\"{y}\"");
41        }
42        format!("<Bookmark {attrs}/>")
43    }
44}
45
46#[cfg(test)]
47mod tests {
48    use super::*;
49
50    #[test]
51    fn test_bookmark_new() {
52        let b = Bookmark::new("Introduction", 1);
53        assert_eq!(b.name, "Introduction");
54        assert_eq!(b.page, 1);
55        assert!(b.y_offset.is_none());
56    }
57
58    #[test]
59    fn test_bookmark_with_y_offset_and_xml() {
60        let b = Bookmark::new("Chapter 1", 3).with_y_offset(120.5);
61        let xml = b.to_xml_string();
62        assert!(xml.contains("Name=\"Chapter 1\""));
63        assert!(xml.contains("Page=\"3\""));
64        assert!(xml.contains("YOffset=\"120.5\""));
65    }
66}