Skip to content

armgit / Filee

Public Imported from GitHub
0

Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.

Preserve DOCX cell padding and list marker glyphs in HWPX

amebaleon1a3ab9161108
diff --git a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Styles.cs b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Styles.cs
index ec312a8f..709b0053 100644
--- a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Styles.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Styles.cs
@@ -448,15 +448,17 @@ internal sealed partial class DocxReader
/// <summary>Word bullets often use Symbol/Wingdings private-use code points; map them to Unicode.</summary>
private static string BulletText(string text) => text switch
{
- "" or "\uF0B7" or "\uF09F" or "•" => "●",
+ "" => "●",
+ "\uF0B7" or "\uF09F" => "•",
"o" or "\uF06F" => "○",
- "\uF0A7" or "\uF06E" or "▪" => "■",
+ "\uF0A7" => "▪",
+ "\uF06E" => "■",
"\uF0D8" => "➢",
"\uF076" => "❖",
"\uF0FC" => "✓",
"\uF071" => "❑",
"\uF075" or "\uF0A8" => "◆",
- "-" or "–" or "\uF02D" => "-",
+ "\uF02D" => "-",
_ when text.Length > 0 && text[0] >= '\uF000' => "●",
_ => text,
};
diff --git a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Tables.cs b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Tables.cs
index fcb818d9..14a72948 100644
--- a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Tables.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Tables.cs
@@ -43,9 +43,10 @@ internal sealed partial class DocxReader
var look = tblPr?.Element(W + "tblLook");
var firstRowLook = Attr(look, "firstRow") is { } firstRow ? firstRow is "1" or "true"
: int.TryParse(Val(look), System.Globalization.NumberStyles.HexNumber, null, out var mask) && (mask & 0x20) != 0;
- var firstRowStyle = firstRowLook
- ? styleChain.SelectMany(s => s.TableConditions).LastOrDefault(c => Attr(c, "type") == "firstRow")
- : null;
+ var firstRowStyles = firstRowLook
+ ? styleChain.SelectMany(s => s.TableConditions).Where(c => Attr(c, "type") == "firstRow").ToList()
+ : [];
+ var firstRowStyle = firstRowStyles.LastOrDefault();
var rows = tbl.Elements().SelectMany(e => e.Name == W + "tr" ? [e] : FlattenRows(e)).ToList();
// vMerge: the cell that restarts a vertical merge, per grid column.
@@ -91,8 +92,12 @@ internal sealed partial class DocxReader
["bottom"] = borders.GetValueOrDefault(isLastRow ? "bottom" : "insideH", HBorder.None),
};
string? fill = null;
- foreach (var properties in styleChain.Select(s => s.TcPr).Append(r == 0 ? firstRowStyle?.Element(W + "tcPr") : null).Append(tcPr))
+ foreach (var properties in styleChain.Select(s => s.TcPr)
+ .Concat(r == 0 ? firstRowStyles.Select(s => s.Element(W + "tcPr")) : [])
+ .Append(tcPr))
{
+ if (properties?.Element(W + "tcMar") is { } cellMar)
+ cell.CellMargin = CellMargins(cellMar, cell.CellMargin ?? table.CellMargin);
ApplyBorders(properties?.Element(W + "tcBorders"), cellBorders);
if (properties?.Element(W + "shd") is { } shd)
fill = ShadingColor(shd) ?? fill;
@@ -167,8 +172,13 @@ internal sealed partial class DocxReader
private static HInsets CellMargins(XElement cellMar, HInsets? current)
{
- int Get(string name, string alternative, int fallback) =>
- HwpxUnits.FromTwips(Twips(cellMar.Element(W + name), "w") ?? Twips(cellMar.Element(W + alternative), "w") ?? fallback / 5);
+ int Get(string name, string alternative, int fallback)
+ {
+ var side = cellMar.Element(W + name) ?? cellMar.Element(W + alternative);
+ if (Attr(side, "type") == "nil")
+ return 0;
+ return Twips(side, "w") is { } twips ? HwpxUnits.FromTwips(twips) : fallback;
+ }
var existing = current ?? new HInsets(540, 540, 0, 0);
return new HInsets(Get("left", "start", existing.Left), Get("right", "end", existing.Right), Get("top", "top", existing.Top), Get("bottom", "bottom", existing.Bottom));
}
diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs
index 0002f6d9..c772ff55 100644
--- a/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs
@@ -152,6 +152,8 @@ internal sealed class HCell
public HVerticalAlign VerticalAlign { get; set; }
public string? Fill { get; set; }
public HBorders? Borders { get; set; }
+ /// <summary>Cell-specific padding; null inherits the table's padding.</summary>
+ public HInsets? CellMargin { get; set; }
public List<HBlock> Blocks { get; } = [];
}
diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Body.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Body.cs
index d33c669b..d1abceb8 100644
--- a/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Body.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Body.cs
@@ -309,6 +309,7 @@ internal sealed partial class HwpxWriter
sb.Append("<hp:tr>");
foreach (var (cell, column) in placed[r])
{
+ var cellMargin = cell.CellMargin ?? margin;
var width = 0;
for (var i = column; i < column + cell.ColSpan && i < widths.Length; i++)
width += widths[i];
@@ -316,20 +317,20 @@ internal sealed partial class HwpxWriter
for (var i = r; i < r + cell.RowSpan && i < rowHeights.Length; i++)
height += rowHeights[i];
- _width = Math.Max(1000, width - margin.Left - margin.Right);
+ _width = Math.Max(1000, width - cellMargin.Left - cellMargin.Right);
var verticalAlign = cell.VerticalAlign switch
{
HVerticalAlign.Center => "CENTER",
HVerticalAlign.Bottom => "BOTTOM",
_ => "TOP",
};
- sb.Append($"<hp:tc name=\"\" header=\"{(r < headerRows ? 1 : 0)}\" hasMargin=\"0\" protect=\"0\" editable=\"0\" dirty=\"0\" borderFillIDRef=\"{BorderFillId(cell.Borders ?? tableBorders, cell.Fill)}\">");
+ sb.Append($"<hp:tc name=\"\" header=\"{(r < headerRows ? 1 : 0)}\" hasMargin=\"{(cell.CellMargin is not null ? 1 : 0)}\" protect=\"0\" editable=\"0\" dirty=\"0\" borderFillIDRef=\"{BorderFillId(cell.Borders ?? tableBorders, cell.Fill)}\">");
sb.Append(SubList(cell.Blocks, verticalAlign));
sb.Append($"<hp:cellAddr colAddr=\"{column}\" rowAddr=\"{r}\"/>");
sb.Append($"<hp:cellSpan colSpan=\"{cell.ColSpan}\" rowSpan=\"{cell.RowSpan}\"/>");
// Like 한글 itself: a merged cell is as tall as all the rows it spans.
sb.Append($"<hp:cellSz width=\"{width}\" height=\"{height}\"/>");
- sb.Append($"<hp:cellMargin left=\"{margin.Left}\" right=\"{margin.Right}\" top=\"{margin.Top}\" bottom=\"{margin.Bottom}\"/>");
+ sb.Append($"<hp:cellMargin left=\"{cellMargin.Left}\" right=\"{cellMargin.Right}\" top=\"{cellMargin.Top}\" bottom=\"{cellMargin.Bottom}\"/>");
sb.Append("</hp:tc>");
}
sb.Append("</hp:tr>");
diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Layout.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Layout.cs
index 8b3e574c..aafc5274 100644
--- a/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Layout.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Layout.cs
@@ -147,13 +147,14 @@ internal sealed partial class HwpxWriter
{
foreach (var (cell, column) in placed[r])
{
+ var cellMargin = cell.CellMargin ?? margin;
if ((pass == 0) != (cell.RowSpan == 1))
continue; // single-row cells first, then spans on top of them
var width = 0;
for (var i = column; i < column + cell.ColSpan && i < widths.Length; i++)
width += widths[i];
- var needed = EstimateHeight(cell.Blocks.Count > 0 ? cell.Blocks : [new HParagraph()], Math.Max(1000, width - margin.Left - margin.Right))
- + margin.Top + margin.Bottom;
+ var needed = EstimateHeight(cell.Blocks.Count > 0 ? cell.Blocks : [new HParagraph()], Math.Max(1000, width - cellMargin.Left - cellMargin.Right))
+ + cellMargin.Top + cellMargin.Bottom;
var last = Math.Min(r + cell.RowSpan, heights.Length) - 1;
var have = 0;
for (var i = r; i <= last; i++)
diff --git a/tests/Filee.Engines.Tests/DocxCellAndBulletTests.cs b/tests/Filee.Engines.Tests/DocxCellAndBulletTests.cs
new file mode 100644
index 00000000..29e3745e
--- /dev/null
+++ b/tests/Filee.Engines.Tests/DocxCellAndBulletTests.cs
@@ -0,0 +1,136 @@
+// DOCX → HWPX fidelity regressions: per-cell padding overrides table defaults, and list glyphs retain their shape.
+
+using System.Xml.Linq;
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using static Filee.Engines.Tests.DocxBuilder;
+using static Filee.Engines.Tests.HwpxAssert;
+
+namespace Filee.Engines.Tests;
+
+public class DocxCellAndBulletTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ private async Task<string> ConvertAsync(DocxBuilder docx)
+ {
+ var source = docx.Save(Path.Combine(fx.NewFolder(), "source.docx"));
+ var job = await fx.ConvertAsync([source], new Preset { TargetFormat = "hwpx" });
+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => f.ErrorDetail)));
+ var output = job.Outputs.Single();
+ ValidPackage(output, 0);
+ return output;
+ }
+
+ private static (int Left, int Right, int Top, int Bottom) Insets(XElement element) =>
+ ((int)element.Attribute("left")!, (int)element.Attribute("right")!, (int)element.Attribute("top")!, (int)element.Attribute("bottom")!);
+
+ private static string Cell(string text, string properties = "") =>
+ $"<w:tc><w:tcPr>{properties}</w:tcPr>{P(R(text))}</w:tc>";
+
+ [Fact]
+ public async Task Cell_margins_override_only_the_specified_sides_and_preserve_zero()
+ {
+ var docx = new DocxBuilder().Paragraph("""
+ <w:tbl><w:tblPr><w:tblCellMar>
+ <w:left w:w="120" w:type="dxa"/><w:right w:w="140" w:type="dxa"/>
+ <w:top w:w="40" w:type="dxa"/><w:bottom w:w="60" w:type="dxa"/>
+ </w:tblCellMar></w:tblPr><w:tblGrid><w:gridCol w:w="2000"/><w:gridCol w:w="2000"/><w:gridCol w:w="2000"/></w:tblGrid><w:tr>
+ """ + Cell("custom", "<w:tcMar><w:start w:w=\"180\" w:type=\"dxa\"/><w:top w:w=\"85\" w:type=\"dxa\"/></w:tcMar>") +
+ Cell("zero", "<w:tcMar><w:end w:w=\"60\" w:type=\"dxa\"/><w:bottom w:w=\"0\" w:type=\"dxa\"/></w:tcMar>") +
+ Cell("inherited") + "</w:tr></w:tbl>" + P(""));
+
+ var table = Xml(await ConvertAsync(docx)).Descendants(Hp + "tbl").Single();
+ var cells = table.Descendants(Hp + "tc").ToList();
+ Assert.Equal((600, 700, 200, 300), Insets(table.Element(Hp + "inMargin")!));
+ Assert.Equal((900, 700, 425, 300), Insets(cells[0].Element(Hp + "cellMargin")!));
+ Assert.Equal((600, 300, 200, 0), Insets(cells[1].Element(Hp + "cellMargin")!));
+ Assert.Equal((600, 700, 200, 300), Insets(cells[2].Element(Hp + "cellMargin")!));
+ Assert.Equal(["1", "1", "0"], cells.Select(c => (string?)c.Attribute("hasMargin")));
+ }
+
+ [Fact]
+ public async Task Cell_style_and_header_margins_are_inherited_before_direct_overrides()
+ {
+ var docx = new DocxBuilder();
+ docx.Styles += """
+ <w:style w:type="table" w:styleId="Padded"><w:name w:val="Padded"/>
+ <w:tblPr><w:tblCellMar><w:left w:w="100"/><w:right w:w="120"/><w:top w:w="20"/><w:bottom w:w="40"/></w:tblCellMar></w:tblPr>
+ <w:tcPr><w:tcMar><w:top w:w="60"/></w:tcMar></w:tcPr>
+ <w:tblStylePr w:type="firstRow"><w:tcPr><w:tcMar><w:bottom w:w="80"/></w:tcMar></w:tcPr></w:tblStylePr>
+ </w:style>
+ """;
+ docx.Paragraph("<w:tbl><w:tblPr><w:tblStyle w:val=\"Padded\"/><w:tblLook w:firstRow=\"1\"/></w:tblPr>" +
+ "<w:tblGrid><w:gridCol w:w=\"2000\"/></w:tblGrid><w:tr>" +
+ Cell("header", "<w:tcMar><w:top w:type=\"nil\"/></w:tcMar>") + "</w:tr><w:tr>" + Cell("body") + "</w:tr></w:tbl>" + P(""));
+
+ var cells = Xml(await ConvertAsync(docx)).Descendants(Hp + "tc").ToList();
+ Assert.Equal((500, 600, 0, 400), Insets(cells[0].Element(Hp + "cellMargin")!));
+ Assert.Equal((500, 600, 300, 200), Insets(cells[1].Element(Hp + "cellMargin")!));
+ Assert.All(cells, c => Assert.Equal("1", (string?)c.Attribute("hasMargin")));
+ }
+
+ [Fact]
+ public async Task Cached_row_height_includes_cell_padding()
+ {
+ var docx = new DocxBuilder().Paragraph("<w:tbl><w:tblPr/><w:tblGrid><w:gridCol w:w=\"2000\"/></w:tblGrid><w:tr>" +
+ Cell("text", "<w:tcMar><w:top w:w=\"1440\"/><w:bottom w:w=\"1440\"/></w:tcMar>") + "</w:tr></w:tbl>" + P(""));
+ var cell = Xml(await ConvertAsync(docx)).Descendants(Hp + "tc").Single();
+ Assert.True((int)cell.Element(Hp + "cellSz")!.Attribute("height")! >= 15700,
+ "One 10 pt line plus two 72 pt cell margins must fit in the cached row height.");
+ }
+
+ [Fact]
+ public async Task Header_cell_margins_inherit_each_side_from_the_base_table_style()
+ {
+ var docx = new DocxBuilder();
+ docx.Styles += """
+ <w:style w:type="table" w:styleId="Base"><w:name w:val="Base"/>
+ <w:tblPr><w:tblCellMar><w:left w:w="100"/><w:right w:w="120"/><w:top w:w="20"/><w:bottom w:w="40"/></w:tblCellMar></w:tblPr>
+ <w:tblStylePr w:type="firstRow"><w:tcPr><w:tcMar><w:top w:w="60"/></w:tcMar></w:tcPr></w:tblStylePr>
+ </w:style>
+ <w:style w:type="table" w:styleId="Derived"><w:name w:val="Derived"/><w:basedOn w:val="Base"/>
+ <w:tblStylePr w:type="firstRow"><w:tcPr><w:tcMar><w:bottom w:w="80"/></w:tcMar></w:tcPr></w:tblStylePr>
+ </w:style>
+ """;
+ docx.Paragraph("<w:tbl><w:tblPr><w:tblStyle w:val=\"Derived\"/><w:tblLook w:firstRow=\"1\"/></w:tblPr>" +
+ "<w:tblGrid><w:gridCol w:w=\"2000\"/></w:tblGrid><w:tr>" + Cell("header") + "</w:tr></w:tbl>" + P(""));
+
+ var cell = Xml(await ConvertAsync(docx)).Descendants(Hp + "tc").Single();
+ Assert.Equal((500, 600, 300, 400), Insets(cell.Element(Hp + "cellMargin")!));
+ }
+
+ [Theory]
+ [InlineData("•", "•")]
+ [InlineData("▪", "▪")]
+ [InlineData("●", "●")]
+ [InlineData("–", "–")]
+ [InlineData("\uF0B7", "•")]
+ [InlineData("\uF09F", "•")]
+ [InlineData("\uF0A7", "▪")]
+ [InlineData("\uF06E", "■")]
+ public async Task List_markers_preserve_unicode_and_normalize_known_symbol_glyphs(string input, string expected)
+ {
+ var docx = new DocxBuilder
+ {
+ Numbering = $"<w:abstractNum w:abstractNumId=\"1\"><w:lvl w:ilvl=\"0\"><w:numFmt w:val=\"bullet\"/><w:lvlText w:val=\"{input}\"/></w:lvl></w:abstractNum>" +
+ "<w:num w:numId=\"1\"><w:abstractNumId w:val=\"1\"/></w:num>",
+ };
+ docx.Paragraph(P(R("item"), "<w:numPr><w:ilvl w:val=\"0\"/><w:numId w:val=\"1\"/></w:numPr>"));
+ var head = Xml(await ConvertAsync(docx), "Contents/header.xml");
+ var numbering = head.Descendants(Hh + "numbering").Last();
+ Assert.Equal(expected, numbering.Elements(Hh + "paraHead").First().Value);
+ }
+
+ [Fact]
+ public async Task Nested_table_uses_the_outer_cells_content_width()
+ {
+ var inner = "<w:tbl><w:tblPr/><w:tr>" + Cell("inner") + "</w:tr></w:tbl>";
+ var docx = new DocxBuilder().Paragraph("<w:tbl><w:tblPr/><w:tblGrid><w:gridCol w:w=\"4000\"/></w:tblGrid><w:tr>" +
+ "<w:tc><w:tcPr><w:tcMar><w:left w:w=\"600\"/><w:right w:w=\"400\"/></w:tcMar></w:tcPr>" + inner + P("") +
+ "</w:tc></w:tr></w:tbl>" + P(""));
+
+ var outer = Xml(await ConvertAsync(docx)).Descendants(Hp + "tbl").First();
+ var nested = outer.Descendants(Hp + "tbl").Single();
+ // 4000 twips of cell width minus 600 + 400 twips of cell padding, at 5 HWPUNIT per twip.
+ Assert.Equal(15000, (int)nested.Element(Hp + "sz")!.Attribute("width")!);
+ }
+}
diff --git a/tests/Filee.Engines.Tests/DocxToHwpxTests.cs b/tests/Filee.Engines.Tests/DocxToHwpxTests.cs
index a972d884..79633152 100644
--- a/tests/Filee.Engines.Tests/DocxToHwpxTests.cs
+++ b/tests/Filee.Engines.Tests/DocxToHwpxTests.cs
@@ -160,7 +160,7 @@ public class DocxToHwpxTests(EngineFixture fx) : IClassFixture<EngineFixture>
var levels = numbering.Elements(Hh + "paraHead").Take(2).Select(h => ((string?)h.Attribute("numFormat"), h.Value)).ToList();
Assert.Equal([("DIGIT", "^1."), ("HANGUL_SYLLABLE", "^2)")], levels);
var bullet = ParaPr(ParagraphWith(section, "글머리 항목")).Element(Hh + "heading")!;
- Assert.Equal("●", head.Descendants(Hh + "numbering").Single(n => (string?)n.Attribute("id") == (string?)bullet.Attribute("idRef")).Elements(Hh + "paraHead").First().Value);
+ Assert.Equal("•", head.Descendants(Hh + "numbering").Single(n => (string?)n.Attribute("id") == (string?)bullet.Attribute("idRef")).Elements(Hh + "paraHead").First().Value);
// Runs split by Word but formatted alike become one text run.
Assert.Contains(section.Descendants(Hp + "t"), t => t.Value == "2016-06-15");