docx-rs/docx-core/src/documents/elements/paragraph.rs

94 lines
2.3 KiB
Rust
Raw Normal View History

2019-11-11 08:36:26 +02:00
use super::{ParagraphProperty, Run};
2019-11-07 09:08:59 +02:00
use crate::documents::BuildXML;
2019-11-11 06:05:07 +02:00
use crate::types::*;
2019-11-07 09:08:59 +02:00
use crate::xml_builder::*;
2019-11-12 11:57:16 +02:00
#[derive(Debug, Clone)]
2019-11-07 09:08:59 +02:00
pub struct Paragraph {
runs: Vec<Run>,
2019-11-11 06:05:07 +02:00
property: ParagraphProperty,
2019-11-07 09:08:59 +02:00
}
impl Default for Paragraph {
fn default() -> Self {
2019-11-11 06:05:07 +02:00
Self {
runs: Vec::new(),
property: ParagraphProperty::new(),
}
2019-11-07 09:08:59 +02:00
}
}
impl Paragraph {
pub fn new() -> Paragraph {
Default::default()
}
pub fn add_run(mut self, run: Run) -> Paragraph {
self.runs.push(run);
self
}
2019-11-11 06:05:07 +02:00
pub fn align(mut self, alignment_type: AlignmentType) -> Paragraph {
self.property = self.property.align(alignment_type);
self
}
2019-11-11 08:36:26 +02:00
pub fn size(mut self, size: usize) -> Paragraph {
self.runs = self.runs.into_iter().map(|r| r.size(size)).collect();
self
}
pub fn style(mut self, style_id: &str) -> Paragraph {
self.property = self.property.style(style_id);
self
}
2019-11-11 09:48:28 +02:00
pub fn indent(mut self, left: usize, special_indent: Option<SpecialIndentType>) -> Paragraph {
self.property = self.property.indent(left, special_indent);
self
}
2019-11-07 09:08:59 +02:00
}
impl BuildXML for Paragraph {
fn build(&self) -> Vec<u8> {
2019-11-07 10:31:04 +02:00
XMLBuilder::new()
.open_paragraph()
2019-11-11 06:05:07 +02:00
.add_child(&self.property)
2019-11-07 10:31:04 +02:00
.add_children(&self.runs)
.close()
.build()
2019-11-07 09:08:59 +02:00
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(test)]
use pretty_assertions::assert_eq;
use std::str;
#[test]
fn test_paragraph() {
2019-11-13 09:51:58 +02:00
let b = Paragraph::new()
.add_run(Run::new().add_text("Hello"))
.build();
2019-11-07 09:08:59 +02:00
assert_eq!(
str::from_utf8(&b).unwrap(),
2019-11-12 06:33:45 +02:00
r#"<w:p><w:pPr><w:pStyle w:val="Normal" /><w:rPr /></w:pPr><w:r><w:rPr /><w:t xml:space="preserve">Hello</w:t></w:r></w:p>"#
2019-11-07 09:08:59 +02:00
);
}
2019-11-11 08:36:26 +02:00
#[test]
fn test_paragraph_size() {
2019-11-13 09:51:58 +02:00
let b = Paragraph::new()
.add_run(Run::new().add_text("Hello"))
.size(60)
.build();
2019-11-11 08:36:26 +02:00
assert_eq!(
str::from_utf8(&b).unwrap(),
2019-11-12 06:33:45 +02:00
r#"<w:p><w:pPr><w:pStyle w:val="Normal" /><w:rPr /></w:pPr><w:r><w:rPr><w:sz w:val="60" /><w:szCs w:val="60" /></w:rPr><w:t xml:space="preserve">Hello</w:t></w:r></w:p>"#
2019-11-11 08:36:26 +02:00
);
}
2019-11-07 09:08:59 +02:00
}