Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support table valign #56

Merged
merged 7 commits into from
Mar 19, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion docx-core/examples/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ pub fn main() -> Result<(), DocxError> {
.grid_span(2),
TableCell::new()
.add_paragraph(Paragraph::new().add_run(Run::new().add_text("Hello")))
.vertical_align(VAlignType::Center)
.vertical_merge(VMergeType::Restart),
]),
TableRow::new(vec![
Expand All @@ -32,7 +33,8 @@ pub fn main() -> Result<(), DocxError> {
.vertical_merge(VMergeType::Continue),
]),
])
.set_grid(vec![2000, 2000, 2000]);
.set_grid(vec![2000, 2000, 2000])
.indent(1000);
Docx::new().add_table(table).build().pack(file)?;
Ok(())
}
2 changes: 2 additions & 0 deletions docx-core/src/documents/elements/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ mod table_width;
mod text;
mod underline;
mod vanish;
mod vertical_align;
mod vertical_merge;
mod zoom;

Expand Down Expand Up @@ -129,5 +130,6 @@ pub use table_width::*;
pub use text::*;
pub use underline::*;
pub use vanish::*;
pub use vertical_align::*;
pub use vertical_merge::*;
pub use zoom::*;
7 changes: 6 additions & 1 deletion docx-core/src/documents/elements/table_cell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,11 @@ impl TableCell {
self
}

pub fn vertical_align(mut self, t: VAlignType) -> TableCell {
self.property = self.property.vertical_align(t);
self
}

pub fn grid_span(mut self, v: usize) -> TableCell {
self.property = self.property.grid_span(v);
self
Expand Down Expand Up @@ -122,7 +127,7 @@ mod tests {
.grid_span(2);
assert_eq!(
serde_json::to_string(&c).unwrap(),
r#"{"children":[{"type":"paragraph","data":{"children":[{"type":"run","data":{"runProperty":{"sz":null,"szCs":null,"color":null,"highlight":null,"underline":null,"bold":null,"boldCs":null,"italic":null,"italicCs":null,"vanish":null},"children":[{"type":"text","data":{"preserveSpace":true,"text":"Hello"}}]}}],"property":{"runProperty":{"sz":null,"szCs":null,"color":null,"highlight":null,"underline":null,"bold":null,"boldCs":null,"italic":null,"italicCs":null,"vanish":null},"style":"Normal","numberingProperty":null,"alignment":null,"indent":null},"hasNumbering":false,"attrs":[]}}],"property":{"width":null,"borders":null,"gridSpan":2,"verticalMerge":null},"hasNumbering":false}"#
r#"{"children":[{"type":"paragraph","data":{"children":[{"type":"run","data":{"runProperty":{"sz":null,"szCs":null,"color":null,"highlight":null,"underline":null,"bold":null,"boldCs":null,"italic":null,"italicCs":null,"vanish":null},"children":[{"type":"text","data":{"preserveSpace":true,"text":"Hello"}}]}}],"property":{"runProperty":{"sz":null,"szCs":null,"color":null,"highlight":null,"underline":null,"bold":null,"boldCs":null,"italic":null,"italicCs":null,"vanish":null},"style":"Normal","numberingProperty":null,"alignment":null,"indent":null},"hasNumbering":false,"attrs":[]}}],"property":{"width":null,"borders":null,"gridSpan":2,"verticalMerge":null,"verticalAlign":null},"hasNumbering":false}"#
);
}
}
8 changes: 4 additions & 4 deletions docx-core/src/documents/elements/table_cell_margins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,10 @@ impl BuildXML for TableCellMargins {
fn build(&self) -> Vec<u8> {
XMLBuilder::new()
.open_table_cell_margins()
.margin_top(self.top, WidthType::DXA)
.margin_left(self.left, WidthType::DXA)
.margin_bottom(self.bottom, WidthType::DXA)
.margin_right(self.right, WidthType::DXA)
.margin_top(self.top as i32, WidthType::DXA)
.margin_left(self.left as i32, WidthType::DXA)
.margin_bottom(self.bottom as i32, WidthType::DXA)
.margin_right(self.right as i32, WidthType::DXA)
.close()
.build()
}
Expand Down
31 changes: 29 additions & 2 deletions docx-core/src/documents/elements/table_cell_property.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use serde::Serialize;

use super::{GridSpan, TableCellBorders, TableCellWidth, VMerge};
use super::{GridSpan, TableCellBorders, TableCellWidth, VAlign, VMerge};
use crate::documents::BuildXML;
use crate::types::*;
use crate::xml_builder::*;
Expand All @@ -12,6 +12,7 @@ pub struct TableCellProperty {
borders: Option<TableCellBorders>,
grid_span: Option<GridSpan>,
vertical_merge: Option<VMerge>,
vertical_align: Option<VAlign>,
}

impl TableCellProperty {
Expand All @@ -29,6 +30,11 @@ impl TableCellProperty {
self
}

pub fn vertical_align(mut self, t: VAlignType) -> TableCellProperty {
self.vertical_align = Some(VAlign::new(t));
self
}

pub fn grid_span(mut self, v: usize) -> TableCellProperty {
self.grid_span = Some(GridSpan::new(v));
self
Expand All @@ -42,6 +48,7 @@ impl Default for TableCellProperty {
borders: None,
grid_span: None,
vertical_merge: None,
vertical_align: None,
}
}
}
Expand All @@ -54,6 +61,7 @@ impl BuildXML for TableCellProperty {
.add_optional_child(&self.borders)
.add_optional_child(&self.grid_span)
.add_optional_child(&self.vertical_merge)
.add_optional_child(&self.vertical_align)
.close()
.build()
}
Expand Down Expand Up @@ -94,6 +102,16 @@ mod tests {
);
}

#[test]
fn test_valign() {
let c = TableCellProperty::new().vertical_align(VAlignType::Center);
let b = c.build();
assert_eq!(
str::from_utf8(&b).unwrap(),
r#"<w:tcPr><w:vAlign w:val="center" /></w:tcPr>"#
);
}

#[test]
fn test_table_cell_prop_json() {
let c = TableCellProperty::new()
Expand All @@ -102,7 +120,16 @@ mod tests {
.width(200, WidthType::DXA);
assert_eq!(
serde_json::to_string(&c).unwrap(),
r#"{"width":{"width":200,"widthType":"DXA"},"borders":null,"gridSpan":3,"verticalMerge":"continue"}"#
r#"{"width":{"width":200,"widthType":"DXA"},"borders":null,"gridSpan":3,"verticalMerge":"continue","verticalAlign":null}"#
);
}

#[test]
fn test_table_cell_prop_json_with_valign() {
let c = TableCellProperty::new().vertical_align(VAlignType::Center);
assert_eq!(
serde_json::to_string(&c).unwrap(),
r#"{"width":null,"borders":null,"gridSpan":null,"verticalMerge":null,"verticalAlign":"center"}"#
);
}
}
2 changes: 1 addition & 1 deletion docx-core/src/documents/elements/table_cell_width.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ impl TableCellWidth {
impl BuildXML for TableCellWidth {
fn build(&self) -> Vec<u8> {
XMLBuilder::new()
.table_cell_width(self.width, WidthType::DXA)
.table_cell_width(self.width as i32, WidthType::DXA)
.build()
}
}
Expand Down
2 changes: 1 addition & 1 deletion docx-core/src/documents/elements/table_grid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ impl BuildXML for TableGrid {
fn build(&self) -> Vec<u8> {
let mut base = XMLBuilder::new().open_table_grid();
for g in &self.grid {
base = base.grid_column(*g, WidthType::DXA);
base = base.grid_column(*g as i32, WidthType::DXA);
}
base.close().build()
}
Expand Down
4 changes: 3 additions & 1 deletion docx-core/src/documents/elements/table_indent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ impl TableIndent {

impl BuildXML for TableIndent {
fn build(&self) -> Vec<u8> {
XMLBuilder::new().table_indent(20, WidthType::DXA).build()
XMLBuilder::new()
.table_indent(self.width, WidthType::DXA)
.build()
}
}

Expand Down
2 changes: 1 addition & 1 deletion docx-core/src/documents/elements/table_row.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ mod tests {
let r = TableRow::new(vec![TableCell::new()]);
assert_eq!(
serde_json::to_string(&r).unwrap(),
r#"{"cells":[{"children":[],"property":{"width":null,"borders":null,"gridSpan":null,"verticalMerge":null},"hasNumbering":false}],"hasNumbering":false,"property":{}}"#
r#"{"cells":[{"children":[],"property":{"width":null,"borders":null,"gridSpan":null,"verticalMerge":null,"verticalAlign":null},"hasNumbering":false}],"hasNumbering":false,"property":{}}"#
);
}
}
2 changes: 1 addition & 1 deletion docx-core/src/documents/elements/table_width.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ impl TableWidth {
impl BuildXML for TableWidth {
fn build(&self) -> Vec<u8> {
XMLBuilder::new()
.table_width(self.width, WidthType::DXA)
.table_width(self.width as i32, WidthType::DXA)
.build()
}
}
Expand Down
51 changes: 51 additions & 0 deletions docx-core/src/documents/elements/vertical_align.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
use serde::{Serialize, Serializer};

use crate::documents::BuildXML;
use crate::types::*;
use crate::xml_builder::*;

#[derive(Debug, Clone, PartialEq)]
pub struct VAlign {
val: VAlignType,
}

impl VAlign {
pub fn new(v: VAlignType) -> VAlign {
VAlign { val: v }
}
}

impl BuildXML for VAlign {
fn build(&self) -> Vec<u8> {
XMLBuilder::new()
.vertical_align(&self.val.to_string())
.build()
}
}

impl Serialize for VAlign {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&format!("{}", &self.val))
}
}

#[cfg(test)]
mod tests {

use super::*;
#[cfg(test)]
use pretty_assertions::assert_eq;
use std::str;

#[test]
fn test_build() {
let b = VAlign::new(VAlignType::Center).build();
assert_eq!(
str::from_utf8(&b).unwrap(),
r#"<w:vAlign w:val="center" />"#
);
}
}
34 changes: 34 additions & 0 deletions docx-core/src/reader/table_cell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,13 @@ impl ElementReader for TableCell {
cell = cell.vertical_merge(VMergeType::Continue)
}
}
XMLElement::VAlign => {
if let Some(a) = &attributes.get(0) {
cell = cell.vertical_align(VAlignType::from_str(
&a.value,
)?);
}
}
XMLElement::TableCellBorders => {
// TODO: Support table cell borders later
}
Expand Down Expand Up @@ -159,4 +166,31 @@ mod tests {
.vertical_merge(VMergeType::Continue),
);
}

#[test]
fn test_read_valign() {
let c = r#"<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:tc>
<w:tcPr>
<w:tcW w:w="6425" w:type="dxa"/>
<w:vAlign w:val="bottom"/>
<w:shd w:fill="auto" w:val="clear"/>
</w:tcPr>
<w:p>
<w:r>
<w:rPr></w:rPr>
</w:r>
</w:p>
</w:tc>
</w:document>"#;
let mut parser = EventReader::new(c.as_bytes());
let cell = TableCell::read(&mut parser, &[]).unwrap();
assert_eq!(
cell,
TableCell::new()
.add_paragraph(Paragraph::new().add_run(Run::new()))
.width(6425, WidthType::DXA)
.vertical_align(VAlignType::Bottom),
);
}
}
2 changes: 2 additions & 0 deletions docx-core/src/reader/xml_element.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ pub enum XMLElement {
BookmarkEnd,
CommentRangeStart,
CommentRangeEnd,
VAlign,
Table,
TableProperty,
TableRow,
Expand Down Expand Up @@ -155,6 +156,7 @@ impl FromStr for XMLElement {
"lvlJc" => Ok(XMLElement::LevelJustification),
"numStyleLink" => Ok(XMLElement::NumStyleLink),
"styleLink" => Ok(XMLElement::StyleLink),
"vAlign" => Ok(XMLElement::VAlign),
_ => Ok(XMLElement::Unsupported),
}
}
Expand Down
2 changes: 2 additions & 0 deletions docx-core/src/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ pub mod font_pitch_type;
pub mod special_indent_type;
pub mod style_type;
pub mod table_alignment_type;
pub mod vertical_align_type;
pub mod vertical_merge_type;
pub mod width_type;

Expand All @@ -19,5 +20,6 @@ pub use font_pitch_type::*;
pub use special_indent_type::*;
pub use style_type::*;
pub use table_alignment_type::*;
pub use vertical_align_type::*;
pub use vertical_merge_type::*;
pub use width_type::*;
37 changes: 37 additions & 0 deletions docx-core/src/types/vertical_align_type.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
use std::fmt;
use wasm_bindgen::prelude::*;

use super::errors;
use std::str::FromStr;

#[wasm_bindgen]
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum VAlignType {
Top,
Center,
Bottom,
Unsupported,
}

impl fmt::Display for VAlignType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
VAlignType::Top => write!(f, "top"),
VAlignType::Center => write!(f, "center"),
VAlignType::Bottom => write!(f, "bottom"),
VAlignType::Unsupported => write!(f, "unsupported"),
}
}
}

impl FromStr for VAlignType {
type Err = errors::TypeError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"top" => Ok(VAlignType::Top),
"center" => Ok(VAlignType::Center),
"bottom" => Ok(VAlignType::Bottom),
_ => Ok(VAlignType::Unsupported),
}
}
}
1 change: 1 addition & 0 deletions docx-core/src/xml_builder/elements.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ impl XMLBuilder {

closed_with_usize!(grid_span, "w:gridSpan");
closed_with_str!(vertical_merge, "w:vMerge");
closed_with_str!(vertical_align, "w:vAlign");

closed_w_with_type_el!(margin_top, "w:top");
closed_w_with_type_el!(margin_left, "w:left");
Expand Down
2 changes: 1 addition & 1 deletion docx-core/src/xml_builder/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ macro_rules! closed_with_usize {

macro_rules! closed_w_with_type_el {
($name: ident, $el_name: expr) => {
pub(crate) fn $name(mut self, w: usize, t: WidthType) -> Self {
pub(crate) fn $name(mut self, w: i32, t: WidthType) -> Self {
self.writer
.write(
XmlEvent::start_element($el_name)
Expand Down

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion docx-core/tests/snapshots/reader__read_insert_table.snap

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion docx-core/tests/snapshots/reader__read_table_docx.snap

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Loading