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.
C# audio-converteravaloniabatch-conversionconvertercsharpdocument-converterdocx-to-pdfdotnetdrag-and-dropfile-conversionfile-converterheic-converterhwphwpximage-converterlinuxmacospdf-convertervideo-converterwindows
HWPX copy for rhwp: laid-out shape sizes, spaced equation commands, Cambria Math when needed
KnifeLemon78e88a60436d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5b166faa..26a401ad 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,6 +23,13 @@ find it, what it does and doesn't do.Korean fonts, so Chinese text mixed two fonts character by character. Chinese (Simplified or Traditional) andJapanese text now gets a Chinese or Japanese font already on the computer (e.g. Microsoft YaHei), and text in otherscripts (Russian, Greek, Thai, Arabic, …) a font that has all its characters. Filee does not download or ship fonts.+- **한글 boxes and equations in PDFs** (issue #65). In HWP / HWPX → PDF:+ - Boxes inside a text box (the "보기" box of an exam paper) came out narrow, with their content clipped and pictures+ shrunk. They now have the size 한글 shows.+ - Equations written in 한글 2022 showed commands as text ("fCIRCf", "ASMALLINTERB", "lek", "rootx") and != or +-+ instead of ≠ and ±. They now show ∘, ∩, ⊂, ≤, √, ≠ and ±.+ - When the computer has no font with the equation symbols (∪, ∈, ⊂, …), Cambria Math, which comes with Windows,+ draws the equations.## 1.10.2diff --git a/src/Filee.Engines/Hwp/RhwpConverter.cs b/src/Filee.Engines/Hwp/RhwpConverter.csindex 772d4e09..38928013 100644--- a/src/Filee.Engines/Hwp/RhwpConverter.cs+++ b/src/Filee.Engines/Hwp/RhwpConverter.cs@@ -35,11 +35,10 @@ public sealed class RhwpConverter : IConverter{var exe = _exe ?? Locate() ?? throw new InvalidOperationException("rhwp was not found.");var temp = Path.Combine(step.WorkDirectory, $"rhwp-{Guid.NewGuid():N}.{step.To}");- // Fonts rhwp cannot embed are swapped for installed ones in a copy (a CFF2 variable font left pages blank).- var input = step.To == "pdf" && step.From == "hwpx" ? RhwpFonts.Prepare(step.InputPath, step.WorkDirectory) ?? step.InputPath : step.InputPath;+ var input = step.To == "pdf" ? await PrepareAsync(exe, step, cancellationToken) : step.InputPath;string[] arguments = step.To switch{- "pdf" => ["export-pdf", input, "-o", temp],+ "pdf" => ["export-pdf", input, "-o", temp, .. RhwpInput.PdfOptions()],"hwpx" => ["export-hwpx", step.InputPath, temp],"hwp" => ["convert", step.InputPath, temp],_ => throw new NotSupportedException(step.To),@@ -60,6 +59,24 @@ public sealed class RhwpConverter : IConverterreturn [target];}+ /// <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.+ /// </summary>+ private static async Task<string> PrepareAsync(string exe, ConversionStep step, CancellationToken cancellationToken)+ {+ var hwpx = step.InputPath;+ if (step.From == "hwp")+ {+ hwpx = Path.Combine(step.WorkDirectory, $"rhwp-{Guid.NewGuid():N}.hwpx");+ await ProcessRunner.RunAsync(exe, ["export-hwpx", step.InputPath, hwpx], Timeout, cancellationToken);+ if (!File.Exists(hwpx) || new FileInfo(hwpx).Length == 0)+ return step.InputPath;+ }+ return RhwpInput.Prepare(hwpx, step.WorkDirectory) ?? step.InputPath;+ }+/// <summary>Filee's own copy (engines/rhwp), never one found elsewhere on the system.</summary>private static string? Locate() =>EngineEnvironment.FindBundled("rhwp") is { } bundleddiff --git a/src/Filee.Engines/Hwp/RhwpFonts.cs b/src/Filee.Engines/Hwp/RhwpFonts.csindex fbcd76ee..c3056c4c 100644--- a/src/Filee.Engines/Hwp/RhwpFonts.cs+++ b/src/Filee.Engines/Hwp/RhwpFonts.cs@@ -1,4 +1,5 @@-// Fonts for rhwp, chosen from the fonts installed on the computer. Nothing is downloaded or shipped.+// Fonts for rhwp, chosen from the fonts installed on the computer (RhwpInput writes them into a copy of the HWPX).+// Nothing is downloaded or shipped.//// - Language: documents Filee writes (Markdown, text, HTML → HWPX) name Korean fonts in every slot. In a Chinese or// Japanese document those drew Korean-style Hanja and, for characters they lack, a different fallback font per@@ -14,8 +15,6 @@using System.Collections.Concurrent;using System.Globalization;using System.Text;-using System.IO.Compression;-using System.Xml.Linq;using SkiaSharp;namespace Filee.Engines.Hwp;@@ -56,59 +55,6 @@ internal static class RhwpFontsprivate static readonly ConcurrentDictionary<string, InstalledFont?> Fonts = new(StringComparer.OrdinalIgnoreCase);- /// <summary>- /// A copy of the HWPX in <paramref name="workDirectory"/> naming better fonts, or null when every font is fine (or- /// the file is not an HWPX package).- /// </summary>- /// <param name="lookup">The installed font with a name, or null (tests pass a fake computer).</param>- public static string? Prepare(string hwpx, string workDirectory, Func<string, InstalledFont?>? lookup = null)- {- try- {- XDocument header;- var text = new StringBuilder();- using (var zip = ZipFile.OpenRead(hwpx))- {- if (zip.GetEntry("Contents/header.xml") is not { } entry)- return null;- using (var stream = entry.Open())- header = XDocument.Load(stream);- foreach (var section in zip.Entries.Where(e => e.FullName.StartsWith("Contents/section", StringComparison.Ordinal)))- {- using var stream = section.Open();- foreach (var t in XDocument.Load(stream).Descendants().Where(e => e.Name.LocalName == "t"))- if (text.Length < 200_000)- text.Append(t.Value);- }- }-- var fonts = header.Descendants()- .Where(e => e.Name.LocalName == "font" && e.Attribute("face") is not null && e.Parent?.Name.LocalName == "fontface")- .Select(e => (Element: e, Slot: (string?)e.Parent!.Attribute("lang") ?? "", Face: (string)e.Attribute("face")!))- .ToList();- var plan = Plan(fonts.Select(f => (f.Slot, f.Face)).ToList(), text.ToString(), lookup ?? Find);- if (plan.Count == 0)- return null;- foreach (var font in fonts)- if (plan.TryGetValue((font.Slot, font.Face), out var replacement))- font.Element.SetAttributeValue("face", replacement);-- var copy = Path.Combine(workDirectory, $"rhwp-fonts-{Guid.NewGuid():N}.hwpx");- File.Copy(hwpx, copy);- using (var zip = ZipFile.Open(copy, ZipArchiveMode.Update))- {- zip.GetEntry("Contents/header.xml")!.Delete();- using var stream = zip.CreateEntry("Contents/header.xml", CompressionLevel.Optimal).Open();- header.Save(stream, SaveOptions.DisableFormatting);- }- return copy;- }- catch (Exception ex) when (ex is InvalidDataException or System.Xml.XmlException)- {- return null; // not a package Filee can read: rhwp reports the problem itself- }- }-/// <summary>Replacements by (slot, face): the language, coverage and CFF2 rules above.</summary>internal static Dictionary<(string Slot, string Face), string> Plan(IReadOnlyList<(string Slot, string Face)> slots, string text, Func<string, InstalledFont?> lookup)diff --git a/src/Filee.Engines/Hwp/RhwpInput.cs b/src/Filee.Engines/Hwp/RhwpInput.csnew file mode 100644index 00000000..690931d8--- /dev/null+++ b/src/Filee.Engines/Hwp/RhwpInput.cs@@ -0,0 +1,218 @@+// What Filee changes in an HWPX before rhwp renders it to PDF, in a copy (the user's file is never touched):+//+// - Fonts (RhwpFonts): installed fonts for the text's language and characters, no CFF2 variable fonts (#61, #64).+// - Shape sizes: a box inside a text box stores its size relative to the column (hp:sz widthRelTo="COLUMN", 9920 =+// 99.2 %); rhwp takes the number as absolute there and drew the exam paper's "보기" boxes 35 mm wide with their+// 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.+//+// 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.++using System.IO.Compression;+using System.Text;+using System.Text.RegularExpressions;+using System.Xml.Linq;++namespace Filee.Engines.Hwp;++internal static partial class RhwpInput+{+ /// <summary>Equation commands 한글 separates from a following identifier (found in 한글 2022 documents).</summary>+ private static readonly string[] UpperCommands =+ [+ "CIRC", "SMALLINTER", "SMALLUNION", "SUBSET", "SUPERSET", "IN", "NOTIN", "OWNS", "INTER", "UNION", "APPROX",+ "EQUIV", "CONG", "DIV", "PLUSMINUS", "MINUSPLUS", "CDOT", "BULLET", "OPLUS", "FORALL", "EXIST", "THEREFORE",+ "BECAUSE", "DEG", "INF", "PARTIAL", "RARROW", "LARROW", "LRARROW", "EMPTYSET", "PROPTO",+ ];++ /// <summary>Lowercase commands: only split before one or two letters or digits ("lek", "le28", "rootxy").</summary>+ private static readonly string[] LowerCommands =+ ["le", "ge", "root", "sqrt", "circ", "subset", "superset", "in", "notin", "approx", "equiv", "div", "pm", "mp", "cdot"];++ /// <summary>Longer commands that start like one of the above and stay whole.</summary>+ private static readonly HashSet<string> Whole = new(StringComparer.Ordinal)+ {+ "left", "leq", "geq", "int", "inf", "inter", "cdots", "CDOTS", "SUBSETEQ", "SUPSETEQ", "INTER", "INF", "NOTIN",+ "notin", "pmatrix", "LEFT", "RIGHT", "LEQ", "GEQ", "INT", "INFTY", "infty", "DIVIDE",+ };++ private static readonly (string Text, string Command)[] Operators =+ [("!=", " NEQ "), ("<=", " LEQ "), (">=", " GEQ "), ("+-", " PLUSMINUS "), ("-+", " MINUSPLUS ")];++ private static readonly string[] SizedObjects =+ ["rect", "ellipse", "arc", "polygon", "curve", "line", "connectLine", "container", "pic", "ole", "textart"];++ /// <summary>+ /// A copy of the HWPX in <paramref name="workDirectory"/> with the changes above, or null when nothing needs+ /// changing (or the file is not an HWPX package Filee can read).+ /// </summary>+ /// <param name="lookup">Installed fonts by name (tests pass a fake computer).</param>+ public static string? Prepare(string hwpx, string workDirectory, Func<string, InstalledFont?>? lookup = null)+ {+ try+ {+ var changed = new Dictionary<string, XDocument>(StringComparer.Ordinal);+ XDocument? header = null;+ var sections = new List<(string Name, XDocument Xml)>();+ using (var zip = ZipFile.OpenRead(hwpx))+ {+ if (zip.GetEntry("Contents/header.xml") is not { } entry)+ return null;+ header = Load(entry);+ 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)));+ }++ var text = new StringBuilder();+ foreach (var (_, xml) in sections)+ foreach (var t in xml.Descendants().Where(e => e.Name.LocalName == "t"))+ if (text.Length < 200_000)+ text.Append(t.Value);+ if (ApplyFonts(header, text.ToString(), lookup ?? RhwpFonts.Find))+ changed["Contents/header.xml"] = header;++ foreach (var (name, xml) in sections)+ if (FixShapeSizes(xml) | NormaliseEquations(xml))+ changed[name] = xml;+ if (changed.Count == 0)+ return null;++ var copy = Path.Combine(workDirectory, $"rhwp-{Guid.NewGuid():N}.hwpx");+ File.Copy(hwpx, copy);+ using (var zip = ZipFile.Open(copy, ZipArchiveMode.Update))+ foreach (var (name, xml) in changed)+ {+ zip.GetEntry(name)!.Delete();+ using var stream = zip.CreateEntry(name, CompressionLevel.Optimal).Open();+ xml.Save(stream, SaveOptions.DisableFormatting);+ }+ return copy;+ }+ catch (Exception ex) when (ex is InvalidDataException or System.Xml.XmlException)+ {+ return null; // not a package Filee can read: rhwp reports the problem itself+ }+ }++ /// <summary>+ /// Options for <c>rhwp export-pdf</c>: Cambria Math for equations when none of the fonts rhwp draws their symbols+ /// with is installed.+ /// </summary>+ public static IReadOnlyList<string> PdfOptions(Func<string, InstalledFont?>? lookup = null)+ {+ lookup ??= RhwpFonts.Find;+ var hasSymbols = new[] { "Latin Modern Math", "STIX Two Math", "Arial Unicode MS" }.Any(f => lookup(f) is { Usable: true });+ return !hasSymbols && lookup("Cambria Math") is { Usable: true } ? ["--equation-font", "Cambria Math"] : [];+ }++ private static XDocument Load(ZipArchiveEntry entry)+ {+ using var stream = entry.Open();+ return XDocument.Load(stream, LoadOptions.PreserveWhitespace); // spaces in hp:t are text+ }++ private static bool ApplyFonts(XDocument header, string text, Func<string, InstalledFont?> lookup)+ {+ var fonts = header.Descendants()+ .Where(e => e.Name.LocalName == "font" && e.Attribute("face") is not null && e.Parent?.Name.LocalName == "fontface")+ .Select(e => (Element: e, Slot: (string?)e.Parent!.Attribute("lang") ?? "", Face: (string)e.Attribute("face")!))+ .ToList();+ var plan = RhwpFonts.Plan(fonts.Select(f => (f.Slot, f.Face)).ToList(), text, lookup);+ foreach (var font in fonts)+ if (plan.TryGetValue((font.Slot, font.Face), out var replacement))+ font.Element.SetAttributeValue("face", replacement);+ return plan.Count > 0;+ }++ /// <summary>+ /// Writes the laid-out size (hp:curSz) of objects sized relative to the column, paragraph or page as their absolute+ /// size. True when something changed.+ /// </summary>+ internal static bool FixShapeSizes(XDocument section)+ {+ var changed = false;+ foreach (var shape in section.Descendants().Where(e => SizedObjects.Contains(e.Name.LocalName)))+ {+ var size = shape.Elements().FirstOrDefault(e => e.Name.LocalName == "sz");+ var current = shape.Elements().FirstOrDefault(e => e.Name.LocalName == "curSz");+ if (size is null || current is null)+ continue;+ var relative = (string?)size.Attribute("widthRelTo") is { } w && w != "ABSOLUTE"+ || (string?)size.Attribute("heightRelTo") is { } h && h != "ABSOLUTE";+ if (!relative || !int.TryParse((string?)current.Attribute("width"), out var width) || width <= 0+ || !int.TryParse((string?)current.Attribute("height"), out var height) || height <= 0)+ continue;+ size.SetAttributeValue("width", width);+ size.SetAttributeValue("height", height);+ size.SetAttributeValue("widthRelTo", "ABSOLUTE");+ size.SetAttributeValue("heightRelTo", "ABSOLUTE");+ changed = true;+ }+ return changed;+ }++ private static bool NormaliseEquations(XDocument section)+ {+ var changed = false;+ foreach (var script in section.Descendants().Where(e => e.Name.LocalName == "script" && e.Parent?.Name.LocalName == "equation"))+ {+ var normalised = NormaliseEquation(script.Value);+ if (normalised != script.Value)+ {+ script.Value = normalised;+ changed = true;+ }+ }+ return changed;+ }++ /// <summary>+ /// The script as rhwp reads it: commands glued to the next identifier spaced ("f CIRCf" → "f CIRC f"), and !=, +-+ /// written as NEQ, PLUSMINUS. Quoted text stays as it is.+ /// </summary>+ internal static string NormaliseEquation(string script)+ {+ var parts = script.Split('"');+ for (var i = 0; i < parts.Length; i += 2) // odd parts are inside quotes+ {+ var part = Identifier().Replace(parts[i], m => Split(m.Value));+ foreach (var (text, command) in Operators)+ part = part.Replace(text, command, StringComparison.Ordinal);+ parts[i] = part;+ }+ return string.Join('"', parts);+ }++ private static string Split(string identifier)+ {+ var words = new List<string>();+ while (true)+ {+ if (Whole.Contains(identifier))+ {+ words.Add(identifier);+ break;+ }+ var command = UpperCommands.Where(c => identifier.StartsWith(c, StringComparison.Ordinal)).MaxBy(c => c.Length);+ if (command is null)+ {+ var lower = LowerCommands.Where(c => identifier.StartsWith(c, StringComparison.Ordinal)).MaxBy(c => c.Length);+ var rest = lower is null ? "" : identifier[lower.Length..];+ command = rest.Length > 0 && (rest.Length <= 2 || rest.All(char.IsAsciiDigit)) ? lower : null;+ }+ if (command is null || command.Length == identifier.Length || Whole.Any(w => identifier.StartsWith(w, StringComparison.Ordinal) && w.Length > command.Length))+ {+ words.Add(identifier);+ break;+ }+ words.Add(command);+ identifier = identifier[command.Length..];+ }+ return string.Join(' ', words);+ }++ [GeneratedRegex("[A-Za-z][A-Za-z0-9]*")]+ private static partial Regex Identifier();+}diff --git a/tests/Filee.Engines.Tests/RhwpFontsTests.cs b/tests/Filee.Engines.Tests/RhwpFontsTests.csindex 1fd2b98e..d71c7e64 100644--- a/tests/Filee.Engines.Tests/RhwpFontsTests.cs+++ b/tests/Filee.Engines.Tests/RhwpFontsTests.cs@@ -108,7 +108,7 @@ public class RhwpFontsTests(EngineFixture fx) : IClassFixture<EngineFixture>var faces = Faces(hwpx);var broken = faces.First();- var copy = RhwpFonts.Prepare(hwpx, dir, face => face == broken+ var copy = RhwpInput.Prepare(hwpx, dir, face => face == broken? new InstalledFont(false, _ => true): face == "Malgun Gothic" ? new InstalledFont(true, _ => true) : null);@@ -118,7 +118,7 @@ public class RhwpFontsTests(EngineFixture fx) : IClassFixture<EngineFixture>Assert.Equal(faces, Faces(hwpx)); // the original is untouchedusing (var zip = ZipFile.OpenRead(copy))Assert.Equal("mimetype", zip.Entries[0].FullName); // still a valid HWPX package- Assert.Null(RhwpFonts.Prepare(hwpx, dir, _ => new InstalledFont(true, _ => true))); // nothing to replace: no copy+ Assert.Null(RhwpInput.Prepare(hwpx, dir, _ => new InstalledFont(true, _ => true))); // nothing to replace: no copy}private static List<string> Faces(string hwpx)diff --git a/tests/Filee.Engines.Tests/RhwpInputTests.cs b/tests/Filee.Engines.Tests/RhwpInputTests.csnew file mode 100644index 00000000..96955d55--- /dev/null+++ b/tests/Filee.Engines.Tests/RhwpInputTests.cs@@ -0,0 +1,63 @@+// What Filee fixes in an HWPX copy before rhwp renders it (issue #65: an exam paper written in 한글 2022).++using System.Xml.Linq;+using Filee.Engines.Hwp;++namespace Filee.Engines.Tests;++public class RhwpInputTests+{+ [Theory]+ [InlineData("f ^{2} = f CIRCf", "f ^{2} = f CIRC f")]+ [InlineData("n(A SMALLINTERB)", "n(A SMALLINTER B)")]+ [InlineData("A SUBSETB", "A SUBSET B")]+ [InlineData("1 lek le28", "1 le k le 28")]+ [InlineData("rootx + rootxy", "root x + root xy")]+ [InlineData("P CUP Q!=U", "P CUP Q NEQ U")]+ [InlineData("4 +- root 6", "4 PLUSMINUS root 6")]+ public void Commands_glued_to_the_next_letter_are_spaced(string script, string expected)+ {+ Assert.Equal(expected, RhwpInput.NormaliseEquation(script));+ }++ [Theory]+ [InlineData("left ( x right ) leq 3")]+ [InlineData("index line inside lemma")] // words, not commands+ [InlineData("\"CIRCf != x\" + y")] // quoted text is literal+ [InlineData("x SUBSETEQ y")]+ public void Commands_and_words_that_are_whole_stay(string script)+ {+ Assert.Equal(script, RhwpInput.NormaliseEquation(script));+ }++ [Fact]+ public void Shapes_sized_relative_to_the_column_get_their_laid_out_size()+ {+ // A "보기" box inside a text box: 9920 means 99.2 % of the column, which rhwp read as 9920 HWPUNIT.+ XNamespace hp = "http://www.hancom.co.kr/hwpml/2011/paragraph";+ var section = new XDocument(new XElement(hp + "sec",+ new XElement(hp + "rect",+ new XElement(hp + "sz", new XAttribute("width", 9920), new XAttribute("widthRelTo", "COLUMN"), new XAttribute("height", 3206), new XAttribute("heightRelTo", "ABSOLUTE")),+ new XElement(hp + "curSz", new XAttribute("width", 23053), new XAttribute("height", 24841))),+ new XElement(hp + "pic",+ new XElement(hp + "sz", new XAttribute("width", 5000), new XAttribute("widthRelTo", "ABSOLUTE"), new XAttribute("height", 4000), new XAttribute("heightRelTo", "ABSOLUTE")),+ new XElement(hp + "curSz", new XAttribute("width", 6000), new XAttribute("height", 4800)))));++ Assert.True(RhwpInput.FixShapeSizes(section));++ var sizes = section.Descendants(hp + "sz").ToList();+ Assert.Equal(("23053", "24841", "ABSOLUTE", "ABSOLUTE"),+ ((string)sizes[0].Attribute("width")!, (string)sizes[0].Attribute("height")!, (string)sizes[0].Attribute("widthRelTo")!, (string)sizes[0].Attribute("heightRelTo")!));+ Assert.Equal("5000", (string)sizes[1].Attribute("width")!); // absolute sizes are left alone+ Assert.False(RhwpInput.FixShapeSizes(section)); // nothing left to fix+ }++ [Fact]+ public void Cambria_math_draws_equations_only_when_no_symbol_font_is_installed()+ {+ static InstalledFont Font() => new(true, _ => true);+ Assert.Equal(["--equation-font", "Cambria Math"], RhwpInput.PdfOptions(name => name == "Cambria Math" ? Font() : null));+ Assert.Empty(RhwpInput.PdfOptions(name => name is "Cambria Math" or "Arial Unicode MS" ? Font() : null));+ Assert.Empty(RhwpInput.PdfOptions(_ => null));+ }+}