docx_rust/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            }
53        }
54        Ok(())
55    }
56}
57
58impl<'a> XmlWrite for Header<'a> {
59    fn to_writer<W: Write>(&self, writer: &mut XmlWriter<W>) -> XmlResult<()> {
60        let Header { content } = self;
61
62        log::debug!("[Header] Started writing.");
63        let _ = write!(writer.inner, "{}", crate::schema::SCHEMA_XML);
64
65        writer.write_element_start("w:hdr")?;
66
67        writer.write_attribute("xmlns:w", SCHEMA_MAIN)?;
68
69        writer.write_attribute("xmlns:w14", SCHEMA_WORDML_14)?;
70
71        writer.write_element_end_open()?;
72
73        for c in content {
74            c.to_writer(writer)?;
75        }
76
77        writer.write_element_end_close("w:hdr")?;
78
79        log::debug!("[Document] Finished writing.");
80
81        Ok(())
82    }
83}
84
85__xml_test_suites!(
86    Header,
87    Header::default(),
88    format!(
89        r#"{}<w:hdr xmlns:w="{}" xmlns:w14="{}"></w:hdr>"#,
90        crate::schema::SCHEMA_XML,
91        SCHEMA_MAIN,
92        SCHEMA_WORDML_14
93    )
94    .as_str(),
95);