Skip to main content

rs_docx/document/
header.rs

1//! Header part
2//!
3//! The corresponding ZIP item is `/word/header{n}.xml`.
4//!
5
6use hard_xml::{XmlRead, XmlResult, XmlWrite, XmlWriter};
7use std::borrow::Borrow;
8use std::io::Write;
9
10use crate::__xml_test_suites;
11use crate::schema::{SCHEMA_MAIN, SCHEMA_WORDML_14};
12
13use crate::document::BodyContent;
14
15/// The root element of the main document part.
16#[derive(Debug, Default, XmlRead, Clone)]
17#[cfg_attr(test, derive(PartialEq))]
18#[xml(tag = "w:hdr")]
19pub struct Header<'a> {
20    #[xml(child = "w:p", child = "w:tbl", child = "w:sectPr", child = "w:sdt")]
21    pub content: Vec<BodyContent<'a>>,
22}
23
24impl<'a> Header<'a> {
25    pub fn push<T: Into<BodyContent<'a>>>(&mut self, content: T) -> &mut Self {
26        self.content.push(content.into());
27        self
28    }
29    pub fn replace_text_simple<S>(&mut self, old: S, new: S)
30    where
31        S: AsRef<str>,
32    {
33        let _d = self.replace_text(&[(old, new)]);
34    }
35
36    pub fn replace_text<'b, I, T, S>(&mut self, dic: T) -> crate::DocxResult<()>
37    where
38        S: AsRef<str> + 'b,
39        T: IntoIterator<Item = I> + Copy,
40        I: Borrow<(S, S)>,
41    {
42        for content in self.content.iter_mut() {
43            match content {
44                BodyContent::Paragraph(p) => {
45                    p.replace_text(dic)?;
46                }
47                BodyContent::Table(_) => {}
48                BodyContent::SectionProperty(_) => {}
49                BodyContent::Sdt(_) => {}
50                BodyContent::TableCell(_) => {}
51                BodyContent::Run(_) => {}
52                BodyContent::BookmarkStart(_) => {}
53                BodyContent::BookmarkEnd(_) => {}
54            }
55        }
56        Ok(())
57    }
58}
59
60impl<'a> XmlWrite for Header<'a> {
61    fn to_writer<W: Write>(&self, writer: &mut XmlWriter<W>) -> XmlResult<()> {
62        let Header { content } = self;
63
64        log::debug!("[Header] Started writing.");
65        let _ = write!(writer.inner, "{}", crate::schema::SCHEMA_XML);
66
67        writer.write_element_start("w:hdr")?;
68
69        writer.write_attribute("xmlns:w", SCHEMA_MAIN)?;
70
71        writer.write_attribute("xmlns:w14", SCHEMA_WORDML_14)?;
72
73        writer.write_element_end_open()?;
74
75        for c in content {
76            c.to_writer(writer)?;
77        }
78
79        writer.write_element_end_close("w:hdr")?;
80
81        log::debug!("[Document] Finished writing.");
82
83        Ok(())
84    }
85}
86
87__xml_test_suites!(
88    Header,
89    Header::default(),
90    format!(
91        r#"{}<w:hdr xmlns:w="{}" xmlns:w14="{}"></w:hdr>"#,
92        crate::schema::SCHEMA_XML,
93        SCHEMA_MAIN,
94        SCHEMA_WORDML_14
95    )
96    .as_str(),
97);