Skip to content

Commit 462e507

Browse files
committed
Table now supports width:auto for auto-fit content #202
1 parent 1a14761 commit 462e507

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

src/Html2OpenXml/Expressions/Table/TableExpression.cs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ private static int GuessColumnsCount(IHtmlTableElement tableNode)
156156
}
157157
}
158158

159-
if (rows.Any())
159+
if (rows.Length > 0)
160160
columnCount = Math.Max(rows.Max(), columnCount);
161161
}
162162

@@ -186,6 +186,9 @@ protected override void ComposeStyles (ParsingContext context)
186186
tableProperties.TableWidth = new() { Type = TableWidthUnitValues.Dxa,
187187
Width = width.ValueInDxa.ToString(CultureInfo.InvariantCulture) };
188188
break;
189+
case UnitMetric.Auto:
190+
tableProperties.TableWidth = new() { Width = "0", Type = TableWidthUnitValues.Auto };
191+
break;
189192
}
190193

191194
foreach (string className in tableNode.ClassList)

test/HtmlToOpenXml.Tests/TableTests.cs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -660,5 +660,26 @@ public void CellBorders_ShouldNotPropagate_OnRuns()
660660
Assert.That(runs.Count(), Is.EqualTo(1));
661661
Assert.That(runs.First().RunProperties?.Border, Is.Null);
662662
}
663+
664+
[TestCase("100%", "pct", "5000")]
665+
[TestCase("auto", "auto", "0")]
666+
[TestCase("120px", "dxa", "1800")]
667+
[TestCase("", "pct", "5000", Description = "Defaults to 100%")]
668+
public void Width_ReturnsRefineTableWidth(string width, string expectedUnit, string expectedValue)
669+
{
670+
var elements = converter.Parse(@$"<table style='width: {width}'>
671+
<tr><td>Placeholder</td></tr>
672+
</table>");
673+
674+
Assert.That(elements, Has.Count.EqualTo(1));
675+
Assert.That(elements, Has.All.TypeOf<Table>());
676+
var tableWidth = elements[0].GetFirstChild<TableProperties>()?.TableWidth;
677+
Assert.That(tableWidth, Is.Not.Null);
678+
Assert.Multiple(() =>
679+
{
680+
Assert.That(tableWidth?.Type?.Value, Is.EqualTo(new TableWidthUnitValues(expectedUnit)));
681+
Assert.That(tableWidth?.Width?.Value, Is.EqualTo(expectedValue));
682+
});
683+
}
663684
}
664685
}

0 commit comments

Comments
 (0)