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.

HWP → PDF: tables floating in a table cell stay where 한글 puts them (#49)

KnifeLemond9fe0dc4bd7d
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 6ed4dc63..439c4d4d 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -615,6 +615,12 @@ built-in routes always win where they exist.
rhwp converts between the two 한글 formats without Hancom Office (`export-hwpx` and `convert`). Anything → HWP goes
through the HWPX writer and then rhwp.
+For HWP / HWPX → PDF, rhwp renders a copy of the HWPX (an HWP is exported with `export-hwpx` first) when Filee has to
+change something for it (`Hwp/RhwpInput.cs`): fonts that are installed, the laid-out size of boxes sized relative to
+the column, spaced equation commands, and, in an HWPX exported from an HWP (rhwp's `META-INF/rhwp-hwp5-origin`
+marker), the stored line of a cell paragraph that holds only a floating table moved up to the paragraph's top, so the
+table is not drawn over the paragraphs below it (#49).
+
## Archives
The archive engine (`Archives/ArchiveConverter.cs`, id `archive`) uses Filee's own copy of the 7-Zip console program
diff --git a/src/Filee.Engines/Hwp/RhwpConverter.cs b/src/Filee.Engines/Hwp/RhwpConverter.cs
index 38928013..a1a69756 100644
--- a/src/Filee.Engines/Hwp/RhwpConverter.cs
+++ b/src/Filee.Engines/Hwp/RhwpConverter.cs
@@ -61,8 +61,8 @@ public sealed class RhwpConverter : IConverter
/// <summary>
/// The document rhwp renders: a copy with the fixes of <see cref="RhwpInput"/> (fonts, shape sizes, equation
- /// scripts) when it needs any, else the original. An HWP is read through an HWPX copy for that, and used as it is
- /// when nothing needs fixing or the HWPX copy fails.
+ /// scripts, tables floating in cells) when it needs any, else the original. An HWP is read through an HWPX copy for
+ /// that, and used as it is when nothing needs fixing or the HWPX copy fails.
/// </summary>
private static async Task<string> PrepareAsync(string exe, ConversionStep step, CancellationToken cancellationToken)
{
diff --git a/src/Filee.Engines/Hwp/RhwpInput.cs b/src/Filee.Engines/Hwp/RhwpInput.cs
index 690931d8..65945fe4 100644
--- a/src/Filee.Engines/Hwp/RhwpInput.cs
+++ b/src/Filee.Engines/Hwp/RhwpInput.cs
@@ -6,6 +6,13 @@
// pictures shrunk to a few pixels (#65). The size 한글 laid the object out at (hp:curSz) is written instead.
// - Equation scripts: 한글 2022 saves a command glued to the next letter ("f CIRCf", "A SMALLINTERB", "lek", "rootx")
// and writes != and +- for ≠ and ±. rhwp printed those as italic text ("fCIRCf"); they are spaced and spelled out.
+// - Tables floating in a table cell, in an HWPX rhwp exported from an HWP (#49): 한글 stores the line of the paragraph
+// that anchors a table (hp:pos vertRelTo="PARA", text above and below it) under the table. rhwp follows the stored
+// lines of an HWP (it reads the HWP itself and an HWPX with its META-INF/rhwp-hwp5-origin marker that way) and, in
+// a cell taller than its text, drew the table from that line instead of the paragraph's top, over the paragraphs
+// below. The same document saved as HWPX by 한글 (no marker) came out right. When the anchor paragraph has no
+// text, its line is moved up to the paragraph's top (the line minus the table's offset, margins and height):
+// nothing is drawn on it, and rhwp then puts the table where 한글 does.
//
// rhwp's equation fonts are Latin Modern Math, STIX Two and Times New Roman; without the first two or Arial Unicode MS
// (which Office installs) ∪ ∈ ⊂ ∘ ∼ came out empty, so Cambria Math (part of Windows) is asked for then.
@@ -41,6 +48,9 @@ internal static partial class RhwpInput
private static readonly (string Text, string Command)[] Operators =
[("!=", " NEQ "), ("<=", " LEQ "), (">=", " GEQ "), ("+-", " PLUSMINUS "), ("-+", " MINUSPLUS ")];
+ /// <summary>The entry rhwp's <c>export-hwpx</c> adds to an HWPX it wrote for an HWP file.</summary>
+ internal const string Hwp5OriginMarker = "META-INF/rhwp-hwp5-origin";
+
private static readonly string[] SizedObjects =
["rect", "ellipse", "arc", "polygon", "curve", "line", "connectLine", "container", "pic", "ole", "textart"];
@@ -56,11 +66,13 @@ internal static partial class RhwpInput
var changed = new Dictionary<string, XDocument>(StringComparer.Ordinal);
XDocument? header = null;
var sections = new List<(string Name, XDocument Xml)>();
+ bool fromHwp;
using (var zip = ZipFile.OpenRead(hwpx))
{
if (zip.GetEntry("Contents/header.xml") is not { } entry)
return null;
header = Load(entry);
+ fromHwp = zip.GetEntry(Hwp5OriginMarker) is not null;
foreach (var section in zip.Entries.Where(e => e.FullName.StartsWith("Contents/section", StringComparison.Ordinal) && e.FullName.EndsWith(".xml", StringComparison.Ordinal)))
sections.Add((section.FullName, Load(section)));
}
@@ -74,7 +86,7 @@ internal static partial class RhwpInput
changed["Contents/header.xml"] = header;
foreach (var (name, xml) in sections)
- if (FixShapeSizes(xml) | NormaliseEquations(xml))
+ if (FixShapeSizes(xml) | NormaliseEquations(xml) | (fromHwp && AnchorTablesInCells(xml)))
changed[name] = xml;
if (changed.Count == 0)
return null;
@@ -153,6 +165,46 @@ internal static partial class RhwpInput
return changed;
}
+ /// <summary>
+ /// In table cells: moves the stored line of a paragraph that holds nothing but one floating table (vertRelTo="PARA",
+ /// top aligned, text above and below) from under the table up to the paragraph's top. Only when the line is where
+ /// 한글 puts it, below the table. True when something changed.
+ /// </summary>
+ internal static bool AnchorTablesInCells(XDocument section)
+ {
+ var changed = false;
+ foreach (var paragraph in section.Descendants().Where(e => e.Name.LocalName == "p" && e.Parent is { Name.LocalName: "subList", Parent.Name.LocalName: "tc" }))
+ {
+ var content = paragraph.Elements().Where(e => e.Name.LocalName == "run").SelectMany(r => r.Elements()).ToList();
+ if (content.Where(e => e.Name.LocalName != "t").ToList() is not [{ Name.LocalName: "tbl" } table]
+ || content.Any(e => e.Name.LocalName == "t" && !string.IsNullOrWhiteSpace(e.Value))
+ || Child(paragraph, "linesegarray")?.Elements().ToList() is not [{ } line]
+ || Child(table, "pos") is not { } pos || Child(table, "sz") is not { } size
+ || (string?)table.Attribute("textWrap") != "TOP_AND_BOTTOM" || (string?)pos.Attribute("treatAsChar") != "0"
+ || (string?)pos.Attribute("vertRelTo") != "PARA" || (string?)pos.Attribute("vertAlign") is { } align && align != "TOP"
+ || Number(line, "vertpos") is not { } vertpos || Number(pos, "vertOffset") is not { } offset || Number(size, "height") is not { } height)
+ continue;
+
+ var margin = Child(table, "outMargin");
+ var top = vertpos - offset - height - (Number(margin, "top") ?? 0) - (Number(margin, "bottom") ?? 0);
+ // The previous paragraph's last line ends above the anchor paragraph: otherwise the line was not under the table.
+ var previous = paragraph.ElementsBeforeSelf().LastOrDefault(e => e.Name.LocalName == "p");
+ var above = Child(previous, "linesegarray")?.Elements().LastOrDefault() is { } last
+ ? (Number(last, "vertpos") ?? 0) + (Number(last, "vertsize") ?? 0)
+ : 0;
+ if (top < above || top >= vertpos)
+ continue;
+ line.SetAttributeValue("vertpos", top);
+ changed = true;
+ }
+ return changed;
+ }
+
+ private static XElement? Child(XElement? element, string name) => element?.Elements().FirstOrDefault(e => e.Name.LocalName == name);
+
+ private static int? Number(XElement? element, string attribute) =>
+ int.TryParse((string?)element?.Attribute(attribute), out var value) ? value : null;
+
private static bool NormaliseEquations(XDocument section)
{
var changed = false;
diff --git a/tests/Filee.Engines.Tests/RhwpInputTests.cs b/tests/Filee.Engines.Tests/RhwpInputTests.cs
index 96955d55..e01c31dd 100644
--- a/tests/Filee.Engines.Tests/RhwpInputTests.cs
+++ b/tests/Filee.Engines.Tests/RhwpInputTests.cs
@@ -1,12 +1,26 @@
-// What Filee fixes in an HWPX copy before rhwp renders it (issue #65: an exam paper written in 한글 2022).
+// What Filee fixes in an HWPX copy before rhwp renders it (issue #65: an exam paper written in 한글 2022; issue #49:
+// a table floating in a table cell of an HWP file).
+using System.IO.Compression;
using System.Xml.Linq;
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
using Filee.Engines.Hwp;
+using UglyToad.PdfPig;
namespace Filee.Engines.Tests;
-public class RhwpInputTests
+public class RhwpInputTests(EngineFixture fx) : IClassFixture<EngineFixture>
{
+ private static readonly XNamespace Hp = "http://www.hancom.co.kr/hwpml/2011/paragraph";
+ private static readonly XNamespace Hs = "http://www.hancom.co.kr/hwpml/2011/section";
+
+ // The form of #49: in a table cell taller than its text, "Title", a paragraph holding only a table that floats 500
+ // below the paragraph's top (three rows of 2000, outer margins 141) and "After". Paragraphs are 2800 apart.
+ private const int Step = 2800, Offset = 500, RowHeight = 2000, Rows = 3, Margin = 141, OuterHeight = 30_000;
+ private const int AnchorTop = Step;
+ private const int UnderTable = AnchorTop + Offset + Margin + Rows * RowHeight + Margin; // where 한글 stores the line
+
[Theory]
[InlineData("f ^{2} = f CIRCf", "f ^{2} = f CIRC f")]
[InlineData("n(A SMALLINTERB)", "n(A SMALLINTER B)")]
@@ -52,6 +66,69 @@ public class RhwpInputTests
Assert.False(RhwpInput.FixShapeSizes(section)); // nothing left to fix
}
+ [Fact]
+ public void A_table_floating_in_a_cell_is_drawn_from_the_top_of_its_paragraph()
+ {
+ var section = new XDocument(new XElement(Hs + "sec", Paragraph(0, Text("Before"), OuterTable(Anchor()))));
+
+ Assert.True(RhwpInput.AnchorTablesInCells(section));
+
+ Assert.Equal([0, AnchorTop, UnderTable + Step], CellLines(section));
+ Assert.Equal(0, LineOf(section, "Before")); // the paragraph holding the outer table keeps its line
+ Assert.False(RhwpInput.AnchorTablesInCells(section)); // nothing left to fix
+ }
+
+ [Fact]
+ public void Paragraphs_with_text_tables_in_line_and_tables_outside_cells_keep_their_lines()
+ {
+ XDocument Cell(XElement anchor) => new(new XElement(Hs + "sec", Paragraph(0, OuterTable(anchor))));
+
+ var withText = Cell(Anchor(text: "next to the table")); // rhwp would draw the text over the table
+ var inLine = Cell(Anchor(treatAsChar: true)); // a table in the line is laid out as text
+ var notUnder = Cell(Anchor(line: AnchorTop + Offset)); // the line is not under the table
+ var outside = new XDocument(new XElement(Hs + "sec", Paragraph(0, Text("Title")), Anchor(), Paragraph(UnderTable + Step, Text("After"))));
+
+ Assert.All(new[] { withText, inLine, notUnder, outside }, section => Assert.False(RhwpInput.AnchorTablesInCells(section)));
+ Assert.Equal(UnderTable, LineOf(outside, "InnerA", anchor: true));
+ }
+
+ [Fact]
+ public async Task Only_an_hwpx_rhwp_converted_from_hwp_gets_its_tables_moved()
+ {
+ var dir = fx.NewFolder();
+ var fromHwp = await MakeFormAsync(dir, fromHwp: true);
+ var saved = await MakeFormAsync(dir, fromHwp: false);
+ static InstalledFont? AllFonts(string face) => new(true, _ => true);
+
+ // A Hancom-saved HWPX is laid out right by rhwp: nothing to change, no copy.
+ Assert.Null(RhwpInput.Prepare(saved, dir, AllFonts));
+
+ var copy = RhwpInput.Prepare(fromHwp, dir, AllFonts);
+ Assert.NotNull(copy);
+ Assert.Equal(AnchorTop, LineOf(Section(copy), "InnerA", anchor: true));
+ Assert.Equal(UnderTable, LineOf(Section(fromHwp), "InnerA", anchor: true)); // the original is untouched
+ using var zip = ZipFile.OpenRead(copy);
+ Assert.NotNull(zip.GetEntry(RhwpInput.Hwp5OriginMarker)); // rhwp still reads the rest like the HWP it came from
+ }
+
+ [Fact]
+ public async Task The_table_floating_in_a_cell_stays_above_the_next_paragraph_in_the_pdf()
+ {
+ var rhwp = fx.Converters.Single(c => c.Id == "rhwp");
+ Assert.SkipUnless(fx.Catalog.StatusOf(rhwp).IsAvailable, "rhwp not found (pwsh build/fetch-engines.ps1 -Only rhwp)");
+ var dir = fx.NewFolder();
+ var hwpx = await MakeFormAsync(dir, fromHwp: true);
+ var pdf = Path.Combine(dir, "form.pdf");
+
+ await rhwp.ConvertAsync(new ConversionStep(hwpx, "hwpx", "pdf", new Preset(), new HwpxAssert.FixedPath(pdf), dir), null, TestContext.Current.CancellationToken);
+
+ using var document = PdfDocument.Open(pdf);
+ var words = document.GetPage(1).GetWords().ToDictionary(w => w.Text, w => w.BoundingBox);
+ // PDF coordinates grow upwards. Before the fix the table started where "After" is, its last row below it.
+ Assert.True(words["Title"].Bottom > words["InnerA"].Top, "the table starts below the title");
+ Assert.True(words["InnerC"].Bottom > words["After"].Top, "the table ends above the next paragraph");
+ }
+
[Fact]
public void Cambria_math_draws_equations_only_when_no_symbol_font_is_installed()
{
@@ -60,4 +137,112 @@ public class RhwpInputTests
Assert.Empty(RhwpInput.PdfOptions(name => name is "Cambria Math" or "Arial Unicode MS" ? Font() : null));
Assert.Empty(RhwpInput.PdfOptions(_ => null));
}
+
+ /// <summary>
+ /// The #49 form in a package of Filee's HWPX writer: "Before", then the tall outer table. With
+ /// <paramref name="fromHwp"/> it carries the marker rhwp's export-hwpx writes.
+ /// </summary>
+ private async Task<string> MakeFormAsync(string dir, bool fromHwp)
+ {
+ var folder = Directory.CreateDirectory(Path.Combine(dir, fromHwp ? "from-hwp" : "saved")).FullName;
+ var hwpx = await fx.MakeHwpxAsync(folder);
+ using var zip = ZipFile.Open(hwpx, ZipArchiveMode.Update);
+ var entry = zip.GetEntry("Contents/section0.xml")!;
+ XDocument section;
+ using (var stream = entry.Open())
+ section = XDocument.Load(stream);
+ var setup = section.Root!.Element(Hp + "p")!.Elements(Hp + "run").First(r => r.Element(Hp + "secPr") is not null);
+ section.Root.ReplaceNodes(
+ new XElement(Hp + "p", ParagraphAttributes(), setup, Run(Text("Before")), Lines(0)),
+ new XElement(Hp + "p", ParagraphAttributes(), Run(OuterTable(Anchor())), Lines(Step, OuterHeight + 2 * Margin)));
+ entry.Delete();
+ using (var stream = zip.CreateEntry("Contents/section0.xml").Open())
+ section.Save(stream, SaveOptions.DisableFormatting);
+ if (fromHwp)
+ using (var writer = new StreamWriter(zip.CreateEntry(RhwpInput.Hwp5OriginMarker).Open()))
+ writer.Write("2:paragraph-utf16");
+ return hwpx;
+ }
+
+ /// <summary>A one-cell table in the line, as tall as a form's cell: "Title", <paramref name="anchor"/>, "After".</summary>
+ private static XElement OuterTable(XElement anchor) =>
+ Table(40_000, OuterHeight, treatAsChar: true, 0,
+ [[Paragraph(0, Text("Title")), anchor, Paragraph(UnderTable + Step, Text("After"))]]);
+
+ /// <summary>A paragraph holding the floating table, with the line where 한글 stores it unless given.</summary>
+ private static XElement Anchor(string? text = null, bool treatAsChar = false, int line = UnderTable)
+ {
+ var rows = new[] { "InnerA", "InnerB", "InnerC" }.Select(t => new[] { Paragraph(0, Text(t)) }).ToArray();
+ return Paragraph(line, Table(30_000, RowHeight, treatAsChar, Offset, rows), text is null ? null : Text(text));
+ }
+
+ /// <summary>A one-column table, its rows <paramref name="rowHeight"/> high, placed relative to its paragraph.</summary>
+ private static XElement Table(int width, int rowHeight, bool treatAsChar, int vertOffset, XElement[][] rows) =>
+ new(Hp + "tbl",
+ new XAttribute("id", 7), new XAttribute("zOrder", 0), new XAttribute("numberingType", "TABLE"),
+ new XAttribute("textWrap", "TOP_AND_BOTTOM"), new XAttribute("textFlow", "BOTH_SIDES"), new XAttribute("lock", 0),
+ new XAttribute("dropcapstyle", "None"), new XAttribute("pageBreak", "CELL"), new XAttribute("repeatHeader", 1),
+ new XAttribute("rowCnt", rows.Length), new XAttribute("colCnt", 1), new XAttribute("cellSpacing", 0),
+ new XAttribute("borderFillIDRef", 2), new XAttribute("noAdjust", 0),
+ new XElement(Hp + "sz", new XAttribute("width", width), new XAttribute("widthRelTo", "ABSOLUTE"),
+ new XAttribute("height", rows.Length * rowHeight), new XAttribute("heightRelTo", "ABSOLUTE"), new XAttribute("protect", 0)),
+ new XElement(Hp + "pos", new XAttribute("treatAsChar", treatAsChar ? 1 : 0), new XAttribute("affectLSpacing", 0),
+ new XAttribute("flowWithText", 1), new XAttribute("allowOverlap", 0), new XAttribute("holdAnchorAndSO", 0),
+ new XAttribute("vertRelTo", "PARA"), new XAttribute("horzRelTo", "COLUMN"), new XAttribute("vertAlign", "TOP"),
+ new XAttribute("horzAlign", "LEFT"), new XAttribute("vertOffset", vertOffset), new XAttribute("horzOffset", 0)),
+ Margins("outMargin"), Margins("inMargin"),
+ rows.Select((paragraphs, row) => new XElement(Hp + "tr", new XElement(Hp + "tc",
+ new XAttribute("name", ""), new XAttribute("header", 0), new XAttribute("hasMargin", 0), new XAttribute("protect", 0),
+ new XAttribute("editable", 0), new XAttribute("dirty", 0), new XAttribute("borderFillIDRef", 2),
+ new XElement(Hp + "subList", new XAttribute("id", ""), new XAttribute("textDirection", "HORIZONTAL"),
+ new XAttribute("lineWrap", "BREAK"), new XAttribute("vertAlign", "TOP"), new XAttribute("linkListIDRef", 0),
+ new XAttribute("linkListNextIDRef", 0), new XAttribute("textWidth", 0), new XAttribute("textHeight", 0),
+ new XAttribute("hasTextRef", 0), new XAttribute("hasNumRef", 0), paragraphs),
+ new XElement(Hp + "cellAddr", new XAttribute("colAddr", 0), new XAttribute("rowAddr", row)),
+ new XElement(Hp + "cellSpan", new XAttribute("colSpan", 1), new XAttribute("rowSpan", 1)),
+ new XElement(Hp + "cellSz", new XAttribute("width", width), new XAttribute("height", rowHeight)),
+ Margins("cellMargin")))));
+
+ private static XElement Margins(string name) =>
+ new(Hp + name, new XAttribute("left", Margin), new XAttribute("right", Margin), new XAttribute("top", Margin), new XAttribute("bottom", Margin));
+
+ private static XElement Paragraph(int line, params object?[] content) => new(Hp + "p", ParagraphAttributes(), Run(content), Lines(line));
+
+ private static XElement Run(params object?[] content) => new(Hp + "run", new XAttribute("charPrIDRef", 0), content);
+
+ private static object[] ParagraphAttributes() =>
+ [
+ new XAttribute("id", 0), new XAttribute("paraPrIDRef", 0), new XAttribute("styleIDRef", 0),
+ new XAttribute("pageBreak", 0), new XAttribute("columnBreak", 0), new XAttribute("merged", 0),
+ ];
+
+ private static XElement Text(string text) => new(Hp + "t", text);
+
+ /// <summary>One stored line: 1000 high (charPr 0 is 10 pt) with 800 below it (180 % line spacing).</summary>
+ private static XElement Lines(int vertpos, int height = 1000) =>
+ new(Hp + "linesegarray", new XElement(Hp + "lineseg",
+ new XAttribute("textpos", 0), new XAttribute("vertpos", vertpos), new XAttribute("vertsize", height),
+ new XAttribute("textheight", height), new XAttribute("baseline", height * 85 / 100), new XAttribute("spacing", 800),
+ new XAttribute("horzpos", 0), new XAttribute("horzsize", 45_130), new XAttribute("flags", 393_216)));
+
+ /// <summary>Stored line of the paragraph with <paramref name="text"/>, or of the paragraph anchoring its table.</summary>
+ private static int LineOf(XDocument section, string text, bool anchor = false)
+ {
+ var paragraph = section.Descendants(Hp + "p").Last(p => p.Elements(Hp + "run").Elements(Hp + "t").Any(t => t.Value == text));
+ if (anchor)
+ paragraph = paragraph.Ancestors(Hp + "p").First();
+ return (int)paragraph.Element(Hp + "linesegarray")!.Element(Hp + "lineseg")!.Attribute("vertpos")!;
+ }
+
+ /// <summary>Stored lines of the paragraphs in the outer table's cell.</summary>
+ private static List<int> CellLines(XDocument section) =>
+ section.Descendants(Hp + "subList").First().Elements(Hp + "p")
+ .Select(p => (int)p.Element(Hp + "linesegarray")!.Element(Hp + "lineseg")!.Attribute("vertpos")!).ToList();
+
+ private static XDocument Section(string hwpx)
+ {
+ using var zip = ZipFile.OpenRead(hwpx);
+ using var stream = zip.GetEntry("Contents/section0.xml")!.Open();
+ return XDocument.Load(stream);
+ }
}