docx_rs/documents/elements/
page_size.rs

1use crate::documents::BuildXML;
2use crate::types::*;
3use crate::xml_builder::*;
4use std::io::Write;
5
6use serde::Serialize;
7
8#[derive(Debug, Clone, PartialEq, Serialize)]
9#[serde(rename_all = "camelCase")]
10pub struct PageSize {
11    w: u32,
12    h: u32,
13    orient: Option<PageOrientationType>,
14}
15
16// These values were based on microsoft office word2019 windows edition.
17// <w:pgSz w:w="11906" w:h="16838"/>
18impl Default for PageSize {
19    fn default() -> PageSize {
20        PageSize {
21            w: 11906,
22            h: 16838,
23            orient: None,
24        }
25    }
26}
27
28impl PageSize {
29    pub fn new() -> PageSize {
30        Default::default()
31    }
32
33    pub fn size(self, w: u32, h: u32) -> PageSize {
34        PageSize {
35            w,
36            h,
37            orient: self.orient,
38        }
39    }
40
41    pub fn width(mut self, w: u32) -> PageSize {
42        self.w = w;
43        self
44    }
45
46    pub fn height(mut self, h: u32) -> PageSize {
47        self.h = h;
48        self
49    }
50
51    pub fn orient(mut self, o: PageOrientationType) -> PageSize {
52        self.orient = Some(o);
53        self
54    }
55}
56
57impl BuildXML for PageSize {
58    fn build_to<W: Write>(
59        &self,
60        stream: xml::writer::EventWriter<W>,
61    ) -> xml::writer::Result<xml::writer::EventWriter<W>> {
62        let w = format!("{}", self.w);
63        let h = format!("{}", self.h);
64
65        XMLBuilder::from(stream)
66            .apply(|b| match self.orient {
67                None => b.page_size(&w, &h),
68                Some(orient) => b.page_size_with_orient(&w, &h, &orient.to_string()),
69            })?
70            .into_inner()
71    }
72}
73
74#[cfg(test)]
75mod tests {
76
77    use super::*;
78    #[cfg(test)]
79    use pretty_assertions::assert_eq;
80    use std::str;
81
82    #[test]
83    fn test_page_size_default() {
84        let b = PageSize::new().build();
85        assert_eq!(
86            str::from_utf8(&b).unwrap(),
87            r#"<w:pgSz w:w="11906" w:h="16838" />"#
88        );
89    }
90}