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.

Chinese Word documents to PDF: WordArt, character indents, quote widths

KnifeLemon571b4b49af56
diff --git a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Drawing.cs b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Drawing.cs
index c006700c..ea9e9f7a 100644
--- a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Drawing.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Drawing.cs
@@ -373,7 +373,8 @@ internal sealed partial class DocxReader
// ───────────────────────── VML (legacy) ─────────────────────────
- private IEnumerable<HInline> Vml(XElement container)
+ /// <param name="format">Formatting of the run holding the objects (WordArt text starts from it).</param>
+ private IEnumerable<HInline> Vml(XElement container, HCharFormat format)
{
foreach (var shape in container.Elements())
{
@@ -381,7 +382,7 @@ internal sealed partial class DocxReader
continue;
if (shape.Name.LocalName == "group")
{
- foreach (var inline in Vml(shape))
+ foreach (var inline in Vml(shape, format))
yield return inline;
continue;
}
@@ -407,6 +408,21 @@ internal sealed partial class DocxReader
ReadTextBoxContent(content, box.Blocks);
yield return box;
}
+ else if (WordArt(shape, width, height, format) is { } text)
+ {
+ if (anchor is null)
+ {
+ yield return text;
+ }
+ else
+ {
+ var box = new TextBoxBuilder(width, height, anchor) { Line = HBorder.None, Padding = new HInsets(0, 0, 0, 0), VerticalAlign = HVerticalAlign.Center }.Build();
+ var paragraph = new HParagraph { Format = new HParaFormat(Align: HAlign.Center) };
+ paragraph.Inlines.Add(text);
+ box.Blocks.Add(paragraph);
+ yield return box;
+ }
+ }
else if (shape.Name.LocalName is "rect" or "roundrect" or "oval" or "line")
{
var kind = shape.Name.LocalName switch
@@ -442,6 +458,45 @@ internal sealed partial class DocxReader
}
}
+ /// <summary>
+ /// Legacy WordArt (a VML shape with v:textpath, as WPS and older Word write it) as plain text in its font and
+ /// fill colour. 한글 has no text effects, so the text keeps the run's other formatting; when the text is stretched
+ /// to the shape (fitpath / fitshape), the font size is chosen so it fills about the same box.
+ /// </summary>
+ private static HText? WordArt(XElement shape, int width, int height, HCharFormat format)
+ {
+ var path = shape.Element(V + "textpath");
+ var text = (string?)path?.Attribute("string");
+ if (path is null || (string?)path.Attribute("on") is "f" or "false" || string.IsNullOrWhiteSpace(text))
+ return null;
+
+ var font = VmlStyle((string?)path.Attribute("style"));
+ var family = font.GetValueOrDefault("font-family")?.Trim('"', '\'', ' ');
+ var size = HwpxUnits.ParseLength(font.GetValueOrDefault("font-size")) is { } points and > 0 ? points : format.Size ?? 1000;
+ var stretched = (string?)path.Attribute("fitpath") is "t" or "true" || (string?)path.Attribute("fitshape") is "t" or "true";
+ if (stretched && width > 0 && height > 0)
+ {
+ // The glyphs fill the shape: capitals and digits are about 0.72 em tall, Han characters about 0.9 em;
+ // East Asian characters are 1 em wide, others about half.
+ var wide = text.Count(c => c is >= '⺀' and <= '鿿' or >= '가' and <= '힣' or >= '＀' and <= '⦆');
+ var ems = wide + (text.Length - wide) * 0.5;
+ var byHeight = height / (wide > 0 ? 0.9 : 0.72);
+ size = (int)Math.Min(byHeight, width / Math.Max(ems, 1));
+ }
+ var color = (string?)shape.Attribute("filled") is "f" or "false"
+ ? VmlColor((string?)shape.Attribute("strokecolor"))
+ : VmlColor((string?)shape.Attribute("fillcolor"));
+ return new HText(text.Replace('\n', ' ').Replace('\r', ' '), format with
+ {
+ Size = Math.Max(size, 100),
+ Font = family ?? format.Font,
+ EastAsianFont = family ?? format.EastAsianFont,
+ Bold = font.GetValueOrDefault("font-weight") is { } weight ? weight == "bold" || int.TryParse(weight, out var w) && w >= 600 : format.Bold,
+ Italic = font.GetValueOrDefault("font-style") is { } italic ? italic == "italic" : format.Italic,
+ Color = color ?? format.Color,
+ });
+ }
+
private static string? VmlFill(XElement shape) =>
(string?)shape.Attribute("filled") is "f" or "false" ? null : VmlColor((string?)shape.Attribute("fillcolor")) ?? "#FFFFFF";
diff --git a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Styles.cs b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Styles.cs
index 709b0053..3c53af87 100644
--- a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Styles.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Styles.cs
@@ -21,6 +21,13 @@ internal sealed partial class DocxReader
{
public string? Jc;
public int? Left, Right, FirstLine, Hanging, Before, After, Line;
+
+ /// <summary>
+ /// Indents in hundredths of a character (w:leftChars ...), which Chinese and Japanese documents use. A
+ /// non-zero value wins over the twips one; "0" means the twips value counts again.
+ /// </summary>
+ public int? LeftChars, RightChars, FirstLineChars, HangingChars;
+
public string? LineRule;
public bool? KeepNext, KeepLines, PageBreakBefore, WidowControl, SnapToGrid;
public int? OutlineLevel;
@@ -46,9 +53,26 @@ internal sealed partial class DocxReader
Left = Twips(ind, "left") ?? Twips(ind, "start") ?? Left;
Right = Twips(ind, "right") ?? Twips(ind, "end") ?? Right;
if (Twips(ind, "hanging") is { } hanging)
- (Hanging, FirstLine) = (hanging, null);
+ (Hanging, FirstLine, FirstLineChars) = (hanging, null, null);
if (Twips(ind, "firstLine") is { } firstLine)
- (FirstLine, Hanging) = (firstLine, null);
+ (FirstLine, Hanging, HangingChars) = (firstLine, null, null);
+
+ if ((Twips(ind, "leftChars") ?? Twips(ind, "startChars")) is { } leftChars)
+ LeftChars = leftChars != 0 ? leftChars : null;
+ if ((Twips(ind, "rightChars") ?? Twips(ind, "endChars")) is { } rightChars)
+ RightChars = rightChars != 0 ? rightChars : null;
+ if (Twips(ind, "hangingChars") is { } hangingChars)
+ {
+ HangingChars = hangingChars != 0 ? hangingChars : null;
+ if (hangingChars != 0)
+ (FirstLine, FirstLineChars) = (null, null);
+ }
+ if (Twips(ind, "firstLineChars") is { } firstLineChars)
+ {
+ FirstLineChars = firstLineChars != 0 ? firstLineChars : null;
+ if (firstLineChars != 0)
+ (Hanging, HangingChars) = (null, null);
+ }
}
if (pPr.Element(W + "spacing") is { } spacing)
{
@@ -284,6 +308,14 @@ internal sealed partial class DocxReader
var ilvl = direct.Ilvl ?? para.Ilvl ?? 0;
if (numId is not null && _numberingLevels.TryGetValue(numId, out var levels))
para.Apply(levels[Math.Clamp(ilvl, 0, 8)].PPr);
+ // numId 0 on the paragraph itself turns numbering off, and Word then drops the indents the paragraph would
+ // inherit for the list (a style's first-line indent too): only the paragraph's own left and first-line indents
+ // count. LibreOffice does the same.
+ if (direct.NumId == "0")
+ {
+ (para.Left, para.FirstLine, para.Hanging) = (null, null, null);
+ (para.LeftChars, para.FirstLineChars, para.HangingChars) = (null, null, null);
+ }
para.Apply(pPr);
para.NumId = numId;
para.Ilvl = ilvl;
@@ -319,9 +351,17 @@ internal sealed partial class DocxReader
int.TryParse(name.AsSpan(8), out var byName) && byName is >= 1 and <= 9 ? byName : 0;
}
- private HParaFormat ParaFormat(ParaProps p)
+ /// <param name="fontSize">Font size of the paragraph (half points): one character of the *Chars indents.</param>
+ private HParaFormat ParaFormat(ParaProps p, int? fontSize)
{
- var firstLine = p.Hanging is { } hanging ? -hanging : p.FirstLine ?? 0;
+ // A character is the paragraph's font size: 10.5 pt (21 half points) = 210 twips.
+ var character = (fontSize ?? 20) * 10;
+ int? Chars(int? hundredths) => hundredths is { } value ? (int)Math.Round(value * character / 100.0) : null;
+ var left = Chars(p.LeftChars) ?? p.Left;
+ var right = Chars(p.RightChars) ?? p.Right;
+ var firstLine = Chars(p.HangingChars) is { } hangingChars ? -hangingChars
+ : Chars(p.FirstLineChars) is { } firstLineChars ? firstLineChars
+ : p.Hanging is { } hanging ? -hanging : p.FirstLine ?? 0;
HLineSpacing? lineSpacing = p.Line is not { } line ? null : p.LineRule switch
{
"exact" => new HLineSpacing(HLineSpacingKind.Fixed, HwpxUnits.FromTwips(line)),
@@ -337,8 +377,8 @@ internal sealed partial class DocxReader
"distribute" => HAlign.Distribute,
_ => HAlign.Left,
},
- Left: HwpxUnits.FromTwips(p.Left ?? 0),
- Right: HwpxUnits.FromTwips(p.Right ?? 0),
+ Left: HwpxUnits.FromTwips(left ?? 0),
+ Right: HwpxUnits.FromTwips(right ?? 0),
FirstLine: HwpxUnits.FromTwips(firstLine),
Before: HwpxUnits.FromTwips(p.Before ?? 0),
After: HwpxUnits.FromTwips(p.After ?? 0),
diff --git a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.cs b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.cs
index ce34ec9c..feae01ce 100644
--- a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.cs
@@ -430,7 +430,7 @@ internal sealed partial class DocxReader
_reader = reader;
_props = props;
_output = output;
- _format = reader.ParaFormat(props);
+ _format = reader.ParaFormat(props, mark.Size);
_mark = reader.CharFormat(mark);
_heading = reader.HeadingLevel(props, pPr);
_list = reader.Numbering(props.NumId) is { } numbering ? new HListRef(numbering, Math.Clamp(props.Ilvl ?? 0, 0, 8), Numbered: true) : null;
@@ -638,7 +638,7 @@ internal sealed partial class DocxReader
case "pict" or "object":
if (ShowsText())
{
- foreach (var inline in Vml(child))
+ foreach (var inline in Vml(child, format))
builder.Add(inline);
}
break;
diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs
index 1c06db10..915a8d07 100644
--- a/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs
@@ -392,7 +392,7 @@ internal readonly record struct HTabStop(int Position, HTabKind Kind, string Lea
/// <summary>Character formatting; null members keep the 한글 style's value.</summary>
/// <param name="Size">Font size in 1/100 pt.</param>
/// <param name="Font">Font for Latin text.</param>
-/// <param name="EastAsianFont">Font for Hangul / Hanja / Japanese text.</param>
+/// <param name="EastAsianFont">Font for Hangul / Hanja / Japanese text and CJK punctuation (the symbol slot).</param>
/// <param name="Color">Text colour "#RRGGBB".</param>
/// <param name="Shade">Background (highlight) colour "#RRGGBB".</param>
internal readonly record struct HCharFormat(
diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Header.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Header.cs
index d9189b2c..156add1e 100644
--- a/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Header.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Header.cs
@@ -163,7 +163,8 @@ internal sealed partial class HwpxWriter
var fontRef = EnsureChild(node, "fontRef");
foreach (var language in Languages)
{
- var eastAsian = language is "HANGUL" or "HANJA" or "JAPANESE";
+ // The symbol slot holds the CJK punctuation (、。「」《》), which Word draws in the East Asian font.
+ var eastAsian = language is "HANGUL" or "HANJA" or "JAPANESE" or "SYMBOL";
var face = eastAsian ? format.EastAsianFont ?? format.Font : format.Font ?? format.EastAsianFont;
if (face is not null)
fontRef.SetAttributeValue(language.ToLowerInvariant(), FontId(language, face));
diff --git a/src/Filee.Engines/Hwp/RhwpFonts.cs b/src/Filee.Engines/Hwp/RhwpFonts.cs
index ed191e19..38d11d10 100644
--- a/src/Filee.Engines/Hwp/RhwpFonts.cs
+++ b/src/Filee.Engines/Hwp/RhwpFonts.cs
@@ -19,8 +19,9 @@ using SkiaSharp;
namespace Filee.Engines.Hwp;
-/// <summary>An installed font: whether rhwp can embed it and which characters it has.</summary>
-internal sealed record InstalledFont(bool Usable, Func<int, bool> Has);
+/// <summary>An installed font: whether rhwp can embed it, which characters it has and how wide they are.</summary>
+/// <param name="Advance">Advance width of a character in em, null when the font lacks it (or is not measured).</param>
+internal sealed record InstalledFont(bool Usable, Func<int, bool> Has, Func<int, double?>? Advance = null);
internal static class RhwpFonts
{
@@ -196,12 +197,21 @@ internal static class RhwpFonts
if (typeface is null)
continue;
if (OperatingSystem.IsWindows() || string.Equals(typeface.FamilyName, candidate, StringComparison.OrdinalIgnoreCase))
- return new InstalledFont(IsUsable(typeface), codePoint => typeface.GetGlyph(codePoint) != 0);
+ return new InstalledFont(IsUsable(typeface), codePoint => typeface.GetGlyph(codePoint) != 0, codePoint => Advance(typeface, codePoint));
typeface.Dispose();
}
return null;
});
+ private static double? Advance(SKTypeface typeface, int codePoint)
+ {
+ var glyph = typeface.GetGlyph(codePoint);
+ if (glyph == 0)
+ return null;
+ using var font = new SKFont(typeface, 1000);
+ return font.GetGlyphWidths([glyph])[0] / 1000.0;
+ }
+
/// <summary>False when the font has CFF2 outlines (variable OpenType fonts made from PostScript outlines).</summary>
internal static bool IsUsable(SKTypeface typeface) => !typeface.GetTableTags().Contains(Tag("CFF2"));
diff --git a/src/Filee.Engines/Hwp/RhwpInput.Punctuation.cs b/src/Filee.Engines/Hwp/RhwpInput.Punctuation.cs
new file mode 100644
index 00000000..e1526675
--- /dev/null
+++ b/src/Filee.Engines/Hwp/RhwpInput.Punctuation.cs
@@ -0,0 +1,192 @@
+// Punctuation widths for rhwp (issue #237). rhwp lays text out with width tables of its own: Korean fonts and common
+// Latin fonts have real ones, every other font (SimSun, Microsoft YaHei, KaiTi, MS Mincho, Noto Serif CJK SC, …) gets
+// a guess in which quotes, dashes and CJK punctuation are half a character wide (‘ ’ 0.3). In Chinese and Japanese
+// fonts those are full width, and the PDF draws the real glyph at the guessed position: an opening quote or bracket
+// (drawn in the right half of its square) lands on the next character, 、 and 。 squeeze the text after them.
+//
+// In the copy rhwp renders, such characters get a run of their own whose character shape adds letter spacing up to
+// the font's real width. rhwp's letter spacing is a percentage of the character's own width, so 100 % doubles it.
+
+using System.Globalization;
+using System.Xml.Linq;
+
+namespace Filee.Engines.Hwp;
+
+internal static partial class RhwpInput
+{
+ /// <summary>
+ /// Characters rhwp guesses narrower than CJK fonts draw them: the language slot it draws them with and its guess
+ /// (in em) for fonts it has no table for. Measured with rhwp 0.8.7.
+ /// </summary>
+ private static readonly Dictionary<char, (string Slot, double Guess)> GuessedWidths = BuildGuesses();
+
+ private static readonly string[] Slots = ["hangul", "latin", "hanja", "japanese", "other", "symbol", "user"];
+
+ private static Dictionary<char, (string, double)> BuildGuesses()
+ {
+ var guesses = new Dictionary<char, (string, double)>
+ {
+ ['‘'] = ("HANGUL", 0.3),
+ ['’'] = ("HANGUL", 0.3),
+ };
+ foreach (var c in "“”—―–‥…•※‰′")
+ guesses[c] = ("HANGUL", 0.5);
+ foreach (var c in "、。〃々〇〈〉《》「」『』【】〔〕〖〗〝〞")
+ guesses[c] = ("SYMBOL", 0.5);
+ return guesses;
+ }
+
+ /// <summary>
+ /// Gives the punctuation above its font's real width in rhwp's layout (see the file comment). True when something
+ /// changed.
+ /// </summary>
+ internal static bool WidenPunctuation(XDocument header, IReadOnlyList<XDocument> sections, Func<string, InstalledFont?> lookup)
+ {
+ var charProperties = header.Descendants().FirstOrDefault(e => e.Name.LocalName == "charProperties");
+ if (charProperties is null)
+ return false;
+ var shapes = charProperties.Elements().Where(e => e.Name.LocalName == "charPr").ToDictionary(e => (string?)e.Attribute("id") ?? "");
+ var faces = header.Descendants().Where(e => e.Name.LocalName == "fontface")
+ .ToDictionary(e => (string?)e.Attribute("lang") ?? "", e => e.Elements().Where(f => f.Name.LocalName == "font")
+ .ToDictionary(f => (string?)f.Attribute("id") ?? "", f => (string?)f.Attribute("face") ?? ""));
+ var nextId = shapes.Keys.Select(k => int.TryParse(k, out var id) ? id : 0).DefaultIfEmpty(-1).Max() + 1;
+ var spacings = new Dictionary<(string Id, char Character), int?>();
+ var widened = new Dictionary<(string Id, int Spacing), string>();
+
+ // The letter spacing that brings a character in this shape to its real width, or null when rhwp's is right.
+ int? Spacing(string id, char c)
+ {
+ if (spacings.TryGetValue((id, c), out var known))
+ return known;
+ int? result = null;
+ if (GuessedWidths.TryGetValue(c, out var guess) && shapes.TryGetValue(id, out var shape))
+ {
+ var slot = guess.Slot.ToLowerInvariant();
+ var fontId = (string?)Child(shape, "fontRef")?.Attribute(slot);
+ var face = fontId is not null && faces.TryGetValue(guess.Slot, out var list) ? list.GetValueOrDefault(fontId) : null;
+ if (face is { Length: > 0 } && lookup(face) is { Usable: true, Advance: { } advance } font && Guesses(face, font)
+ && advance(c) is { } real && real > guess.Guess + 0.05)
+ {
+ var current = Number(Child(shape, "spacing"), slot) ?? 0;
+ result = Math.Clamp((int)Math.Round(real / guess.Guess * (100 + current)) - 100, -50, 500);
+ }
+ }
+ return spacings[(id, c)] = result;
+ }
+
+ string Widened(string id, int spacing)
+ {
+ if (widened.TryGetValue((id, spacing), out var existing))
+ return existing;
+ var copy = new XElement(shapes[id]);
+ var newId = (nextId++).ToString(CultureInfo.InvariantCulture);
+ copy.SetAttributeValue("id", newId);
+ if (Child(copy, "spacing") is not { } element)
+ {
+ element = new XElement(copy.Name.Namespace + "spacing");
+ (Child(copy, "ratio") ?? Child(copy, "fontRef"))?.AddAfterSelf(element);
+ if (element.Parent is null)
+ copy.AddFirst(element);
+ }
+ // The run holds only the widened characters, so every slot can take the same spacing.
+ foreach (var slot in Slots)
+ element.SetAttributeValue(slot, spacing);
+ charProperties.Add(copy);
+ return widened[(id, spacing)] = newId;
+ }
+
+ var changed = false;
+ foreach (var section in sections)
+ {
+ foreach (var run in section.Descendants().Where(e => e.Name.LocalName == "run").ToList())
+ {
+ var id = (string?)run.Attribute("charPrIDRef") ?? "";
+ if (!run.Elements().Any(e => e.Name.LocalName == "t" && e.Value.Any(c => Spacing(id, c) is not null)))
+ continue;
+ run.ReplaceWith(SplitRun(run, c => Spacing(id, c) is { } spacing ? Widened(id, spacing) : null));
+ changed = true;
+ }
+ }
+ if (changed)
+ charProperties.SetAttributeValue("itemCnt", charProperties.Elements().Count(e => e.Name.LocalName == "charPr"));
+ return changed;
+ }
+
+ /// <summary>
+ /// rhwp has no width table for the font (it guesses): Chinese and Japanese fonts. Korean fonts (with Hangul) and
+ /// Latin fonts (without Han) have tables.
+ /// </summary>
+ private static bool Guesses(string face, InstalledFont font) =>
+ RhwpFonts.Script(face) is "zh-Hans" or "zh-Hant" or "ja" || font.Has('一') && !font.Has('가');
+
+ /// <summary>
+ /// The run split so that the characters <paramref name="shapeOf"/> gives a character shape for are in runs of that
+ /// shape; everything else (other text, tabs, controls) stays in the run's own shape, in order.
+ /// </summary>
+ private static List<XElement> SplitRun(XElement run, Func<char, string?> shapeOf)
+ {
+ var baseId = (string?)run.Attribute("charPrIDRef") ?? "";
+ var pieces = new List<XElement>();
+ XElement? current = null;
+ string? currentId = null;
+ XElement? text = null; // the hp:t of the current piece being filled, if any
+
+ XElement Piece(string id)
+ {
+ if (current is null || currentId != id)
+ {
+ current = new XElement(run.Name, run.Attributes().Where(a => a.Name.LocalName != "charPrIDRef"));
+ current.SetAttributeValue("charPrIDRef", id);
+ currentId = id;
+ pieces.Add(current);
+ text = null;
+ }
+ return current;
+ }
+
+ foreach (var node in run.Nodes())
+ {
+ if (node is not XElement { Name.LocalName: "t" } t)
+ {
+ Piece(baseId).Add(node is XElement element ? new XElement(element) : node);
+ text = null;
+ continue;
+ }
+ XElement Text(string id)
+ {
+ var piece = Piece(id);
+ if (text is null)
+ {
+ text = new XElement(t.Name, t.Attributes());
+ piece.Add(text);
+ }
+ return text;
+ }
+ foreach (var part in t.Nodes())
+ {
+ if (part is XText value)
+ {
+ // Consecutive characters of the same shape stay together ("……", "——").
+ var chars = value.Value;
+ for (var start = 0; start < chars.Length;)
+ {
+ var id = shapeOf(chars[start]) ?? baseId;
+ var end = start + 1;
+ while (end < chars.Length && (shapeOf(chars[end]) ?? baseId) == id)
+ end++;
+ Text(id).Add(chars[start..end]);
+ start = end;
+ }
+ }
+ else
+ {
+ Text(baseId).Add(part is XElement element ? new XElement(element) : part);
+ }
+ }
+ if (!t.Nodes().Any())
+ Text(baseId);
+ text = null;
+ }
+ return pieces;
+ }
+}
diff --git a/src/Filee.Engines/Hwp/RhwpInput.cs b/src/Filee.Engines/Hwp/RhwpInput.cs
index 7f249f33..d690b10d 100644
--- a/src/Filee.Engines/Hwp/RhwpInput.cs
+++ b/src/Filee.Engines/Hwp/RhwpInput.cs
@@ -1,6 +1,8 @@
// 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).
+// - Punctuation widths (RhwpInput.Punctuation): quotes and CJK punctuation in Chinese and Japanese fonts get letter
+// spacing up to their real width, which rhwp guesses as half a character (#237).
// - 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.
@@ -85,8 +87,15 @@ internal static partial class RhwpInput
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))
+ lookup ??= RhwpFonts.Find;
+ if (ApplyFonts(header, text.ToString(), lookup))
changed["Contents/header.xml"] = header;
+ if (WidenPunctuation(header, sections.Select(s => s.Xml).ToList(), lookup))
+ {
+ changed["Contents/header.xml"] = header;
+ foreach (var (name, xml) in sections)
+ changed[name] = xml;
+ }
foreach (var (name, xml) in sections)
{
diff --git a/tests/Filee.Engines.Tests/DocxChineseLayoutTests.cs b/tests/Filee.Engines.Tests/DocxChineseLayoutTests.cs
new file mode 100644
index 00000000..abe2ef40
--- /dev/null
+++ b/tests/Filee.Engines.Tests/DocxChineseLayoutTests.cs
@@ -0,0 +1,165 @@
+// A Chinese Word document (issue #237): legacy WordArt, indents in characters, numbering turned off with numId 0,
+// CJK punctuation in the East Asian font, and the punctuation widths rhwp guesses for Chinese fonts.
+
+using System.Xml.Linq;
+using Filee.Engines.Hwp;
+using Filee.Engines.Hwp.Hwpx;
+using Filee.Engines.Hwp.Hwpx.Docx;
+using static Filee.Engines.Tests.DocxBuilder;
+using static Filee.Engines.Tests.HwpxAssert;
+
+namespace Filee.Engines.Tests;
+
+public class DocxChineseLayoutTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ private const string WordArt = """
+ <w:r><w:rPr><w:b/><w:color w:val="FF0000"/><w:sz w:val="32"/><w:u w:val="single"/></w:rPr><w:pict>
+ <v:shape id="_x0000_i1025" type="#_x0000_t136" style="height:28.8pt;width:420pt;" fillcolor="#FF0000" filled="t" stroked="t">
+ <v:textpath on="t" fitshape="t" fitpath="t" trim="t" string="111111111111111111111" style="font-family:宋体;font-size:28pt;font-weight:bold;"/>
+ <w10:wrap type="none"/>
+ </v:shape>
+ </w:pict></w:r>
+ """;
+
+ private const string ChineseStyles = """
+ <w:docDefaults><w:rPrDefault><w:rPr><w:rFonts w:ascii="Times New Roman" w:hAnsi="Times New Roman" w:eastAsia="宋体"/></w:rPr></w:rPrDefault></w:docDefaults>
+ <w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/>
+ <w:pPr><w:ind w:firstLine="420"/></w:pPr><w:rPr><w:sz w:val="21"/></w:rPr></w:style>
+ """;
+
+ private HDocument Read(DocxBuilder docx)
+ {
+ var dir = fx.NewFolder();
+ return DocxReader.Read(docx.Save(Path.Combine(dir, "source.docx")), Path.Combine(dir, "media"));
+ }
+
+ private static List<HParagraph> Paragraphs(HDocument document) => document.Sections.SelectMany(s => s.Blocks).OfType<HParagraph>().ToList();
+
+ [Fact]
+ public void Legacy_WordArt_keeps_its_text_in_its_font_colour_and_about_its_size()
+ {
+ var document = Read(new DocxBuilder().Paragraph(P(WordArt, "<w:jc w:val=\"center\"/>")));
+
+ var text = Assert.IsType<HText>(Assert.Single(Paragraphs(document)[0].Inlines));
+ Assert.Equal("111111111111111111111", text.Text);
+ Assert.Equal(("宋体", "宋体", "#FF0000", true, true), (text.Format.Font, text.Format.EastAsianFont, text.Format.Color, text.Format.Bold, text.Format.Underline));
+ // Stretched over 420 × 28.8 pt: 21 half-width digits make about 40 pt.
+ Assert.InRange(text.Format.Size!.Value, 3800, 4100);
+ }
+
+ [Fact]
+ public void Floating_WordArt_becomes_a_borderless_text_box_where_it_was()
+ {
+ var floating = WordArt.Replace("style=\"height:28.8pt;width:420pt;\"",
+ "style=\"position:absolute;margin-left:10pt;margin-top:20pt;height:36pt;width:200pt;mso-position-horizontal-relative:margin;z-index:2\"", StringComparison.Ordinal);
+ var document = Read(new DocxBuilder().Paragraph(P(floating)));
+
+ var box = Assert.IsType<HTextBox>(Assert.Single(Paragraphs(document)[0].Inlines));
+ Assert.Equal(HBorder.None, box.Line);
+ Assert.Equal((1000, 2000), (box.Anchor!.HorizontalOffset, box.Anchor.VerticalOffset));
+ var paragraph = Assert.IsType<HParagraph>(Assert.Single(box.Blocks));
+ Assert.Equal("111111111111111111111", Assert.IsType<HText>(Assert.Single(paragraph.Inlines)).Text);
+ }
+
+ [Fact]
+ public void Indents_in_characters_use_the_paragraph_font_size()
+ {
+ var docx = new DocxBuilder { Styles = ChineseStyles };
+ docx.Paragraph(P(R("左缩进"), "<w:ind w:leftChars=\"200\"/><w:rPr><w:sz w:val=\"21\"/></w:rPr>"))
+ .Paragraph(P(R("首行"), "<w:ind w:firstLineChars=\"200\"/><w:rPr><w:sz w:val=\"24\"/></w:rPr>"))
+ .Paragraph(P(R("悬挂"), "<w:ind w:left=\"840\" w:hangingChars=\"100\"/>"))
+ .Paragraph(P(R("厘米"), "<w:ind w:left=\"720\" w:leftChars=\"0\" w:firstLine=\"0\" w:firstLineChars=\"0\"/>"));
+
+ var formats = Paragraphs(Read(docx)).Select(p => p.Format).ToList();
+ // 2 characters of 10.5 pt = 21 pt; the style's first-line indent (420 twips) stays where only the left changes.
+ Assert.Equal((HwpxUnits.FromTwips(420), HwpxUnits.FromTwips(420)), (formats[0].Left, formats[0].FirstLine));
+ Assert.Equal((0, HwpxUnits.FromTwips(480)), (formats[1].Left, formats[1].FirstLine));
+ Assert.Equal((HwpxUnits.FromTwips(840), -HwpxUnits.FromTwips(210)), (formats[2].Left, formats[2].FirstLine));
+ // leftChars="0" means the twips value counts.
+ Assert.Equal((HwpxUnits.FromTwips(720), 0), (formats[3].Left, formats[3].FirstLine));
+ }
+
+ [Fact]
+ public void Numbering_turned_off_drops_the_inherited_indents()
+ {
+ var docx = new DocxBuilder { Styles = ChineseStyles };
+ docx.Paragraph(P(R("模型部署"), "<w:numPr><w:numId w:val=\"0\"/></w:numPr><w:ind w:leftChars=\"200\"/>"))
+ .Paragraph(P(R("正文"), "<w:numPr><w:numId w:val=\"0\"/></w:numPr>"))
+ .Paragraph(P(R("普通")));
+
+ var formats = Paragraphs(Read(docx)).Select(p => (p.Format.Left, p.Format.FirstLine)).ToList();
+ Assert.Equal((HwpxUnits.FromTwips(420), 0), formats[0]);
+ Assert.Equal((0, 0), formats[1]);
+ Assert.Equal((0, HwpxUnits.FromTwips(420)), formats[2]); // without numPr the style's indent stays
+ }
+
+ [Fact]
+ public void Cjk_punctuation_is_written_in_the_East_Asian_font()
+ {
+ var dir = fx.NewFolder();
+ var docx = new DocxBuilder { Styles = ChineseStyles }.Paragraph(P(R("“在线教育平台”、《标题》")));
+ var hwpx = Path.Combine(dir, "out.hwpx");
+ HwpxWriter.Write(DocxReader.Read(docx.Save(Path.Combine(dir, "source.docx")), Path.Combine(dir, "media")), hwpx);
+
+ var header = Xml(hwpx, "Contents/header.xml");
+ string Face(XElement fontRef, string slot) =>
+ (string)header.Descendants(Hh + "fontface").Single(f => (string?)f.Attribute("lang") == slot.ToUpperInvariant())
+ .Elements(Hh + "font").Single(f => (string?)f.Attribute("id") == (string?)fontRef.Attribute(slot))
+ .Attribute("face")!;
+ var run = RunWith(Xml(hwpx), "在线");
+ var fontRef = HeadItem(hwpx, "charPr", (string)run.Attribute("charPrIDRef")!).Element(Hh + "fontRef")!;
+ Assert.Equal(("宋体", "宋体", "Times New Roman"), (Face(fontRef, "symbol"), Face(fontRef, "hanja"), Face(fontRef, "latin")));
+ }
+
+ /// <summary>A Chinese font as rhwp's PDF draws it: full-width punctuation, no Hangul.</summary>
+ private static InstalledFont? ChineseComputer(string face) => face switch
+ {
+ "宋体" => new InstalledFont(true, c => c != '가', c => c < 0x2000 ? 0.5 : 1.0),
+ "Times New Roman" => new InstalledFont(true, c => c < 0x3000, c => 0.5),
+ _ => null,
+ };
+
+ [Fact]
+ public void Punctuation_rhwp_guesses_narrow_gets_spacing_up_to_its_width()
+ {
+ var dir = fx.NewFolder();
+ var docx = new DocxBuilder { Styles = ChineseStyles }.Paragraph(P(R("“在线”、‘课’……Web。")));
+ var hwpx = Path.Combine(dir, "out.hwpx");
+ HwpxWriter.Write(DocxReader.Read(docx.Save(Path.Combine(dir, "source.docx")), Path.Combine(dir, "media")), hwpx);
+
+ var copy = RhwpInput.Prepare(hwpx, dir, ChineseComputer);
+
+ Assert.NotNull(copy);
+ ValidPackage(copy);
+ var paragraph = ParagraphWith(Xml(copy), "在线");
+ var runs = paragraph.Elements(Hp + "run").Where(r => r.Element(Hp + "t") is not null).ToList();
+ Assert.Equal("“在线”、‘课’……Web。", string.Concat(runs.Select(r => r.Element(Hp + "t")!.Value)));
+
+ int Spacing(string text)
+ {
+ var run = runs.Single(r => r.Element(Hp + "t")!.Value == text);
+ var spacing = HeadItem(copy, "charPr", (string)run.Attribute("charPrIDRef")!).Element(Hh + "spacing")!;
+ return (int)spacing.Attribute("hangul")!;
+ }
+ // rhwp: “ ” … half a character, ‘ ’ 0.3, 、 。 half; the font: all full width.
+ Assert.Equal(100, Spacing("“"));
+ Assert.Equal(100, Spacing("”、")); // same shape: one run
+ Assert.Equal(233, Spacing("‘"));
+ Assert.Equal(100, Spacing("……"));
+ Assert.Equal(100, Spacing("。"));
+ Assert.Equal(0, Spacing("在线"));
+ Assert.Equal(0, Spacing("Web"));
+ }
+
+ [Fact]
+ public void Punctuation_in_Korean_and_Latin_fonts_is_left_to_rhwp()
+ {
+ var dir = fx.NewFolder();
+ var docx = new DocxBuilder().Paragraph(P(R("“인용”、《제목》")));
+ var hwpx = Path.Combine(dir, "out.hwpx");
+ HwpxWriter.Write(DocxReader.Read(docx.Save(Path.Combine(dir, "source.docx")), Path.Combine(dir, "media")), hwpx);
+
+ // A Korean font: rhwp has its widths.
+ Assert.Null(RhwpInput.Prepare(hwpx, dir, _ => new InstalledFont(true, _ => true, _ => 1.0)));
+ }
+}