Skip to main content

docx_templating/
rendered.rs

1//! Rendered document output.
2
3use std::io::Write;
4use std::path::Path;
5
6/// A rendered DOCX document.
7///
8/// Wraps the generated ZIP bytes in memory, providing methods to
9/// write to a file or extract the raw bytes.
10///
11/// # Examples
12///
13/// ```no_run
14/// # use docx_templating::{Template, Context};
15/// # use serde_json::json;
16/// # fn example() -> docx_templating::Result<()> {
17/// let template = Template::from_path("template.docx")?;
18/// let rendered = template.render(json!({"name": "Ada"}))?;
19///
20/// // Write to file
21/// rendered.write_to_file("output.docx")?;
22/// # Ok(())
23/// # }
24///
25/// // Or get raw bytes
26/// # fn example2() -> docx_templating::Result<()> {
27/// # let template = Template::from_path("template.docx")?;
28/// # let rendered = template.render(json!({"name": "Ada"}))?;
29/// let bytes = rendered.as_bytes();
30/// # Ok(())
31/// # }
32/// ```
33#[derive(Debug)]
34pub struct RenderedDocument {
35    bytes: Vec<u8>,
36}
37
38impl RenderedDocument {
39    /// Create a rendered document from raw DOCX bytes.
40    pub(crate) fn new(bytes: Vec<u8>) -> Self {
41        Self { bytes }
42    }
43
44    /// Write the document to a file.
45    ///
46    /// # Errors
47    ///
48    /// Returns error if the file cannot be written.
49    pub fn write_to_file(self, path: impl AsRef<Path>) -> crate::Result<()> {
50        std::fs::write(path, self.bytes)?;
51        Ok(())
52    }
53
54    /// Write the rendered DOCX bytes to any `Write` sink.
55    ///
56    /// Consumes the `RenderedDocument`.
57    ///
58    /// # Errors
59    ///
60    /// Returns an error if writing to the sink fails.
61    pub fn write_to_writer<W: Write>(self, mut writer: W) -> crate::Result<()> {
62        writer.write_all(&self.bytes)?;
63        Ok(())
64    }
65
66    /// Get a reference to the raw DOCX bytes.
67    pub fn as_bytes(&self) -> &[u8] {
68        &self.bytes
69    }
70
71    /// Consume the document and return the raw DOCX bytes.
72    pub fn into_bytes(self) -> Vec<u8> {
73        self.bytes
74    }
75}
76
77impl AsRef<[u8]> for RenderedDocument {
78    fn as_ref(&self) -> &[u8] {
79        &self.bytes
80    }
81}
82
83impl From<RenderedDocument> for Vec<u8> {
84    fn from(document: RenderedDocument) -> Self {
85        document.bytes
86    }
87}
88
89#[cfg(test)]
90mod tests {
91    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
92
93    use super::*;
94
95    #[test]
96    fn new_stores_bytes() {
97        let bytes = vec![1, 2, 3];
98        let doc = RenderedDocument::new(bytes.clone());
99        assert_eq!(doc.as_bytes(), &bytes);
100    }
101
102    #[test]
103    fn into_bytes_returns_ownership() {
104        let bytes = vec![1, 2, 3];
105        let doc = RenderedDocument::new(bytes.clone());
106        assert_eq!(doc.into_bytes(), bytes);
107    }
108
109    #[test]
110    fn as_ref_returns_the_bytes() {
111        let doc = RenderedDocument::new(vec![1, 2, 3]);
112        let bytes: &[u8] = doc.as_ref();
113        assert_eq!(bytes, &[1, 2, 3]);
114    }
115
116    #[test]
117    fn a_document_converts_into_a_byte_vector() {
118        let doc = RenderedDocument::new(vec![1, 2, 3]);
119        let bytes: Vec<u8> = doc.into();
120        assert_eq!(bytes, vec![1, 2, 3]);
121    }
122}