docx-rs/docx-core/src/documents/document.rs

65 lines
2.1 KiB
Rust
Raw Normal View History

2019-11-11 07:39:22 +02:00
use super::Paragraph;
2019-11-07 09:08:59 +02:00
use crate::documents::BuildXML;
use crate::xml_builder::*;
2019-11-07 11:45:03 +02:00
#[derive(Debug)]
2019-11-07 10:31:04 +02:00
pub struct Document {
paragraphs: Vec<Paragraph>,
}
2019-11-07 09:08:59 +02:00
impl Document {
pub fn new() -> Document {
Default::default()
}
2019-11-07 10:31:04 +02:00
pub fn add_paragraph(mut self, p: Paragraph) -> Self {
self.paragraphs.push(p);
self
}
2019-11-07 09:08:59 +02:00
}
impl Default for Document {
fn default() -> Self {
2019-11-07 10:31:04 +02:00
Self {
paragraphs: Vec::new(),
}
2019-11-07 09:08:59 +02:00
}
}
impl BuildXML for Document {
fn build(&self) -> Vec<u8> {
let b = XMLBuilder::new();
2019-11-07 10:31:04 +02:00
b.declaration(Some(true))
.open_document()
.open_body()
.add_children(&self.paragraphs)
.close()
.close()
.build()
2019-11-07 09:08:59 +02:00
}
}
#[cfg(test)]
mod tests {
2019-11-11 07:39:22 +02:00
use super::super::Run;
2019-11-07 09:08:59 +02:00
use super::*;
#[cfg(test)]
use pretty_assertions::assert_eq;
use std::str;
#[test]
fn test_document() {
2019-11-07 10:31:04 +02:00
let b = Document::new()
.add_paragraph(Paragraph::new().add_run(Run::new("Hello")))
.build();
2019-11-07 09:08:59 +02:00
assert_eq!(
str::from_utf8(&b).unwrap(),
2019-11-07 10:31:04 +02:00
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:document xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape" xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:wp14="http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" mc:Ignorable="w14 wp14">
<w:body><w:p><w:r><w:rPr /><w:t>Hello</w:t></w:r></w:p></w:body>
2019-11-07 09:08:59 +02:00
</w:document>"#
);
}
}