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
Read complex-script PDF text in its logical order and mark Arabic paragraphs right to left
KnifeLemon98d9bb16dfd2
diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex 5ef91e29..a207e074 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -38,6 +38,19 @@ DOCX, XLSX, XLS, ODS and PPTX → PDF need neither Microsoft Office nor LibreOffand rendered by rhwp. Anything the built-in readers understand (including PDF) is written as DOCX by the DOCX writer.LibreOffice's and Pandoc's costs are set so the built-in route always wins where one exists.+Except for text that needs shaping. rhwp draws one glyph per character from left to right without OpenType shaping,+so Arabic and Hebrew come out unjoined and in the wrong order, and Indic vowel signs and conjuncts as separate glyphs+with dotted circles (#185 Gujarati, #202 Arabic). Its PDF edges are marked `Unshaped`, and rhwp tells+(`ITextShapingCheck`) whether a source has such text: `Infrastructure/ComplexScripts.cs` scans the text parts of the+file without reading it into the document model (DOCX `word/document.xml`, headers, footers and notes, PPTX slides,+XLSX shared strings and sheets, HWPX sections, EPUB chapters, or a text file with its HTML / RTF character+references) for the Hebrew, Arabic, Syriac, Thaana, N'Ko, Indic, Sinhala, Thai, Lao, Tibetan, Myanmar, Khmer,+Mongolian and other South / Southeast Asian blocks. For such a file `JobQueue` plans again without unshaped edges: DOCX,+TXT, Markdown, HTML, XLSX, PPTX and HWPX → PDF (and → images through PDF) go through LibreOffice even when Settings →+*Engines* doesn't choose it for documents. Without LibreOffice the file fails with "This script needs LibreOffice to+convert correctly" and the script's name instead of becoming a broken PDF. Latin, Greek, Cyrillic, CJK and Korean+documents keep the built-in route; a binary HWP is not scanned and stays with rhwp.+All built-in document readers are registered in one place, `Hwp/Hwpx/DocumentReaders.cs` (format id → reader, andwhich formats need Pandoc). The HWPX writer and the DOCX writer take their input formats from it: adding a readerthere is one line and makes both writers (and every route through them) accept the format.@@ -431,6 +444,19 @@ it. DOCX → DOCX is no edge; the Word variants are the Office Open XML engine'sline's first word would have fitted keeps its line break;- reading order: gutters between columns are found where no narrow paragraph crosses; paragraphs that span thecolumns (titles, figures, closing text) split the page into bands, read column by column;+- text that needs shaping (`PdfDocumentReader.ComplexText.cs`): an `/ActualText` of marked content replaces the+ glyphs it covers on every page (LibreOffice writes one for each cluster whose glyphs don't map to its characters+ one to one: conjuncts, vowel signs drawn before their consonant, ligatures). On a page with Arabic, Hebrew, Indic,+ Thai, ... text, words are built from the glyphs in content-stream order instead of by position, because marks+ have no width and overlap their letter: a mark joins the letter before it, a vowel sign drawn before its consonant+ (Word's PDFs keep that visual order) joins the consonant after it, and the dotted circles of PDFs made by rhwp+ (mapped to U+0002 or to a vowel sign, wider than any mark) are left out. Right-to-left words are read from the+ right, with numbers and Latin words in them left to right, a line's words likewise; a paragraph of mostly+ right-to-left lines is marked right to left (`HParaFormat.RightToLeft`), its alignment and indents measured from+ the right, and DOCX gets `w:bidi` on it and `w:rtl` on its Arabic or Hebrew runs (HWPX has no right-to-left+ paragraphs). Fonts keep their family names (`ArialUnicodeMS` → Arial Unicode MS, `NirmalaUI` → Nirmala UI,+ `NotoSansGujarati` → Noto Sans Gujarati). Not recovered: a cluster drawn as one glyph whose ToUnicode entry is+ wrong, in a PDF without ActualText (some Word PDFs), and the word spacing of rhwp's broken layouts;- headings from font sizes (short paragraphs clearly larger than the body text, the largest size is level 1), boldand italic from the fonts, colours, links from link annotations, alignment, indents, spacing and line pitch;- pictures: JPEG streams are kept as they are, others are decoded to PNG, and what PdfPig cannot decode is cut out@@ -817,6 +843,9 @@ HWPX writer) get room for their equations: rhwp puts a line's baseline at 85 % oequation's own baseline on it, so a fraction, matrix or sum hangs below the line; that overhang is added as spaceafter the paragraph (#143).+An HWPX with text that needs shaping (Arabic, Hindi, Thai, ...) goes to LibreOffice with H2Orestart instead, like the+documents above; an HWP is not scanned and stays with rhwp.+rhwp renders text slowly: about 1 s per KB of section XML, some 4 s per page of a novel (rhwp 0.8.7 on ani7-1185G7, pictures cost little). So each rhwp run's time limit follows the document's text: 2 minutes + 30 minutesper MB of unpacked `Contents/section*.xml` (an HWP counts three times its file size, its text being deflated), at mostdiff --git a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxWriter.Body.cs b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxWriter.Body.csindex d2df5d35..3e706a88 100644--- a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxWriter.Body.cs+++ b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxWriter.Body.cs@@ -6,6 +6,7 @@// (CT_PPr, CT_RPr, CT_SectPr, CT_TblPr, CT_TcPr), which Word enforces.using System.Text;+using Filee.Engines.Infrastructure;namespace Filee.Engines.Hwp.Hwpx.Docx;@@ -209,7 +210,7 @@ internal sealed partial class DocxWriterreturn sb.Append("</w:p>").ToString();}- /// <summary>w:pPr in CT_PPr order: pStyle, keepNext, keepLines, pageBreakBefore, widowControl, numPr, tabs, spacing, ind, jc, rPr, sectPr.</summary>+ /// <summary>w:pPr in CT_PPr order: pStyle, keepNext, keepLines, pageBreakBefore, widowControl, numPr, tabs, bidi, spacing, ind, jc, rPr, sectPr.</summary>private string ParagraphProperties(HParagraph paragraph, string? style, bool heading, string? sectPr, RunContext context){var format = paragraph.Format;@@ -255,6 +256,10 @@ internal sealed partial class DocxWritersb.Append("</w:tabs>");}+ // Right to left: w:ind's left / right and w:jc's left / right then mean the start and the end side.+ if (format.RightToLeft == true)+ sb.Append("<w:bidi/>");+var spacing = new StringBuilder();if (format.Before is { } before)spacing.Append($" w:before=\"{Number(Math.Max(0, Twips(before)))}\"");@@ -367,7 +372,8 @@ internal sealed partial class DocxWriter{if (text.Length == 0)return;- sb.Append("<w:r>").Append(RunPr(format, context));+ // Arabic or Hebrew text is marked right to left, as Word does: it then takes the complex script font and size.+ sb.Append("<w:r>").Append(RunPr(format, context, rightToLeft: ComplexScripts.Direction(text) < 0));var start = 0;for (var i = 0; i <= text.Length; i++){@@ -387,14 +393,14 @@ internal sealed partial class DocxWritersb.Append("</w:r>");}- private static string RunPr(HCharFormat format, RunContext context, string? characterStyle = null)+ private static string RunPr(HCharFormat format, RunContext context, string? characterStyle = null, bool rightToLeft = false){- var properties = RunProperties(format, context, characterStyle);+ var properties = RunProperties(format, context, characterStyle, rightToLeft);return properties.Length == 0 ? "" : $"<w:rPr>{properties}</w:rPr>";}/// <summary>Content of w:rPr in CT_RPr order.</summary>- private static string RunProperties(HCharFormat format, RunContext context, string? characterStyle = null)+ private static string RunProperties(HCharFormat format, RunContext context, string? characterStyle = null, bool rightToLeft = false){var sb = new StringBuilder();characterStyle ??= context.Link ? "Hyperlink" : null;@@ -445,6 +451,8 @@ internal sealed partial class DocxWritersb.Append("<w:vertAlign w:val=\"superscript\"/>");else if (format.Subscript == true)sb.Append("<w:vertAlign w:val=\"subscript\"/>");+ if (rightToLeft)+ sb.Append("<w:rtl/>");return sb.ToString();}diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxModel.csindex c772ff55..1c06db10 100644--- a/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs@@ -346,6 +346,11 @@ internal readonly record struct HLineSpacing(HLineSpacingKind Kind, int Value);/// <summary>Paragraph formatting; null members keep the 한글 style's value.</summary>/// <param name="FirstLine">First line indent relative to <paramref name="Left"/>; negative = hanging indent.</param>+/// <param name="RightToLeft">+/// A right-to-left paragraph (Arabic, Hebrew): its lines start at the right. <paramref name="Align"/>,+/// <paramref name="Left"/> and <paramref name="Right"/> then name the start and the end side, as Word's w:bidi+/// paragraphs do (Left aligns to the right edge). Written to DOCX only; HWPX has no right-to-left paragraphs.+/// </param>internal readonly record struct HParaFormat(HAlign? Align = null,int? Left = null,@@ -357,7 +362,8 @@ internal readonly record struct HParaFormat(bool? KeepWithNext = null,bool? KeepLines = null,bool? WidowOrphan = null,- IReadOnlyList<HTabStop>? Tabs = null)+ IReadOnlyList<HTabStop>? Tabs = null,+ bool? RightToLeft = null){public bool IsEmpty => this == default;@@ -366,10 +372,10 @@ internal readonly record struct HParaFormat(Align == other.Align && Left == other.Left && Right == other.Right && FirstLine == other.FirstLine &&Before == other.Before && After == other.After && LineSpacing == other.LineSpacing &&KeepWithNext == other.KeepWithNext && KeepLines == other.KeepLines && WidowOrphan == other.WidowOrphan &&- (Tabs ?? []).SequenceEqual(other.Tabs ?? []);+ RightToLeft == other.RightToLeft && (Tabs ?? []).SequenceEqual(other.Tabs ?? []);public override int GetHashCode() =>- HashCode.Combine(Align, Left, Right, FirstLine, Before, After, LineSpacing, HashCode.Combine(KeepWithNext, KeepLines, WidowOrphan, Tabs?.Count ?? 0));+ HashCode.Combine(Align, Left, Right, FirstLine, Before, After, LineSpacing, HashCode.Combine(KeepWithNext, KeepLines, WidowOrphan, RightToLeft, Tabs?.Count ?? 0));}internal enum HTabKinddiff --git a/src/Filee.Engines/Pdf/PdfDocumentReader.ComplexText.cs b/src/Filee.Engines/Pdf/PdfDocumentReader.ComplexText.csnew file mode 100644index 00000000..20667854--- /dev/null+++ b/src/Filee.Engines/Pdf/PdfDocumentReader.ComplexText.cs@@ -0,0 +1,333 @@+// Text of scripts that need shaping (Arabic, Hebrew, the Indic scripts, Thai, ...) for PdfDocumentReader.+//+// A PDF holds glyphs, not characters: a shaped cluster (a conjunct, a vowel sign drawn before its consonant, a letter+// with its marks) is one or several glyphs whose ToUnicode entries can't say the cluster's characters, and the glyphs of+// right-to-left text are drawn left to right. So:+// * /ActualText of marked content (LibreOffice writes it for every cluster whose glyphs don't map one to one) replaces+// the glyphs it covers, on every page.+// * On a page with such text, words are built from the glyphs in content-stream order, not by their positions:+// combining marks sit on or before their letter (zero width, overlapping), so sorting by position mixes them up, and+// rhwp's PDFs (made by Filee before it routed these documents to LibreOffice) place them anywhere. Marks join the+// letter before them in the stream; a vowel sign that is drawn before its consonant in the stream (Word's PDFs)+// joins the consonant after it.+// * A right-to-left word is read from right to left (its clusters by position), with numbers and Latin words in it+// kept left to right; the words of a right-to-left line likewise (Runs), and such a paragraph is marked right to left.+// Not recovered: PDFs that draw a cluster as one glyph whose ToUnicode entry is wrong and give no ActualText.++using System.Globalization;+using System.Text;+using Filee.Engines.Infrastructure;+using UglyToad.PdfPig.Content;+using UglyToad.PdfPig.Core;++namespace Filee.Engines.Pdf;++internal sealed partial class PdfDocumentReader+{+ /// <summary>A word of a page before it gets its position relative to the crop box and its formatting.</summary>+ private sealed record PageWord(string Text, PdfRectangle Box, IReadOnlyList<Letter> Letters, Letter Lead);++ /// <summary>An ActualText that covers more glyphs or lines than this is a label for a passage, not a cluster's text.</summary>+ private const int MaxActualTextLetters = 64;++ // ───────────────────────── ActualText ─────────────────────────++ /// <summary>+ /// The page's letters in content-stream order, the glyphs of each /ActualText span replaced by one letter with its+ /// text (over their joint box). Glyphs that stand for no text keep their place with an empty value (words still+ /// span them): control characters, and the dotted circles an engine draws before marks it can't attach (rhwp maps+ /// them to U+0002 or to a vowel sign, and draws them wider than any mark).+ /// </summary>+ private static List<Letter> ContentLetters(Page page)+ {+ var spans = ActualTextSpans(page);+ var letters = page.Letters;+ var result = new List<Letter>(letters.Count);+ var done = new HashSet<MarkedContentElement>(ReferenceEqualityComparer.Instance);+ for (var i = 0; i < letters.Count; i++)+ {+ var letter = letters[i];+ if (spans is not null && spans.TryGetValue(letter, out var span))+ {+ if (done.Add(span.Element) && span.Text.Length > 0)+ result.Add(Merged(span.Text, span.Letters));+ continue;+ }+ var value = letter.Value;+ var beforeMark = i + 1 < letters.Count && IsMark(letters[i + 1].Value) && OnSameBaseline(letter, letters[i + 1]);+ if ((value.Length > 0 && value.All(char.IsControl))+ || (beforeMark && (value == "◌" || (IsMark(value) && Math.Abs(letter.Width) >= 0.5 * Math.Max(1, LetterSize(letter))))))+ {+ result.Add(Blank(letter));+ continue;+ }+ result.Add(letter);+ }+ return result;+ }++ /// <summary>The glyph's place without its text.</summary>+ private static Letter Blank(Letter letter) =>+ new(string.Empty, letter.BoundingBox, letter.BoundingBox, letter.StartBaseLine, letter.EndBaseLine, letter.Width, letter.FontSize,+ letter.FontDetails, letter.RenderingMode, letter.StrokeColor, letter.FillColor, letter.PointSize, letter.TextSequence);++ /// <summary>Letters covered by an ActualText span (the outermost one) → the span; null when the page has none.</summary>+ private static Dictionary<Letter, (MarkedContentElement Element, string Text, List<Letter> Letters)>? ActualTextSpans(Page page)+ {+ IReadOnlyList<MarkedContentElement> marked;+ try+ {+ marked = page.GetMarkedContents();+ }+ catch (Exception ex) when (ex is InvalidOperationException or ArgumentException or NullReferenceException)+ {+ return null; // broken marked content: the glyphs are read as they are+ }+ Dictionary<Letter, (MarkedContentElement, string, List<Letter>)>? spans = null;+ void Walk(IEnumerable<MarkedContentElement> elements, int depth)+ {+ foreach (var element in elements)+ {+ if (element.ActualText is { } text)+ {+ var letters = new List<Letter>();+ Collect(element, letters, 0);+ if (letters.Count > 0 && letters.Count <= MaxActualTextLetters && OnOneLine(letters))+ {+ spans ??= new Dictionary<Letter, (MarkedContentElement, string, List<Letter>)>(ReferenceEqualityComparer.Instance);+ // A space stays a space (a word boundary); other text loses the spaces around it.+ var clean = text.Replace("\0", "", StringComparison.Ordinal);+ clean = string.IsNullOrWhiteSpace(clean) ? (clean.Length > 0 ? " " : "") : clean.Trim();+ foreach (var letter in letters)+ spans.TryAdd(letter, (element, clean, letters));+ continue;+ }+ }+ if (depth < 32)+ Walk(element.Children, depth + 1);+ }+ }+ Walk(marked, 0);+ return spans;++ static void Collect(MarkedContentElement element, List<Letter> letters, int depth)+ {+ letters.AddRange(element.Letters);+ if (depth < 32)+ foreach (var child in element.Children)+ Collect(child, letters, depth + 1);+ }++ static bool OnOneLine(List<Letter> letters)+ {+ var y = letters[0].StartBaseLine.Y;+ var size = Math.Max(1, letters.Max(LetterSize));+ return letters.All(l => Math.Abs(l.StartBaseLine.Y - y) <= 0.5 * size);+ }+ }++ /// <summary>One letter standing for <paramref name="letters"/>: their joint box, the font and colour of the first.</summary>+ private static Letter Merged(string text, List<Letter> letters)+ {+ var first = letters[0];+ var box = new PdfRectangle(letters.Min(l => l.BoundingBox.Left), letters.Min(l => l.BoundingBox.Bottom),+ letters.Max(l => l.BoundingBox.Right), letters.Max(l => l.BoundingBox.Top));+ var y = first.StartBaseLine.Y;+ var start = new PdfPoint(letters.Min(l => Math.Min(l.StartBaseLine.X, l.EndBaseLine.X)), y);+ var end = new PdfPoint(letters.Max(l => Math.Max(l.StartBaseLine.X, l.EndBaseLine.X)), y);+ return new Letter(text, box, box, start, end, end.X - start.X, first.FontSize, first.FontDetails, first.RenderingMode,+ first.StrokeColor, first.FillColor, first.PointSize, first.TextSequence);+ }++ private static double LetterSize(Letter letter) => letter.PointSize > 0 ? letter.PointSize : letter.FontSize;++ // ───────────────────────── Words in content order ─────────────────────────++ /// <summary>A letter with the marks that belong to it.</summary>+ private sealed class Cluster(Letter lead)+ {+ public Letter Lead { get; } = lead;+ public List<Letter> Letters { get; } = [lead];+ public StringBuilder Text { get; } = new(lead.Value);+ public double Size { get; } = Math.Max(1, LetterSize(lead));+ public double Start => Lead.StartBaseLine.X;+ public double End { get; private set; } = lead.EndBaseLine.X;+ public double Center => (Lead.StartBaseLine.X + Lead.EndBaseLine.X) / 2;+ public double Baseline => Lead.StartBaseLine.Y;+ public bool IsSpace => string.IsNullOrWhiteSpace(Lead.Value);++ public void Add(Letter mark)+ {+ Letters.Add(mark);+ Text.Append(mark.Value);+ End = Math.Max(End, mark.EndBaseLine.X);+ }+ }++ /// <summary>True if any of <paramref name="letters"/> is of a script that needs shaping.</summary>+ private static bool HasComplexText(List<Letter> letters) => letters.Any(l => ComplexScripts.Contains(l.Value));++ /// <summary>+ /// The words of a page with text that needs shaping, from its letters in content-stream order (see the top of this+ /// file): marks joined to their letters, words split at spaces, line changes and gaps, and pieces that touch on+ /// a line (a full stop drawn by another text run) joined again.+ /// </summary>+ private static List<PageWord> ComplexWords(List<Letter> letters)+ {+ var horizontal = letters.Where(l => l.TextOrientation == TextOrientation.Horizontal).ToList();++ // Letters → clusters.+ var clusters = new List<Cluster>();+ Letter? pendingPreBase = null;+ for (var i = 0; i < horizontal.Count; i++)+ {+ var letter = horizontal[i];+ if (letter.Value.Length == 0)+ {+ // A glyph without text (a dotted circle): part of the word it is drawn in.+ if (clusters.Count > 0 && !clusters[^1].IsSpace && OnSameBaseline(clusters[^1].Lead, letter))+ clusters[^1].Add(letter);+ continue;+ }+ if (IsMark(letter.Value))+ {+ // Drawn before the letter that follows it (Word's PDFs keep the visual order of a vowel sign written+ // before its consonant): it belongs to that letter.+ if (IsPreBase(letter.Value) && i + 1 < horizontal.Count && !IsMark(horizontal[i + 1].Value)+ && OnSameBaseline(letter, horizontal[i + 1]) && horizontal[i + 1].StartBaseLine.X >= letter.EndBaseLine.X - 0.15 * Math.Max(1, LetterSize(letter)))+ {+ pendingPreBase = letter;+ continue;+ }+ if (clusters.Count > 0 && OnSameBaseline(clusters[^1].Lead, letter) && !clusters[^1].IsSpace)+ {+ clusters[^1].Add(letter);+ continue;+ }+ }+ var cluster = new Cluster(letter);+ if (pendingPreBase is not null)+ {+ cluster.Add(pendingPreBase);+ pendingPreBase = null;+ }+ clusters.Add(cluster);+ }++ // Clusters → words, in stream order.+ var words = new List<List<Cluster>>();+ List<Cluster>? current = null;+ foreach (var cluster in clusters)+ {+ if (cluster.IsSpace)+ {+ current = null;+ continue;+ }+ if (current is not null)+ {+ var previous = current[^1];+ var size = Math.Min(cluster.Size, previous.Size);+ if (!OnSameBaseline(previous.Lead, cluster.Lead) || cluster.Start > previous.End + 0.25 * size || cluster.Start < previous.Start - 0.1 * size)+ current = null;+ }+ if (current is null)+ words.Add(current = []);+ current.Add(cluster);+ }++ // Pieces of one word drawn apart in the stream (a run per direction, a full stop in another font) join again+ // where they touch.+ var rows = new List<List<List<Cluster>>>();+ foreach (var word in words)+ {+ var row = rows.FirstOrDefault(r => OnSameBaseline(r[0][0].Lead, word[0].Lead));+ if (row is null)+ rows.Add(row = []);+ row.Add(word);+ }+ var result = new List<PageWord>(words.Count);+ foreach (var row in rows)+ {+ row.Sort((a, b) => a.Min(c => c.Start).CompareTo(b.Min(c => c.Start)));+ var joined = new List<Cluster>(row[0]);+ for (var w = 1; w <= row.Count; w++)+ {+ if (w < row.Count)+ {+ var right = joined.Max(c => c.End);+ var left = row[w].Min(c => c.Start);+ if (left - right < 0.1 * Math.Min(joined[^1].Size, row[w][0].Size))+ {+ joined.AddRange(row[w]);+ continue;+ }+ }+ result.Add(Word(joined));+ if (w < row.Count)+ joined = [.. row[w]];+ }+ }+ return result;+ }++ /// <summary>A word of clusters: its characters in logical order and its box.</summary>+ private static PageWord Word(List<Cluster> clusters)+ {+ var rtl = ComplexScripts.Direction(string.Concat(clusters.Select(c => c.Text.ToString()))) < 0;+ IEnumerable<Cluster> ordered = rtl+ ? LogicalOrder(clusters.OrderByDescending(c => c.Center).ToList(), c => ComplexScripts.Direction(c.Text.ToString()), rightToLeft: true)+ : clusters.OrderBy(c => c.Start);+ var text = string.Concat(ordered.Select(c => c.Text.ToString()));+ var letters = clusters.SelectMany(c => c.Letters).ToList();+ var box = new PdfRectangle(letters.Min(l => l.BoundingBox.Left), letters.Min(l => l.BoundingBox.Bottom),+ letters.Max(l => l.BoundingBox.Right), letters.Max(l => l.BoundingBox.Top));+ return new PageWord(text, box, letters, clusters.OrderBy(c => c.Start).First().Lead);+ }++ private static bool OnSameBaseline(Letter a, Letter b) =>+ Math.Abs(a.StartBaseLine.Y - b.StartBaseLine.Y) <= 0.3 * Math.Max(1, Math.Min(LetterSize(a), LetterSize(b)));++ /// <summary>Combining marks only (vowel signs, viramas, nuktas, Arabic harakat, Thai tone marks, joiners).</summary>+ private static bool IsMark(string value) =>+ value.Length > 0 && value.All(c => c is '\u200C' or '\u200D'+ || CharUnicodeInfo.GetUnicodeCategory(c) is UnicodeCategory.NonSpacingMark or UnicodeCategory.SpacingCombiningMark or UnicodeCategory.EnclosingMark);++ /// <summary>Vowel signs written after their consonant but drawn before it.</summary>+ private static bool IsPreBase(string value) => value.Length == 1 && value[0] is '\u093F' or '\u094E' or '\u09BF' or '\u09C7' or '\u09C8'+ or '\u0A3F' or '\u0ABF' or '\u0B47' or '\u0BC6' or '\u0BC7' or '\u0BC8' or '\u0D46' or '\u0D47' or '\u0D48' or '\u0DD9' or '\u0DDA'+ or '\u0DDB' or '\u1031' or '\u17C1' or '\u17C2' or '\u17C3';++ // ───────────────────────── Direction ─────────────────────────++ /// <summary>+ /// Items read in their visual order (left to right, or right to left for <paramref name="rightToLeft"/>) put in+ /// logical order: runs of the other direction (Latin words and numbers in Arabic text, Arabic words in English text)+ /// are turned around, also over neutral items between them ("10, 20").+ /// </summary>+ private static List<T> LogicalOrder<T>(List<T> visual, Func<T, int> direction, bool rightToLeft)+ {+ var other = rightToLeft ? 1 : -1;+ var result = new List<T>(visual);+ for (var i = 0; i < result.Count;)+ {+ if (direction(result[i]) != other)+ {+ i++;+ continue;+ }+ var end = i;+ for (var j = i + 1; j < result.Count; j++)+ {+ var d = direction(result[j]);+ if (d == other)+ end = j;+ else if (d != 0)+ break;+ }+ result.Reverse(i, end - i + 1);+ i = end + 1;+ }+ return result;+ }+}diff --git a/src/Filee.Engines/Pdf/PdfDocumentReader.Layout.cs b/src/Filee.Engines/Pdf/PdfDocumentReader.Layout.csindex 5262ab51..5e9162b6 100644--- a/src/Filee.Engines/Pdf/PdfDocumentReader.Layout.cs+++ b/src/Filee.Engines/Pdf/PdfDocumentReader.Layout.cs@@ -191,18 +191,27 @@ internal sealed partial class PdfDocumentReader{var last = item.Lines[^1];var em = line.Size;- if (ListStart.IsMatch(line.Words[0].Text))+ if (ListStart.IsMatch(line.First.Text))return true;+ var listItem = ListStart.IsMatch(item.Lines[0].First.Text) || item.Lines[0].Tabs.Count > 0;+ var firstWord = line.First.Right - line.First.Left;+ if (line.RightToLeft && last.RightToLeft)+ {+ // The same, mirrored: right-to-left lines start at the right.+ var bodyRight = item.Lines.Count > 1 ? item.Lines.Skip(1).Max(l => l.Right) : last.Right;+ if (line.Right < bodyRight - 0.8 * em && !listItem && (item.Lines.Count > 1 || line.Right < last.Right - 0.8 * em))+ return true;+ var start = Math.Min(item.Left, line.Left);+ return last.Left - 0.3 * em - firstWord > start + 0.5 * em && item.Right - start > 10 * em;+ }// First-line indent: this line starts further right than the paragraph's other lines.var bodyLeft = item.Lines.Count > 1 ? item.Lines.Skip(1).Min(l => l.Left) : last.Left;- var listItem = ListStart.IsMatch(item.Lines[0].Words[0].Text) || item.Lines[0].Tabs.Count > 0;if (line.Left > bodyLeft + 0.8 * em && !listItem && (item.Lines.Count > 1 || line.Left > last.Left + 0.8 * em))return true;// The previous line ended although the next word would have fitted: the paragraph ended there.var right = Math.Max(item.Right, line.Right);- var firstWord = line.Words[0].Right - line.Words[0].Left;return last.Right + 0.3 * em + firstWord < right - 0.5 * em && right - item.Left > 10 * em;}diff --git a/src/Filee.Engines/Pdf/PdfDocumentReader.cs b/src/Filee.Engines/Pdf/PdfDocumentReader.csindex 81726f14..cb4a9058 100644--- a/src/Filee.Engines/Pdf/PdfDocumentReader.cs+++ b/src/Filee.Engines/Pdf/PdfDocumentReader.cs@@ -18,6 +18,7 @@using System.Text;using System.Text.RegularExpressions;using Filee.Engines.Hwp.Hwpx;+using Filee.Engines.Infrastructure;using PDFtoImage;using SkiaSharp;using UglyToad.PdfPig;@@ -67,8 +68,37 @@ internal sealed partial class PdfDocumentReader["ComicSansMS"] = "Comic Sans MS",["LucidaConsole"] = "Lucida Console",["PalatinoLinotype"] = "Palatino Linotype",+ ["MicrosoftSansSerif"] = "Microsoft Sans Serif",+ // Fonts for scripts that need shaping, as Word and LibreOffice name them in PDFs.+ ["ArialUnicodeMS"] = "Arial Unicode MS",+ ["NirmalaUI"] = "Nirmala UI",+ ["NirmalaText"] = "Nirmala Text",+ ["LeelawadeeUI"] = "Leelawadee UI",+ ["KhmerUI"] = "Khmer UI",+ ["LaoUI"] = "Lao UI",+ ["MyanmarText"] = "Myanmar Text",+ ["IskoolaPota"] = "Iskoola Pota",+ ["TraditionalArabic"] = "Traditional Arabic",+ ["SimplifiedArabic"] = "Simplified Arabic",+ ["SimplifiedArabicFixed"] = "Simplified Arabic Fixed",+ ["ArabicTypesetting"] = "Arabic Typesetting",+ ["SakkalMajalla"] = "Sakkal Majalla",+ ["UrduTypesetting"] = "Urdu Typesetting",+ ["AngsanaNew"] = "Angsana New",+ ["AngsanaUPC"] = "AngsanaUPC",+ ["BrowalliaNew"] = "Browallia New",+ ["CordiaNew"] = "Cordia New",};+ /// <summary>+ /// Families whose PostScript names are the family name without spaces ("NotoSansGujarati", "LiberationSerif",+ /// "DejaVuSans"): split again before each capital ("Noto Sans Gujarati").+ /// </summary>+ private static readonly Regex SpacedFamily = new("^(Noto|Liberation|DejaVu)[A-Z]", RegexOptions.Compiled | RegexOptions.CultureInvariant);++ /// <summary>Where a space goes in such a name: before a capital that follows a small letter or a digit, and between "UI" and a word.</summary>+ private static readonly Regex WordStart = new("(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])", RegexOptions.Compiled | RegexOptions.CultureInvariant);+private readonly string _path;private readonly string _mediaFolder;private readonly bool _textOnly;@@ -113,6 +143,17 @@ internal sealed partial class PdfDocumentReaderpublic double Baseline => Words[0].Baseline;public double Size => Words.Max(w => w.Size);public string Text => string.Join(' ', Words.Select(w => w.Text));++ private bool? _rightToLeft;++ /// <summary>Mostly Arabic or Hebrew: read from right to left, so its first word is the rightmost one.</summary>+ public bool RightToLeft => _rightToLeft ??= ComplexScripts.Direction(string.Concat(Words.Select(w => w.Text))) < 0;++ /// <summary>The word the line starts with in reading order.</summary>+ public TextWord First => RightToLeft ? Words[^1] : Words[0];++ /// <summary>The word the line ends with in reading order.</summary>+ public TextWord Last => RightToLeft ? Words[0] : Words[^1];}/// <summary>A paragraph, a picture or a ruled table on a page, the unit of reading order.</summary>@@ -139,6 +180,9 @@ internal sealed partial class PdfDocumentReaderpublic string Text => Table?.Text ?? string.Join(' ', Lines.Select(l => l.Text));+ /// <summary>A paragraph of mostly right-to-left lines.</summary>+ public bool RightToLeft => !IsPicture && !IsTable && Lines.Count(l => l.RightToLeft) * 2 > Lines.Count;+/// <summary>Left and right edges of the column (or the text area) the item sits in, set by the reading order.</summary>public double ContainerLeft { get; set; }public double ContainerRight { get; set; }@@ -236,10 +280,18 @@ internal sealed partial class PdfDocumentReader.Select(h => (Bounds: Shift(h.Bounds, crop), Uri: h.Uri!)).ToList();+ // Text that needs shaping (Arabic, Indic, ...) is read in content-stream order (PdfDocumentReader.ComplexText).+ var pageLetters = ContentLetters(page);+ var pageWords = HasComplexText(pageLetters)+ ? ComplexWords(pageLetters)+ : NearestNeighbourWordExtractor.Instance.GetWords(pageLetters.Where(l => l.Value.Length > 0).ToList())+ .Where(w => w.TextOrientation == TextOrientation.Horizontal && w.Letters.Count > 0)+ .Select(w => new PageWord(w.Text, w.BoundingBox, w.Letters, w.Letters[0]));+var words = new List<TextWord>();- foreach (var word in page.GetWords(NearestNeighbourWordExtractor.Instance))+ foreach (var word in pageWords){- if (word.TextOrientation != TextOrientation.Horizontal || string.IsNullOrWhiteSpace(word.Text))+ if (string.IsNullOrWhiteSpace(word.Text))continue;var letters = word.Letters.Where(l => !string.IsNullOrWhiteSpace(l.Value)).ToList();if (letters.Count == 0)@@ -247,12 +299,13 @@ internal sealed partial class PdfDocumentReader// Invisible text is the OCR layer of a scan: part of the text, not of the page's look.if (!_textOnly && letters.All(l => l.RenderingMode == TextRenderingMode.Neither))continue;- var box = Shift(word.BoundingBox, crop);- var size = Median(letters.Select(l => l.PointSize > 0 ? l.PointSize : l.FontSize));+ var lead = string.IsNullOrWhiteSpace(word.Lead.Value) ? letters[0] : word.Lead;+ var box = Shift(word.Box, crop);+ var size = Median(letters.Select(LetterSize));var center = new PdfPoint((box.Left + box.Right) / 2, (box.Top + box.Bottom) / 2);var link = links.FirstOrDefault(l => Inside(l.Bounds, center)).Uri;words.Add(new TextWord(CleanText(word.Text), box.Left, box.Right, box.Top, box.Bottom,- letters[0].StartBaseLine.Y - crop.Bottom, Math.Max(1, size), Format(letters[0], size), link));+ lead.StartBaseLine.Y - crop.Bottom, Math.Max(1, size), Format(lead, size), link));}if (words.Count == 0 || (rotated && !_textOnly))@@ -323,6 +376,13 @@ internal sealed partial class PdfDocumentReader}if (KnownFonts.TryGetValue(name, out var known))return known;+ if (SpacedFamily.IsMatch(name))+ {+ // "NotoSansCJKkr" → "Noto Sans CJK KR"+ var cjk = Regex.Match(name, "CJK(kr|jp|sc|tc|hk)$", RegexOptions.CultureInvariant);+ var spaced = WordStart.Replace(cjk.Success ? name[..cjk.Index] : name, " ").Replace("Deja Vu", "DejaVu", StringComparison.Ordinal);+ return cjk.Success ? $"{spaced} CJK {cjk.Groups[1].Value.ToUpperInvariant()}" : spaced;+ }return name.Length < 3 || Regex.IsMatch(name, "^(F|T3Font_?|Font)\\d+$", RegexOptions.CultureInvariant) ? null : name;}@@ -680,48 +740,52 @@ internal sealed partial class PdfDocumentReaderif (headingLevels.TryGetValue(Math.Round(size), out var level) && item.Lines.Count <= 3 && item.Text.Length <= 200)paragraph.HeadingLevel = level;- // Alignment and indents relative to the column (or text area) the paragraph is in.+ // Alignment and indents relative to the column (or text area) the paragraph is in. A right-to-left paragraph+ // starts at the right: its alignment and indents are measured from that side (HParaFormat.RightToLeft).+ var rightToLeft = item.RightToLeft;var containerWidth = Math.Max(1, item.ContainerRight - item.ContainerLeft);var lefts = item.Lines.Select(l => l.Left - item.ContainerLeft).ToList();var rights = item.Lines.Select(l => item.ContainerRight - l.Right).ToList();+ var (starts, ends) = rightToLeft ? (rights, lefts) : (lefts, rights);var tolerance = Math.Max(3, containerWidth * 0.03);HAlign align;if (item.Lines.All(l => Math.Abs((l.Left - item.ContainerLeft) - (item.ContainerRight - l.Right)) < tolerance) && lefts.Min() > containerWidth * 0.04)align = HAlign.Center;- else if (rights.All(r => r < 3) && lefts.Min() > containerWidth * 0.15)+ else if (ends.All(r => r < 3) && starts.Min() > containerWidth * 0.15)align = HAlign.Right;- else if (item.Lines.Count >= 2 && rights.Take(rights.Count - 1).All(r => r < 2.5) && item.Width > containerWidth * 0.5)+ else if (item.Lines.Count >= 2 && ends.Take(ends.Count - 1).All(r => r < 2.5) && item.Width > containerWidth * 0.5)align = HAlign.Justify;elsealign = HAlign.Left;- int? left = null, firstLine = null;+ int? start = null, firstLine = null;if (align is HAlign.Left or HAlign.Justify){- var body = item.Lines.Count > 1 ? lefts.Skip(1).Min() : lefts[0];+ var body = item.Lines.Count > 1 ? starts.Skip(1).Min() : starts[0];if (body > 2)- left = Hwp(body);- var first = lefts[0] - Math.Max(0, body);+ start = Hwp(body);+ var first = starts[0] - Math.Max(0, body);if (Math.Abs(first) > 2)firstLine = Hwp(first);}// A tabbed row: a left tab stop where each part starts in the PDF.- var tabs = item.Lines.SelectMany(l => l.Tabs.Select(t => Hwp(l.Words[t].Left - item.ContainerLeft))).Distinct().Order()+ var tabs = rightToLeft ? [] : item.Lines.SelectMany(l => l.Tabs.Select(t => Hwp(l.Words[t].Left - item.ContainerLeft))).Distinct().Order().Select(position => new HTabStop(position, HTabKind.Left, "NONE")).ToList();var pitch = item.Lines.Count >= 2 ? Pitch(item) : size * lineRatio;paragraph.Format = new HParaFormat(Align: align,- Left: left,+ Left: start,FirstLine: firstLine,Tabs: tabs.Count > 0 ? tabs : null,Before: SpaceBefore(item, previous, lineRatio),After: 0,// "At least" the PDF's line distance: close to the original and never cuts off a larger font.- LineSpacing: new HLineSpacing(HLineSpacingKind.AtLeast, Hwp(Math.Clamp(pitch, size, size * 3))));+ LineSpacing: new HLineSpacing(HLineSpacingKind.AtLeast, Hwp(Math.Clamp(pitch, size, size * 3))),+ RightToLeft: rightToLeft ? true : null);paragraph.MarkFormat = new HCharFormat(Size: (int)(Math.Round(size * 2) * 50));- Runs(item, paragraph.Inlines);+ Runs(item, paragraph.Inlines, rightToLeft);return paragraph;}@@ -745,15 +809,17 @@ internal sealed partial class PdfDocumentReader/// Words joined into runs of equal formatting; line ends become spaces (not inside CJK text or after a hyphen), or/// line breaks where the line ended early on purpose. Tabs of a tabbed row stay tabs./// </summary>- private static void Runs(Item item, List<HInline> output)+ private static void Runs(Item item, List<HInline> output, bool rightToLeft){var pieces = new List<(string Text, HCharFormat Format, string? Link)>();for (var l = 0; l < item.Lines.Count; l++){var line = item.Lines[l];- for (var w = 0; w < line.Words.Count; w++)+ // Words in reading order: a tabbed row keeps its parts where they are.+ var words = line.Tabs.Count > 0 ? line.Words : InReadingOrder(line.Words, rightToLeft);+ for (var w = 0; w < words.Count; w++){- var word = line.Words[w];+ var word = words[w];var text = word.Text;if (pieces.Count > 0){@@ -770,7 +836,7 @@ internal sealed partial class PdfDocumentReader{pieces[^1] = (previousText[..^1], previousFormat, previousLink); // hyphenated at the line end}- else if (EndedEarly(item, l))+ else if (EndedEarly(item, l, rightToLeft)){pieces.Add(("\n", word.Format, null));}@@ -816,20 +882,57 @@ internal sealed partial class PdfDocumentReader/// that within its own width; past it only when the paragraph is clearly narrower than its column (an indented/// block of short lines), not a quote with a right indent./// </summary>- private static bool EndedEarly(Item item, int l)+ private static bool EndedEarly(Item item, int l, bool rightToLeft){var previous = item.Lines[l - 1];var line = item.Lines[l];- if (previous.Words[^1].Text.EndsWith('-'))+ if (previous.Last.Text.EndsWith('-'))return false;var em = line.Size;- var end = previous.Right + 0.3 * em + (line.Words[0].Right - line.Words[0].Left);+ var column = item.ContainerRight - item.ContainerLeft;+ var firstWord = line.First.Right - line.First.Left;+ if (rightToLeft)+ {+ // Mirrored: right-to-left lines end at the left.+ var start = previous.Left - 0.3 * em - firstWord;+ if (start > item.Left + 0.5 * em)+ return true;+ return start > item.ContainerLeft + 0.5 * em && item.Left - item.ContainerLeft > 0.25 * column;+ }+ var end = previous.Right + 0.3 * em + firstWord;if (end < item.Right - 0.5 * em)return true;- var column = item.ContainerRight - item.ContainerLeft;return end < item.ContainerRight - 0.5 * em && item.ContainerRight - item.Right > 0.25 * column;}+ /// <summary>+ /// A line's words (left to right) in reading order: from right to left in a right-to-left paragraph, with numbers+ /// and Latin words in it kept left to right, and Arabic or Hebrew words in a left-to-right line turned around.+ /// </summary>+ private static List<TextWord> InReadingOrder(List<TextWord> words, bool rightToLeft)+ {+ if (!rightToLeft && !words.Any(w => ComplexScripts.Direction(w.Text) < 0))+ return words;+ var ordered = rightToLeft+ ? LogicalOrder(Enumerable.Reverse(words).ToList(), w => ComplexScripts.Direction(w.Text), rightToLeft: true)+ : LogicalOrder(words, w => ComplexScripts.Direction(w.Text), rightToLeft: false);+ // A full stop or comma after a word of the other direction is drawn on that word's far side ("2024." at the end+ // of an Arabic sentence shows as ".2024"): it comes first in the word's letters and goes back to the end.+ var other = rightToLeft ? 1 : -1;+ for (var i = 0; i < ordered.Count; i++)+ {+ var text = ordered[i].Text;+ var lead = 0;+ while (lead < text.Length - 1 && SentencePunctuation.Contains(text[lead]))+ lead++;+ if (lead > 0 && ComplexScripts.Direction(text) == other)+ ordered[i] = ordered[i] with { Text = text[lead..] + text[..lead] };+ }+ return ordered;+ }++ private const string SentencePunctuation = ".,:;!?،؛؟";+private static IEnumerable<(string Text, HCharFormat Format, string? Link)> Merge(List<(string Text, HCharFormat Format, string? Link)> pieces){var sb = new StringBuilder();diff --git a/tests/Filee.Engines.Tests/ComplexScriptTests.cs b/tests/Filee.Engines.Tests/ComplexScriptTests.csnew file mode 100644index 00000000..d2296675--- /dev/null+++ b/tests/Filee.Engines.Tests/ComplexScriptTests.cs@@ -0,0 +1,230 @@+// Text that needs shaping: Arabic, Hebrew, the Indic scripts, Thai, ... (issues #185 Gujarati and #202 Arabic).+// * Documents → PDF: rhwp draws such text unshaped, so a document with it goes to LibreOffice, or is refused with that+// reason when LibreOffice is missing (ComplexScripts finds the text, RhwpConverter's PDF edges are Unshaped).+// * PDF → DOCX / TXT: the reader takes ActualText, keeps marks with their letters in content-stream order, reads+// right-to-left words and lines from the right and marks such paragraphs right to left.+// The PDFs are written glyph by glyph (GlyphPdfBuilder) the way the shaping engines leave them.++using System.Text;+using System.Xml.Linq;+using Filee.Core.Conversion;+using Filee.Core.Presets;+using Filee.Engines.Infrastructure;+using Filee.Engines.Pdf;+using static Filee.Engines.Tests.DocxAssert;++namespace Filee.Engines.Tests;++public class ComplexScriptTests(EngineFixture fx) : IClassFixture<EngineFixture>+{+ private static string PlainText(string pdf) => PdfDocumentReader.PlainText(PdfDocumentReader.ReadText(pdf)).Trim();++ // ───────────────────────── Finding the text ─────────────────────────++ [Fact]+ public void Scripts_that_need_shaping_are_found_in_documents()+ {+ var folder = fx.NewFolder();+ string Docx(string name, string text, string? styles = null)+ {+ var builder = new DocxBuilder();+ if (styles is not null)+ builder.Styles = styles;+ builder.Paragraph(DocxBuilder.P(DocxBuilder.R(text)));+ return builder.Save(Path.Combine(folder, name));+ }+ string Text(string name, string text)+ {+ var path = Path.Combine(folder, name);+ File.WriteAllText(path, text, new UTF8Encoding(false));+ return path;+ }++ Assert.Equal("Gujarati", ComplexScripts.FindInFile(Docx("gujarati.docx", "સૌરાષ્ટ્ર ઘરખેડ"), "docx"));+ Assert.Equal("Arabic", ComplexScripts.FindInFile(Docx("arabic.docx", "Report: مرحبا بالعالم"), "docx"));+ Assert.Null(ComplexScripts.FindInFile(Docx("plain.docx", "English, 한국어, 中文, Ελληνικά, Русский"), "docx"));+ // Style and font names per script are no text of the document.+ Assert.Null(ComplexScripts.FindInFile(Docx("styles.docx", "English only",+ $"<w:styles {DocxBuilder.Namespaces}><w:style w:type=\"paragraph\" w:styleId=\"Title\"><w:name w:val=\"عنوان\"/></w:style></w:styles>"), "docx"));++ Assert.Equal("Devanagari", ComplexScripts.FindInFile(Text("hindi.txt", "Title\nहिन्दी भाषा"), "txt"));+ Assert.Equal("Hebrew", ComplexScripts.FindInFile(Text("hebrew.html", "<p>שלום</p>"), "html"));+ Assert.Equal("Thai", ComplexScripts.FindInFile(Text("thai.rtf", @"{\rtf1 \u3585?\u3634?}"), "rtf"));+ Assert.Null(ComplexScripts.FindInFile(Text("plain.md", "# Title\n\nC:\\users\\me and © 2026"), "md"));+ Assert.Null(ComplexScripts.FindInFile(Text("binary.hwp", "ignored"), "hwp"));+ }++ [Fact]+ public async Task Scripts_are_found_in_hwpx_sections()+ {+ var folder = fx.NewFolder();+ var txt = Path.Combine(folder, "tamil.txt");+ await File.WriteAllTextAsync(txt, "தமிழ் மொழி\n한글 문단", TestContext.Current.CancellationToken);+ var job = await fx.ConvertAsync([txt], new Preset { TargetFormat = "hwpx" });+ Assert.Equal(JobState.Completed, job.State);++ Assert.Equal("Tamil", ComplexScripts.FindInFile(job.Outputs.Single(), "hwpx"));+ Assert.Null(ComplexScripts.FindInFile(await fx.MakeHwpxAsync(fx.NewFolder()), "hwpx"));+ }++ [Fact]+ public void Rhwp_says_it_draws_pdf_text_unshaped()+ {+ var rhwp = fx.Converters.Single(c => c.Id == "rhwp");+ Assert.All(rhwp.Edges.Where(e => e.To == "pdf"), e => Assert.True(e.Unshaped));+ Assert.All(rhwp.Edges.Where(e => e.To != "pdf"), e => Assert.False(e.Unshaped));+ Assert.IsAssignableFrom<ITextShapingCheck>(rhwp);+ }++ [Fact]+ public async Task A_gujarati_document_goes_to_libreoffice_or_is_refused_with_the_reason()+ {+ var available = fx.Converters.Where(c => fx.Catalog.StatusOf(c).IsAvailable).Select(c => c.Id).ToHashSet();+ Assert.SkipUnless(available.Contains("rhwp") || available.Contains("libreoffice"), "neither rhwp nor LibreOffice is available");+ var builder = new DocxBuilder();+ builder.Paragraph(DocxBuilder.P(DocxBuilder.R("સૌરાષ્ટ્ર ઘરખેડ ગણોત વહીવટ")));+ var docx = builder.Save(Path.Combine(fx.NewFolder(), "gujarati.docx"));++ var job = await fx.ConvertAsync([docx], new Preset { TargetFormat = "pdf" });++ var file = Assert.Single(job.Files);+ if (available.Contains("libreoffice"))+ {+ Assert.Equal(FileState.Done, file.State);+ }+ else+ {+ Assert.Equal(FileState.Failed, file.State);+ Assert.Equal("error.needs_shaping", file.ErrorKey);+ Assert.Equal("Gujarati", file.ErrorDetail);+ }+ }++ // ───────────────────────── Reading PDFs ─────────────────────────++ /// <summary>+ /// Text laid out like rhwp did: one glyph per character, a placeholder glyph (a dotted circle, here mapped to+ /// <paramref name="placeholder"/>) before every mark, bases overlapping the marks.+ /// </summary>+ private static void Unshaped(GlyphPdfBuilder pdf, string text, double x, double y, string placeholder, double size = 14)+ {+ foreach (var word in text.Split(' '))+ {+ foreach (var c in word)+ {+ if (char.GetUnicodeCategory(c) is System.Globalization.UnicodeCategory.NonSpacingMark or System.Globalization.UnicodeCategory.SpacingCombiningMark)+ {+ pdf.Glyph(placeholder, x, y, 0.6 * size, size);+ x += 0.6 * size;+ var spacing = char.GetUnicodeCategory(c) == System.Globalization.UnicodeCategory.SpacingCombiningMark;+ pdf.Glyph(c.ToString(), x, y, spacing ? 0.27 * size : 0, size);+ x += spacing ? 0.27 * size : 0;+ }+ else+ {+ pdf.Glyph(c.ToString(), x - 0.1 * size, y, 0.55 * size, size);+ x += 0.45 * size;+ }+ }+ x += 1.2 * size;+ }+ }++ [Fact]+ public void Text_drawn_without_shaping_is_read_in_its_logical_order()+ {+ // Issue #185's PDF: Gujarati from rhwp, its dotted circles mapped to U+0002; Hindi with them mapped to a vowel sign.+ var pdf = new GlyphPdfBuilder();+ Unshaped(pdf, "સૌરાષ્ટ્ર ઘરખેડ ગણોત", 72, 100, "\u0002");+ Unshaped(pdf, "भाषा में दस्तावेज़", 72, 140, "\u093F");+ var path = pdf.Save(Path.Combine(fx.NewFolder(), "unshaped.pdf"));++ Assert.Equal("સૌરાષ્ટ્ર ઘરખેડ ગણોત\r\n\r\nभाषा में दस्तावेज़", PlainText(path));+ }++ [Fact]+ public void Actual_text_replaces_the_glyphs_it_covers()+ {+ // LibreOffice: a conjunct drawn as one glyph and a vowel sign drawn before its consonant carry their text.+ var pdf = new GlyphPdfBuilder();+ var x = 72.0;+ pdf.Glyph("ર", x, 100, 7).Glyph("\u0ABE", x += 7, 100, 4);+ pdf.ActualText("ષ્ટ્ર", p => p.Glyph("ષ", x += 4, 100, 12));+ x += 12 + 4;+ pdf.ActualText("નિ", p => p.Glyph("\u0ABF", x, 100, 3).Glyph("ન", x + 3, 100, 8));+ pdf.Glyph("ય", x += 11, 100, 8).Glyph("મ", x + 8, 100, 9);+ // Latin text keeps working on the same page, with an ActualText for a ligature.+ pdf.Run("Office ", 72, 130, 6);+ pdf.ActualText("fi", p => p.Glyph("fi", 72 + 7 * 6, 130, 6));+ pdf.Run("le", 72 + 8 * 6, 130, 6);+ var path = pdf.Save(Path.Combine(fx.NewFolder(), "actualtext.pdf"));++ Assert.Equal("રાષ્ટ્ર નિયમ\r\n\r\nOffice file", PlainText(path));+ }++ [Fact]+ public void Vowel_signs_drawn_before_their_consonant_follow_it()+ {+ // Word's PDFs keep the visual order of ि and give no ActualText: ि क → कि.+ var pdf = new GlyphPdfBuilder();+ var x = 72.0;+ pdf.Glyph("\u093F", x, 100, 3).Glyph("क", x + 3, 100, 8).Glyph("स", x + 11, 100, 8).Glyph("\u0940", x + 19, 100, 3);+ x += 30;+ pdf.Glyph("\u093F", x, 100, 3).Glyph("ह", x + 3, 100, 7).Glyph("न्", x + 10, 100, 5).Glyph("द", x + 15, 100, 7).Glyph("\u0940", x + 22, 100, 3);+ var path = pdf.Save(Path.Combine(fx.NewFolder(), "prebase.pdf"));++ Assert.Equal("किसी हिन्दी", PlainText(path));+ }++ /// <summary>+ /// A right-to-left line as Word and LibreOffice draw it: words from the right edge leftwards, the glyphs of each+ /// word left to right (so an Arabic word's letters are reversed in the stream), numbers left to right.+ /// </summary>+ /// <returns>The left edge of the last word.</returns>+ private static double RightToLeft(GlyphPdfBuilder pdf, IEnumerable<string> words, double right, double y, double advance = 6)+ {+ var x = right + advance;+ foreach (var word in words)+ {+ x -= advance; // the space between words+ var visual = ComplexScripts.Direction(word) < 0 ? new string([.. word.Reverse()]) : word;+ x -= visual.Length * advance;+ pdf.Run(visual, x, y, advance);+ }+ return x;+ }++ [Fact]+ public async Task Arabic_is_read_from_right_to_left_into_a_right_to_left_paragraph()+ {+ // Issue #202: Arabic PDF → DOCX. A two-line paragraph with a number and an English word in it, a short one with+ // harakat (marks after their letter in the stream), then an English paragraph.+ var pdf = new GlyphPdfBuilder();+ RightToLeft(pdf, ["هذا", "نص", "عربي", "للاختبار", "مع", "كلمة", "English", "في", "الوسط", "والرقم", "وهذه", "جملة", "طويلة", "جدا"], 523, 100);+ // The second line ends the sentence: "2024." shows as ".2024" left of the last Arabic word.+ var end = RightToLeft(pdf, ["اللغة", "العربية", "جميلة", "2024"], 523, 115);+ pdf.Glyph(".", end - 6, 115, 6);+ // مُحَمَّد in visual order: د, م with fatha and shadda, ح with fatha, م with damma.+ pdf.Glyph("د", 470, 160, 6).Glyph("م", 476, 160, 6).Glyph("\u064E", 476, 160, 0).Glyph("\u0651", 476, 160, 0)+ .Glyph("ح", 482, 160, 6).Glyph("\u064E", 482, 160, 0).Glyph("م", 488, 160, 6).Glyph("\u064F", 488, 160, 0);+ pdf.Run("Plain English paragraph.", 72, 200, 6);+ var path = pdf.Save(Path.Combine(fx.NewFolder(), "arabic.pdf"));++ Assert.Equal(+ "هذا نص عربي للاختبار مع كلمة English في الوسط والرقم وهذه جملة طويلة جدا اللغة العربية جميلة 2024.\r\n\r\n" ++ "مُحَمَّد\r\n\r\nPlain English paragraph.", PlainText(path));++ var job = await fx.ConvertAsync([path], new Preset { TargetFormat = "docx" });+ Assert.Equal(JobState.Completed, job.State);+ var docx = job.Outputs.Single();+ ValidPackage(docx);+ var paragraphs = Body(docx).Descendants(W + "p").Where(p => p.Descendants(W + "t").Any()).ToList();+ Assert.Equal(3, paragraphs.Count);+ bool Bidi(XElement p) => p.Element(W + "pPr")?.Element(W + "bidi") is not null;+ Assert.Equal([true, true, false], paragraphs.Select(Bidi));+ // Arabic runs are right to left (Word then uses their complex script font and size), English ones are not.+ var runs = paragraphs[0].Descendants(W + "r").Where(r => r.Element(W + "t") is not null).ToList();+ Assert.All(runs.Where(r => ComplexScripts.Direction(r.Element(W + "t")!.Value) < 0), r => Assert.NotNull(r.Element(W + "rPr")?.Element(W + "rtl")));+ Assert.Empty(paragraphs[2].Descendants(W + "rtl"));+ }+}diff --git a/tests/Filee.Engines.Tests/GlyphPdfBuilder.cs b/tests/Filee.Engines.Tests/GlyphPdfBuilder.csnew file mode 100644index 00000000..f3d195d7--- /dev/null+++ b/tests/Filee.Engines.Tests/GlyphPdfBuilder.cs@@ -0,0 +1,112 @@+// Writes one-page PDFs glyph by glyph, for the PDF reader's complex-script tests: each glyph is placed on its own at a+// given position and width, in the order given (the content-stream order), with the text its ToUnicode entry gives it,+// and runs of glyphs can carry an /ActualText. That is how shaping engines leave Indic and Arabic text in a PDF (marks+// with no width on top of their letter, vowel signs before their consonant, right-to-left glyphs drawn left to right,+// placeholder glyphs), which the PdfPig writer behind PdfBuilder can't produce. The font is a Type 3 font whose glyphs+// draw nothing: only the positions, widths and ToUnicode entries matter.++using System.Globalization;+using System.Text;++namespace Filee.Engines.Tests;++/// <summary>A one-page A4 PDF of individually placed glyphs; <c>y</c> is the baseline in points from the top.</summary>+internal sealed class GlyphPdfBuilder+{+ private const double Height = 842;+ private readonly StringBuilder _content = new();+ private readonly Dictionary<string, int> _codes = [];+ private readonly Dictionary<int, double> _widths = [];++ /// <summary>+ /// One glyph whose ToUnicode text is <paramref name="text"/>, its origin at <paramref name="x"/>, advancing by+ /// <paramref name="width"/> points (0 for a mark drawn on the glyph before it).+ /// </summary>+ public GlyphPdfBuilder Glyph(string text, double x, double y, double width, double size = 12)+ {+ if (!_codes.TryGetValue(text + "|" + Number(width / size), out var code))+ {+ code = 0x21 + _codes.Count;+ if (code > 0xFE)+ throw new InvalidOperationException("Too many different glyphs for one test font.");+ _codes[text + "|" + Number(width / size)] = code;+ _widths[code] = width / size * 1000;+ }+ _content.Append(CultureInfo.InvariantCulture, $"BT /F1 {Number(size)} Tf 1 0 0 1 {Number(x)} {Number(Height - y)} Tm <{code:X2}> Tj ET\n");+ return this;+ }++ /// <summary>Glyphs one after the other from <paramref name="x"/>, each <paramref name="advance"/> wide (a word of plain letters).</summary>+ public GlyphPdfBuilder Run(string text, double x, double y, double advance, double size = 12)+ {+ foreach (var letter in text.EnumerateRunes())+ {+ Glyph(letter.ToString(), x, y, advance, size);+ x += advance;+ }+ return this;+ }++ /// <summary>The glyphs added in <paramref name="glyphs"/> stand for <paramref name="text"/> (/Span with /ActualText).</summary>+ public GlyphPdfBuilder ActualText(string text, Action<GlyphPdfBuilder> glyphs)+ {+ _content.Append("/Span <</ActualText <FEFF").Append(Utf16Hex(text)).Append(">>> BDC\n");+ glyphs(this);+ _content.Append("EMC\n");+ return this;+ }++ public string Save(string path)+ {+ var codes = _codes.OrderBy(c => c.Value).ToList();+ var first = codes.Count == 0 ? 0x21 : codes[0].Value;+ var last = codes.Count == 0 ? 0x21 : codes[^1].Value;+ var widths = string.Join(' ', Enumerable.Range(first, last - first + 1).Select(c => Number(_widths.GetValueOrDefault(c))));+ var names = string.Join(' ', Enumerable.Range(first, last - first + 1).Select(c => $"/g{c}"));+ var cmap = new StringBuilder();+ cmap.Append("/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n")+ .Append("/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n")+ .Append("/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n")+ .Append("1 begincodespacerange\n<00> <FF>\nendcodespacerange\n")+ .Append(CultureInfo.InvariantCulture, $"{codes.Count} beginbfchar\n");+ foreach (var (key, code) in codes)+ cmap.Append(CultureInfo.InvariantCulture, $"<{code:X2}> <{Utf16Hex(key[..key.LastIndexOf('|')])}>\n");+ cmap.Append("endbfchar\nendcmap\nCMapName currentdict /CIDInit /ResourceSet defineresource pop\nend\nend\n");++ var content = _content.ToString();+ string[] objects =+ [+ "<< /Type /Catalog /Pages 2 0 R >>",+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>",+ $"<< /Type /Font /Subtype /Type3 /FontBBox [0 -200 1000 800] /FontMatrix [0.001 0 0 0.001 0 0] /CharProcs 7 0 R " ++ $"/Encoding << /Type /Encoding /Differences [{first} {names}] >> /FirstChar {first} /LastChar {last} /Widths [{widths}] " ++ "/ToUnicode 6 0 R /Resources << >> >>",+ Stream(content),+ Stream(cmap.ToString()),+ $"<< {string.Join(' ', Enumerable.Range(first, last - first + 1).Select(c => $"/g{c} 8 0 R"))} >>",+ Stream("0 0 d0\n"),+ ];++ var pdf = new StringBuilder("%PDF-1.7\n");+ var offsets = new List<int>();+ for (var i = 0; i < objects.Length; i++)+ {+ offsets.Add(Encoding.ASCII.GetByteCount(pdf.ToString()));+ pdf.Append(CultureInfo.InvariantCulture, $"{i + 1} 0 obj\n{objects[i]}\nendobj\n");+ }+ var xref = Encoding.ASCII.GetByteCount(pdf.ToString());+ pdf.Append(CultureInfo.InvariantCulture, $"xref\n0 {objects.Length + 1}\n0000000000 65535 f \n");+ foreach (var offset in offsets)+ pdf.Append(CultureInfo.InvariantCulture, $"{offset:D10} 00000 n \n");+ pdf.Append(CultureInfo.InvariantCulture, $"trailer\n<< /Size {objects.Length + 1} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n");+ File.WriteAllBytes(path, Encoding.ASCII.GetBytes(pdf.ToString()));+ return path;++ static string Stream(string data) => $"<< /Length {Encoding.ASCII.GetByteCount(data)} >>\nstream\n{data}endstream";+ }++ private static string Utf16Hex(string text) => Convert.ToHexString(Encoding.BigEndianUnicode.GetBytes(text));++ private static string Number(double value) => value.ToString("0.###", CultureInfo.InvariantCulture);+}diff --git a/tests/Filee.Engines.Tests/PdfReaderTests.cs b/tests/Filee.Engines.Tests/PdfReaderTests.csindex 125ba028..7b21386b 100644--- a/tests/Filee.Engines.Tests/PdfReaderTests.cs+++ b/tests/Filee.Engines.Tests/PdfReaderTests.cs@@ -369,6 +369,16 @@ public class PdfReaderTests(EngineFixture fx) : IClassFixture<EngineFixture>[InlineData("Helvetica-Oblique", "Arial")][InlineData("QWERTY+MalgunGothic,Bold", "Malgun Gothic")][InlineData("NanumGothic", "NanumGothic")]+ [InlineData("TGNRPS+ArialUnicodeMS", "Arial Unicode MS")]+ [InlineData("RESVUN+NirmalaUI-Bold", "Nirmala UI")]+ [InlineData("BAAAAA+ArialMT", "Arial")]+ [InlineData("TraditionalArabic,Bold", "Traditional Arabic")]+ [InlineData("NotoSansGujarati-Regular", "Noto Sans Gujarati")]+ [InlineData("NotoNaskhArabicUI-Bold", "Noto Naskh Arabic UI")]+ [InlineData("NotoSansCJKkr-Regular", "Noto Sans CJK KR")]+ [InlineData("DejaVuSans-Bold", "DejaVu Sans")]+ [InlineData("LiberationSerif-Italic", "Liberation Serif")]+ [InlineData("Mangal", "Mangal")][InlineData("F1", null)][InlineData("T3Font_2", null)]public void Font_names_become_families(string postScript, string? family) =>