Skip to content
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
Binary file added assets/bugfixes/issue-289/after.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/bugfixes/issue-289/before.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/bugfixes/issue-289/gt.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
235 changes: 222 additions & 13 deletions crates/office2pdf/src/parser/docx_context_table_style.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,37 @@ use std::cell::Cell;
use std::collections::HashMap;

use super::super::{Block, Color, TextStyle, parse_hex_color};
use crate::ir::{BorderLineStyle, BorderSide, CellBorder};

#[derive(Debug, Clone, Copy, Default)]
#[derive(Debug, Clone, Default)]
struct RegionBorders {
top: Option<BorderSide>,
bottom: Option<BorderSide>,
left: Option<BorderSide>,
right: Option<BorderSide>,
inside_h: Option<BorderSide>,
inside_v: Option<BorderSide>,
}

impl RegionBorders {
fn overlay(self, other: Self) -> Self {
Self {
top: other.top.or(self.top),
bottom: other.bottom.or(self.bottom),
left: other.left.or(self.left),
right: other.right.or(self.right),
inside_h: other.inside_h.or(self.inside_h),
inside_v: other.inside_v.or(self.inside_v),
}
}
}

#[derive(Debug, Clone, Default)]
struct TableRegionStyle {
background: Option<Color>,
text_color: Option<Color>,
bold: Option<bool>,
borders: RegionBorders,
}

impl TableRegionStyle {
Expand All @@ -16,6 +41,7 @@ impl TableRegionStyle {
background: other.background.or(self.background),
text_color: other.text_color.or(self.text_color),
bold: other.bold.or(self.bold),
borders: self.borders.overlay(other.borders),
}
}
}
Expand Down Expand Up @@ -73,11 +99,12 @@ pub(in super::super) struct TableStyleContext {
cursor: Cell<usize>,
}

#[derive(Debug, Clone, Copy, Default)]
#[derive(Debug, Clone, Default)]
pub(in super::super) struct ResolvedTableCellStyle {
pub(in super::super) background: Option<Color>,
pub(in super::super) text_color: Option<Color>,
pub(in super::super) bold: Option<bool>,
pub(in super::super) border: Option<CellBorder>,
}

pub(in super::super) struct ResolvedTableStyle {
Expand Down Expand Up @@ -117,53 +144,115 @@ impl ResolvedTableStyle {
column_span: usize,
column_count: usize,
) -> ResolvedTableCellStyle {
let mut region = self.definition.base;
let mut region = self.definition.base.clone();
if self.look.horizontal_banding {
let band_index = row_index.saturating_sub(usize::from(self.look.first_row));
region = region.overlay(if band_index.is_multiple_of(2) {
self.definition.band1_horizontal
self.definition.band1_horizontal.clone()
} else {
self.definition.band2_horizontal
self.definition.band2_horizontal.clone()
});
}
if self.look.vertical_banding {
let band_index = column_index.saturating_sub(usize::from(self.look.first_column));
region = region.overlay(if band_index.is_multiple_of(2) {
self.definition.band1_vertical
self.definition.band1_vertical.clone()
} else {
self.definition.band2_vertical
self.definition.band2_vertical.clone()
});
}
if self.look.first_row && row_index == 0 {
region = region.overlay(self.definition.first_row);
region = region.overlay(self.definition.first_row.clone());
}
if self.look.last_row && row_index + 1 == row_count {
region = region.overlay(self.definition.last_row);
region = region.overlay(self.definition.last_row.clone());
}
if self.look.first_column && column_index == 0 {
region = region.overlay(self.definition.first_column);
region = region.overlay(self.definition.first_column.clone());
}
if self.look.last_column && column_index + column_span == column_count {
region = region.overlay(self.definition.last_column);
region = region.overlay(self.definition.last_column.clone());
}
// Resolve the cell's border sides. The base region draws the table
// grid (outer edges on boundary cells, insideH/insideV on interior
// edges); an active special region's explicit sides then override
// the matching edges of its own cells (e.g. the firstRow bottom
// border lands on the header row's bottom edge).
let base = &self.definition.base.borders;
let mut top = if row_index == 0 {
base.top.clone()
} else {
base.inside_h.clone()
};
let mut bottom = if row_index + 1 == row_count {
base.bottom.clone()
} else {
base.inside_h.clone()
};
let mut left = if column_index == 0 {
base.left.clone()
} else {
base.inside_v.clone()
};
let mut right = if column_index + column_span >= column_count {
base.right.clone()
} else {
base.inside_v.clone()
};

let mut override_edges = |borders: &RegionBorders| {
if let Some(side) = &borders.top {
top = Some(side.clone());
}
if let Some(side) = &borders.bottom {
bottom = Some(side.clone());
}
if let Some(side) = &borders.left {
left = Some(side.clone());
}
if let Some(side) = &borders.right {
right = Some(side.clone());
}
};
if self.look.first_column && column_index == 0 {
override_edges(&self.definition.first_column.borders);
}
if self.look.last_column && column_index + column_span == column_count {
override_edges(&self.definition.last_column.borders);
}
if self.look.first_row && row_index == 0 {
override_edges(&self.definition.first_row.borders);
}
if self.look.last_row && row_index + 1 == row_count {
override_edges(&self.definition.last_row.borders);
}
let border = (top.is_some() || bottom.is_some() || left.is_some() || right.is_some())
.then_some(CellBorder {
top,
bottom,
left,
right,
});

ResolvedTableCellStyle {
background: region.background,
text_color: region.text_color,
bold: region.bold,
border,
}
}
}

pub(in super::super) fn apply_table_text_style(
blocks: &mut [Block],
region: ResolvedTableCellStyle,
region: &ResolvedTableCellStyle,
) {
for block in blocks {
apply_text_style(block, region);
}
}

fn apply_text_style(block: &mut Block, region: ResolvedTableCellStyle) {
fn apply_text_style(block: &mut Block, region: &ResolvedTableCellStyle) {
if let Block::Paragraph(paragraph) = block {
for run in &mut paragraph.runs {
let mut style: TextStyle = run.style.clone();
Expand Down Expand Up @@ -210,6 +299,36 @@ fn region_mut(
}
}

/// Parse one border side element (`<w:top w:val w:sz w:color/>`).
/// Widths are eighths of a point; nil/none sides are skipped.
fn parse_border_side(element: &quick_xml::events::BytesStart<'_>) -> Option<BorderSide> {
let val = attribute_value(element, b"val").unwrap_or_default();
if val == "nil" || val == "none" || val.is_empty() {
return None;
}
let width: f64 = attribute_value(element, b"sz")
.and_then(|value| value.parse::<f64>().ok())
.map(|eighths| eighths / 8.0)
.unwrap_or(0.5);
let color: Color = attribute_value(element, b"color")
.filter(|value| value != "auto")
.and_then(|value| parse_hex_color(&value))
.unwrap_or(Color::new(0, 0, 0));
let style = match val.as_str() {
"dashed" | "dashSmallGap" => BorderLineStyle::Dashed,
"dotted" => BorderLineStyle::Dotted,
"dotDash" => BorderLineStyle::DashDot,
"dotDotDash" => BorderLineStyle::DashDotDot,
"double" | "doubleWave" => BorderLineStyle::Double,
_ => BorderLineStyle::Solid,
};
Some(BorderSide {
width,
color,
style,
})
}

fn scan_table_styles(xml: &str) -> HashMap<String, TableStyleDefinition> {
let mut reader = quick_xml::Reader::from_str(xml);
let mut buffer: Vec<u8> = Vec::new();
Expand All @@ -219,6 +338,7 @@ fn scan_table_styles(xml: &str) -> HashMap<String, TableStyleDefinition> {
let mut current_region = TableStyleRegion::Base;
let mut in_cell_properties = false;
let mut in_run_properties = false;
let mut in_borders = false;

loop {
match reader.read_event_into(&mut buffer) {
Expand All @@ -237,6 +357,7 @@ fn scan_table_styles(xml: &str) -> HashMap<String, TableStyleDefinition> {
}
b"tcPr" if current_style_id.is_some() => in_cell_properties = true,
b"rPr" if current_style_id.is_some() => in_run_properties = true,
b"tblBorders" | b"tcBorders" if current_style_id.is_some() => in_borders = true,
_ => {}
}
apply_style_element(
Expand All @@ -245,6 +366,7 @@ fn scan_table_styles(xml: &str) -> HashMap<String, TableStyleDefinition> {
current_region,
in_cell_properties,
in_run_properties,
in_borders,
);
}
Ok(quick_xml::events::Event::Empty(ref element)) => {
Expand All @@ -254,11 +376,13 @@ fn scan_table_styles(xml: &str) -> HashMap<String, TableStyleDefinition> {
current_region,
in_cell_properties,
in_run_properties,
in_borders,
);
}
Ok(quick_xml::events::Event::End(ref element)) => match element.local_name().as_ref() {
b"tcPr" => in_cell_properties = false,
b"rPr" => in_run_properties = false,
b"tblBorders" | b"tcBorders" => in_borders = false,
b"tblStylePr" => current_region = TableStyleRegion::Base,
b"style" => {
if let Some(style_id) = current_style_id.take() {
Expand All @@ -282,10 +406,26 @@ fn apply_style_element(
region: TableStyleRegion,
in_cell_properties: bool,
in_run_properties: bool,
in_borders: bool,
) {
let Some(target) = region_mut(definition, region) else {
return;
};
if in_borders {
let side_slot: Option<&mut Option<BorderSide>> = match element.local_name().as_ref() {
b"top" => Some(&mut target.borders.top),
b"bottom" => Some(&mut target.borders.bottom),
b"left" | b"start" => Some(&mut target.borders.left),
b"right" | b"end" => Some(&mut target.borders.right),
b"insideH" => Some(&mut target.borders.inside_h),
b"insideV" => Some(&mut target.borders.inside_v),
_ => None,
};
if let Some(slot) = side_slot {
*slot = parse_border_side(element);
return;
}
}
match element.local_name().as_ref() {
b"shd" if in_cell_properties => {
target.background = attribute_value(element, b"fill")
Expand Down Expand Up @@ -415,3 +555,72 @@ fn boolean_attribute(element: &quick_xml::events::BytesStart<'_>, name: &[u8]) -
fn on_off_element_is_enabled(element: &quick_xml::events::BytesStart<'_>) -> bool {
boolean_attribute(element, b"val").unwrap_or(true)
}

#[cfg(test)]
mod tests {
use super::*;

const STYLES_XML: &str = r#"<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:style w:type="table" w:styleId="DarkGrid">
<w:tblPr>
<w:tblBorders>
<w:top w:val="single" w:sz="4" w:color="FFFFFF"/>
<w:left w:val="single" w:sz="4" w:color="FFFFFF"/>
<w:bottom w:val="single" w:sz="4" w:color="FFFFFF"/>
<w:right w:val="single" w:sz="4" w:color="FFFFFF"/>
<w:insideH w:val="single" w:sz="4" w:color="FFFFFF"/>
<w:insideV w:val="single" w:sz="4" w:color="FFFFFF"/>
</w:tblBorders>
</w:tblPr>
<w:tcPr><w:shd w:val="clear" w:fill="404040"/></w:tcPr>
<w:tblStylePr w:type="firstRow">
<w:tcPr>
<w:tcBorders>
<w:bottom w:val="double" w:sz="8" w:color="FF0000"/>
</w:tcBorders>
<w:shd w:val="clear" w:fill="000000"/>
</w:tcPr>
</w:tblStylePr>
</w:style>
</w:styles>"#;

const DOCUMENT_XML: &str = r#"<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:body><w:tbl><w:tblPr>
<w:tblStyle w:val="DarkGrid"/>
<w:tblLook w:firstRow="1" w:noHBand="1" w:noVBand="1"/>
</w:tblPr></w:tbl></w:body>
</w:document>"#;

#[test]
fn test_table_style_borders_resolve_per_cell() {
let context = TableStyleContext::from_xml(Some(DOCUMENT_XML), Some(STYLES_XML));
let resolved = context.consume_next().expect("style application");

// Interior cell: white grid on all sides from tblBorders.
let interior = resolved.cell_style(1, 3, 1, 1, 3);
let border = interior.border.expect("interior cell gets style borders");
for side in [&border.top, &border.bottom, &border.left, &border.right] {
let side = side.as_ref().expect("all sides bordered");
assert_eq!(side.color, Color::new(0xFF, 0xFF, 0xFF));
assert_eq!(side.width, 0.5, "w:sz=4 eighths = 0.5pt");
}

// First-row cell: red double bottom border from the region override.
let header = resolved.cell_style(0, 3, 1, 1, 3);
let border = header.border.expect("header cell gets style borders");
let bottom = border.bottom.as_ref().expect("bottom side");
assert_eq!(bottom.color, Color::new(0xFF, 0, 0));
assert_eq!(bottom.width, 1.0, "w:sz=8 eighths = 1pt");
assert_eq!(
bottom.style,
crate::ir::BorderLineStyle::Double,
"double border style survives"
);
assert_eq!(header.background, Some(Color::new(0, 0, 0)));

// Boundary edges use the outer borders (still white here).
let top_left = resolved.cell_style(1, 3, 0, 1, 3);
let border = top_left.border.expect("boundary cell borders");
assert!(border.left.is_some());
}
}
6 changes: 5 additions & 1 deletion crates/office2pdf/src/parser/docx_tables.rs
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,11 @@ fn apply_conditional_table_style(raw_rows: &mut [RawRow], table_style: &Resolved
if !cell.has_explicit_background {
cell.background = style.background;
}
apply_table_text_style(&mut cell.content, style);
// Explicit tcBorders on the cell win over the style's borders.
if cell.border.is_none() {
cell.border = style.border.clone();
}
apply_table_text_style(&mut cell.content, &style);
}
}
}
Expand Down
Loading