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.

Merge feat/hwpx-reader

KnifeLemon95795178e862
diff --cc docs/ENGINES.md
index 42033ae5,af4d31ea..9c62c115
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@@ -135,183 -92,37 +135,214 @@@ text) and LibreOffice + H2Orestart (ope
Not converted: Word charts, SmartArt, equations (kept as text), free-form shapes, tracked changes and comments.
+## Spreadsheets
+
+`SpreadsheetConverter` (engine id `spreadsheet`) converts between XLSX, XLS (also `.xlt`), ODS, CSV and TSV (also
+`.tab`) in-process; every format goes through one in-memory workbook (`Office/Sheets/Workbook.cs`) whose cells keep
+the text the spreadsheet shows, the value behind it and its Excel number format.
+
+| Format | Read | Written |
+|---|---|---|
+| XLSX | own reader: values, number formats, fonts, fills, borders, alignment, merges, widths, heights, hidden rows / columns / sheets, frozen rows | every sheet, numbers and dates as numbers with their formats, booleans, styles, merges, widths, heights, hidden rows / columns, frozen rows |
+| XLS (Excel 97–2003, also Excel 5/95) | ExcelDataReader (MIT): values, number formats, merges, horizontal / vertical alignment; widths, heights and hidden rows / columns from the BIFF records (`XlsLayout.cs`) | no (LibreOffice) |
+| ODS | own reader (`content.xml`, `styles.xml`, `settings.xml`): repeated rows / columns (the empty repeats up to the end of the sheet are skipped), spans, every value type, the text Calc shows (`text:p`), data styles as Excel codes, cell styles, widths, heights, hidden rows / columns / sheets, frozen and header rows | every sheet, typed cells (float, percentage, currency, date, time, boolean) with data styles and the shown text, styles, merges, widths, heights, hidden rows / columns, frozen rows |
+| CSV / TSV | delimiter (CSV: comma, semicolon or tab; TSV: tab) and encoding (UTF-8 / UTF-16 with BOM, else CP949) | UTF-8 with BOM, CRLF, one file per sheet |
+
+- Number formats: Excel codes and OpenDocument data styles are converted both ways (`OdsNumberStyles.cs`) for
+ digits, decimals, grouping, thousands scaling, percent, scientific, currency symbols, literal text, colours,
+ positive / negative / zero sections, dates, times and durations. Codes with conditions (`[>100]`), fractions or
+ text between digits are written as plain numbers (General).
+- Column widths use Excel's unit (a digit of Calibri 11 = 7 px); in ODS a character is 5.25 pt. LibreOffice
+ measures with its own fonts, so a width can differ by up to a fifth after LibreOffice opens the file.
+- XLS cells keep the default font, fill and borders (ExcelDataReader does not expose them); XLS output still
+ needs LibreOffice. Password-protected XLS and ODS files stop with a clear message.
+- Not converted: formulas (their cached results are kept), charts, pictures, comments, conditional formatting,
+ data validation, print areas and page breaks.
+
+## Fonts
+
+Fonts are converted in-process (`Filee.Engines/Fonts`); zlib and Brotli come with .NET. The input format is
+recognised by content, so a mislabelled file still converts.
+
+- **WOFF 1.0**: every table zlib-compressed (stored as-is when that isn't smaller). Lossless both ways.
+- **WOFF2**: one Brotli stream at the highest quality with the glyf/loca transform and, where it applies, the hmtx
+ transform, so files come out the size of Google's reference encoder's. Reading handles both transforms, the
+ overlap bitmap, untransformed tables and the first font of a WOFF2 collection. Like other encoders, Filee drops
+ the DSIG signature and sets bit 11 of head.flags. Brotli is slow on big fonts (about 10 s per MB, so about a
+ minute for a 4.6 MB CJK font); the job shows progress and can be cancelled.
+- **EOT**: written as version 0x00020001 (names and OS/2 fields in the header, no MicroType Express compression, no
+ XOR obfuscation, no URL restriction). Uncompressed EOT files are read (XOR-obfuscated ones too); MTX-compressed
+ ones fail with a clear message.
+- **TTF → OTF** keeps the TrueType outlines: TrueType-flavoured OpenType is valid OpenType and what systems and
+ browsers expect; cubic outlines would gain nothing.
+- **OTF with CFF outlines → TTF** (and → EOT, because Internet Explorer renders only TrueType outlines in EOT)
+ converts the glyphs: Type 2 charstrings with subroutines, flex, seac accents and CID-keyed fonts are drawn, curves
+ are approximated with quadratic splines within 1/1000 em (the approach of fontTools' cu2qu) and contours are
+ reversed to TrueType's direction. glyf, loca, maxp 1.0 and post (format 2 with the CFF glyph names, format 3 for
+ CID fonts) are built; head, hhea, hmtx and, from VORG, vmtx are updated; CFF, VORG and DSIG are dropped; every
+ other table (cmap, name, OS/2, GSUB, GPOS, kern, ...) is kept. PostScript hints are not converted: the font gets a
+ gasp table (smoothing at every size) and a prep that switches on dropout control instead.
+- Not supported: CFF2 (variable) outlines to TTF or EOT (to WOFF, WOFF2 and OTF they convert), writing font
+ collections, and WOFF/WOFF2 extended metadata (dropped).
+
+`tests/Filee.Engines.Tests/FontTests.cs` checks every conversion with small OFL fonts in
+`tests/Filee.Engines.Tests/Fonts` (see `OFL.txt` there): round trips keep every table byte for byte, a WOFF2 made
+by Google's encoder decodes to the source font, and converted CFF glyphs are compared with the originals in Skia.
+
+## DOCX writer
+
+The counterpart of the HWPX writer: `Hwp/Hwpx/Docx/DocxWriter*.cs` writes WordprocessingML by hand from the same
+document model, so every reader in `DocumentReaders` can produce an editable Word file without Word, LibreOffice or
+Pandoc. It writes:
+
+- sections with page size, orientation, margins (header and footer distances), columns, page number restarts;
+ columns that change mid-page become continuous section breaks, as Word does it;
+- headers and footers (odd/even pages, "different first page") with PAGE / NUMPAGES fields; a section without its
+ own header gets an empty one, since Word would otherwise repeat the previous section's;
+- paragraphs: alignment, indents (first line / hanging), spacing, line spacing (the model's percent of the font
+ size is converted back to Word's multiple, the inverse of DocxReader), keep with next / keep lines / widow
+ control, tab stops with leaders, page and column breaks;
+- runs: Latin and East Asian fonts, size, bold, italic, underline, strike, colour, highlight (Word's named colours)
+ or shading, super/subscript, letter spacing;
+- headings as Word's built-in "heading 1".."heading 9" styles (outline levels, so the navigation pane and tables of
+ contents work), lists as real numbering definitions (1., a., 가., ①, bullets, start numbers, nine levels);
+- tables with column widths, horizontal and vertical merges, borders, fills, cell alignment, row heights and
+ repeated header rows;
+- pictures inline and floating (anchored to page, margin, column or paragraph, with wrapping), text boxes and
+ rectangles / rounded rectangles / ellipses / lines as Word 2010 shapes (wps) with solid or gradient fills and
+ outlines, hyperlinks (web and to bookmarks), bookmarks, footnotes and endnotes.
+
+Parts, relationships and content types are written per part (pictures and links in headers and notes are related
+from their own part), children in schema order. The tests validate every file with the Open XML SDK schema
+validator, read it back with DocxReader (DOCX → model → DOCX → model keeps the layout) and convert it with
+LibreOffice as an independent reader, see `tests/Filee.Engines.Tests/DocxWriterTests.cs`.
+
+Its edges cost 8, less than Pandoc's and LibreOffice's direct conversions, so Markdown → DOCX, PDF → DOCX, ... use
+it. DOCX → DOCX is no edge; the Word variants are the Office Open XML engine's job.
+
+## PDF reader
+
+`Pdf/PdfDocumentReader*.cs` reads PDFs with PdfPig (Apache-2.0) into the document model, for PDF → DOCX, HWPX and
+(with `PdfTextConverter`) TXT:
+
+- words with their positions, fonts, sizes and colours → lines → paragraphs: a line continues the paragraph above
+ when it follows at about one line pitch, unless it starts with a bullet or number, is indented as a first line,
+ or the previous line ended although the next word would have fitted; hyphenated line ends are joined, and no
+ space is added between Chinese or Japanese lines;
+- reading order: gutters between columns are found where no narrow paragraph crosses; paragraphs that span the
+ columns (titles, figures, closing text) split the page into bands, read column by column;
+- headings from font sizes (short paragraphs clearly larger than the body text, the largest size is level 1), bold
+ and 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
+ of the rendered page; a picture covering the page behind text (the scan under an OCR layer) is skipped;
+- page size per page and margins shared by the document; running headers and footers that repeat on most pages
+ (and bare page numbers) are left out;
+- a page without text (a scan, a page of drawings, a turned page) becomes the rendered page (PDFium, 150 dpi JPEG)
+ as a picture behind the text of an empty page, so nothing is lost; there is no OCR. PDF → TXT includes the
+ invisible OCR text layer of scanned PDFs that have one.
+
+Password-protected PDFs fail with a clear message. Not converted: tables (their cells come out as paragraphs in
+reading order), vector drawings on text pages, form fields and annotations other than links.
+
+## Office Open XML variants
+
+`Office/OoxmlConverter.cs` converts between the variants of a family (Word, Excel, PowerPoint) by copying the
+package with the main part's content type rewritten. Going to a macro-free type also removes the VBA project, its
+signatures and data, Word's key map customisations and Excel 4.0 macro sheets (with their sheet entries), and every
+relationship and content type entry pointing to them. The built-in readers take the variants directly (DOCM → HWPX,
+XLSM → CSV, PPSX → DOCX ...).
+
+## E-mail
+
+`Email/EmlConverter.cs` reads .eml files with MimeKitLite (MIT), which decodes quoted-printable and base64, encoded
+headers (RFC 2047 / 2231) and charsets including EUC-KR / CP949 and ISO-2022-KR; raw 8-bit header text that is not
+UTF-8 is read as CP949, as older Korean mail programs wrote it.
+
+- **EML → HTML**: a standalone page with From / To / Cc / Date / Subject / Attachments and the HTML body (its style
+ sheets kept, scripts removed) or the text body; pictures sent inline (`cid:`) become data URIs.
+- **EML → TXT**: the same headers and the text body (or the HTML body as text).
+- **EML → ZIP**: the attachments (attached messages as .eml) with safe, unique file names.
+
+## CAD drawings (DWG, DXF)
+
+Built in, no AutoCAD or ODA software (`Filee.Engines/Cad`). [ACadSharp](https://github.com/DomCR/ACadSharp) reads
+and writes the files; Filee's own renderer draws them with SkiaSharp (one drawing routine for PDF, SVG and images).
+
+- **Reading**: DWG from R14 (AC1014) to the AutoCAD 2018 format (AC1032, still current in AutoCAD 2026); DXF R12 to
+ 2018, ASCII and binary. DWG R13 and older fail with "version not supported". Korean AutoCAD writes pre-2007 DXF with
+ the code page name `ANSI_949`, which ACadSharp 3.8 does not map; Filee rewrites that header in memory so the text
+ is decoded as CP949 (`CadFile.OpenDxf`, covered by a test that fails once ACadSharp handles it).
+- **Writing** (DWG ↔ DXF): always **AutoCAD 2018 (AC1032)** — the current DWG format (AutoCAD 2018 and later, DWG
+ TrueView, BricsCAD, ODA tools); 2018 DXF stores text as UTF-8. ACadSharp's DWG writer is younger than its reader
+ and its DXF writer, so DXF is the safer format to hand on. Objects ACadSharp does not model (proxy and AEC objects,
+ some 3D and underlay data) are not written; degenerate dimensions it cannot measure are left out of DWG output
+ instead of failing the file.
+- **What is drawn**: model space seen from the top (Z is dropped). If model space has nothing visible, the active
+ layout (paper space) is drawn instead; viewports inside it are not followed. The page is fitted to the extents of
+ what is actually drawn — the header's EXTMIN/EXTMAX are ignored, so drawings far from the origin still fill it.
+ - PDF: an ISO A3 sheet (A4 or Letter when the preset asks for it), landscape when the drawing is wider than tall,
+ 10 mm margins (or the preset's margin). Vector paths, text as text with embedded fonts.
+ - SVG: the drawing's aspect ratio with a 420 mm (A3) long edge at 96 px/inch, white background, text as `<text>`.
+ - Images: the same page rendered at the preset's render resolution (150 dpi → 2480 px on the long edge, at most
+ 12 000 px / 80 MP), then the preset's image options (resize, grayscale, quality, DPI) as for other images.
+- **Entities**: LINE, XLINE/RAY (clipped to the page), LWPOLYLINE and POLYLINE (bulges, constant and tapered widths,
+ spline-fit and 3D), CIRCLE, ARC, ELLIPSE (also partial), SPLINE (NURBS from control points, knots and weights, or
+ a smooth curve through fit points), TEXT, ATTRIB and MTEXT (justification, rotation, width factor, oblique,
+ mirroring; MTEXT word wrap, height/colour/font/width codes, stacked fractions shown as `1/2`, `%%d` `%%c` `%%p`,
+ `\U+` and `\M+` escapes), INSERT (base point, scale, rotation, MINSERT arrays, nesting, attributes), DIMENSION and
+ TABLE (their anonymous block), LEADER, MULTILEADER (lines, arrows, text or block content), HATCH, SOLID/TRACE,
+ 3DFACE edges, POINT, MLINE, polyface and polygon meshes (edges).
+- **Hatches**: solid fills, gradients as a linear gradient, patterns as their real pattern lines clipped to the
+ boundary; a pattern too dense to draw (over 20 000 segments) becomes a light tint of its colour.
+- **Colours and lines**: ACI index table and true colour, BYLAYER / BYBLOCK (inside blocks, entities on layer "0"
+ follow the insert's layer). White and near-white (ACI 7, which AutoCAD shows white on black) draw black on the white
+ page. Line weights are plotted in millimetres ("Default" as a thin 0.18 mm line); line types become dash patterns
+ scaled by LTSCALE, the entity's scale and the block scale (shapes and text inside complex line types are omitted).
+- **Layers**: off, frozen and non-plotting layers (including Defpoints) are not drawn, like a plot. A frozen layer
+ hides a whole block reference; an OFF one only its layer-0 contents.
+- **Fonts**: drawings name SHX fonts, which are not available, so text uses the text style's TrueType font when it is
+ installed (arial.ttf, malgun.ttf ...) and otherwise a sans-serif face (Noto Sans, Arial, Liberation Sans ...).
+ Characters the font lacks fall back per character to a CJK font (Noto Sans KR/CJK, Malgun Gothic, Apple SD Gothic
+ Neo, ...). These come from the fonts SkiaSharp finds on the system; without any, SkiaSharp's default typeface is
+ used and the geometry is unaffected.
+- **Not drawn** (counted per type in the log): 3DSOLID, REGION and BODY (ACIS), IMAGE, OLE objects, PDF/DWF/DGN
+ underlays, WIPEOUT (its masking is not applied), SHAPE, TOLERANCE, proxy entities. MTEXT columns, tabs, underline
+ and overline are ignored.
+- **Limits**: 1 000 000 drawn primitives, block nesting depth 16, 10 000 MINSERT cells, 2 000 000 hatch pattern
+ segments in total; beyond that the drawing is cut short with a warning in the log. Damaged or truncated files fail
+ with "The file is not a valid DWG/DXF drawing or is damaged: …".
+
+ ## HWPX reader
+
+ `Hwp/Hwpx/HwpxReader*.cs` is the inverse of the writer: it reads an HWPX package into the same document model, so
+ HWPX (and HWP, which rhwp turns into HWPX first) can be written as DOCX, HTML or EPUB without Hancom Office or
+ LibreOffice. It reads files saved by 한글, by rhwp's `export-hwpx` and by Filee itself:
+
+ - elements are matched by local name (any prefix or namespace version); `hp:switch` takes the `hp:case` for
+ HwpUnitChar / 2016 paragraphs, else `hp:default`, whose lengths 한글 doubles (as are margins and tab stops
+ outside a switch in older files); every `…IDRef` is resolved through `header.xml`;
+ - sections in spine order with page size (`landscape="NARROWLY"` turns the portrait sheet), margins, gutter,
+ columns (also changing mid-section), hidden first header/footer, start page (`startNum`, `hp:newNum`);
+ - headers and footers (both / odd / even pages) with page numbers and counts; an automatic page number
+ (`hp:pageNum`, e.g. "- 1 -" at the bottom centre) becomes a footer or header paragraph;
+ - paragraph shapes (alignment, indents with 한글's hanging-indent convention, spacing, line spacing kinds, tab stops,
+ keep options, page break before) and complete character shapes (fonts per language, size, bold/italic,
+ underline, strikeout, colour, shade, highlighter `hp:markpen`, super/subscript, letter spacing);
+ - outline paragraphs (개요) as headings, numbered with the section's outline numbering when it shows numbers;
+ numberings and bullets as lists; tabs, line breaks, non-breaking/fixed-width spaces, soft hyphens; tracked
+ deletions are left out;
+ - hyperlinks (HYPERLINK fields, also across paragraphs; `?name` = bookmark), bookmarks, other fields as their
+ text, footnotes and endnotes (without 한글's number), equations as their script text;
+ - tables with spans, column widths, row heights, header rows, borders and fills (`borderFill`), cell padding,
+ vertical alignment, captions and nested tables; a table splits the paragraph that holds it;
+ - pictures from `BinData` (inline, or floating with `hp:pos` offsets, alignment and wrapping), rectangles,
+ ellipses and lines with outline and solid / gradient fill, text boxes (`hp:drawText`), groups.
+
+ Not kept (the model has no place for them; skipped and counted by the `Read(path, media, skipped)` overload):
+ OLE objects, charts, video, form controls, text art (its text is kept), arcs / polygons / curves without text,
+ master pages, memos, character ratio, relative size and offset, paragraph borders, picture cropping and rotation.
+ Password-protected (encrypted) HWPX and DRM-wrapped files stop with a clear error.
+
## HWP ↔ HWPX
rhwp converts between the two 한글 formats without Hancom Office (`export-hwpx` and `convert`). Anything → HWP goes
diff --cc src/Filee.Engines/Hwp/Hwpx/DocumentReaders.cs
index 55f0276f,00000000..5c9a7fd9
mode 100644,000000..100644
--- a/src/Filee.Engines/Hwp/Hwpx/DocumentReaders.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/DocumentReaders.cs
@@@ -1,155 -1,0 +1,157 @@@
+// The one place that knows how to read a file of some format into the document model (HDocument). The HWPX writer
+// (HwpxConverter) and the DOCX writer (DocxWriterConverter) take their input formats from here, so a new reader is one
+// line in BuiltIn and both writers (and every route through them) pick it up.
+
+using System.Text;
+using System.Text.Json.Nodes;
+using Filee.Engines.Hwp.Hwpx.Docx;
+using Filee.Engines.Hwp.Hwpx.Pptx;
+using Filee.Engines.Infrastructure;
+using Filee.Engines.Office;
+using Filee.Engines.Office.Sheets;
+using Filee.Engines.Pdf;
+
+namespace Filee.Engines.Hwp.Hwpx;
+
+/// <summary>Registry of document readers: format id → reader.</summary>
+internal static class DocumentReaders
+{
+ private static readonly TimeSpan PandocTimeout = TimeSpan.FromMinutes(2);
+
+ /// <summary>
+ /// Readers built into Filee: (input file, folder for extracted pictures) → document. Office Open XML variants
+ /// (macro-enabled files, templates, slide shows) share the reader of their family.
+ /// </summary>
+ private static readonly Dictionary<string, Func<string, string, HDocument>> BuiltIn = new(StringComparer.OrdinalIgnoreCase)
+ {
+ ["docx"] = DocxReader.Read,
+ ["docm"] = DocxReader.Read,
+ ["dotx"] = DocxReader.Read,
+ ["dotm"] = DocxReader.Read,
+ ["txt"] = (path, _) => TextDocument(File.ReadAllBytes(path)),
+ ["md"] = (path, _) => MarkdownReader.Read(DecodeText(File.ReadAllBytes(path)), Path.GetDirectoryName(Path.GetFullPath(path))!),
+ ["xlsx"] = (path, _) => SheetDocument.Build(XlsxReader.Read(path)),
+ ["xlsm"] = (path, _) => SheetDocument.Build(XlsxReader.Read(path)),
+ ["xltx"] = (path, _) => SheetDocument.Build(XlsxReader.Read(path)),
+ ["csv"] = (path, _) => SheetDocument.Build(CsvFormat.Read(path)),
+ ["tsv"] = (path, _) => SheetDocument.Build(SpreadsheetConverter.Read(path, "tsv")),
+ ["xls"] = (path, _) => SheetDocument.Build(SpreadsheetConverter.Read(path, "xls")),
+ ["ods"] = (path, _) => SheetDocument.Build(SpreadsheetConverter.Read(path, "ods")),
+ ["pptx"] = PptxReader.Read,
+ ["pptm"] = PptxReader.Read,
+ ["potx"] = PptxReader.Read,
+ ["ppsx"] = PptxReader.Read,
+ ["pdf"] = PdfDocumentReader.Read,
++ // HWP comes here as HWPX, converted by rhwp first (the route planner adds that step).
++ ["hwpx"] = HwpxReader.Read,
+ };
+
+ /// <summary>
+ /// Formats read through Pandoc's JSON AST (PandocAstReader) when Pandoc is installed: format id → Pandoc reader.
+ /// A built-in reader for the same format wins.
+ /// </summary>
+ private static readonly Dictionary<string, string> ThroughPandoc = new(StringComparer.OrdinalIgnoreCase)
+ {
+ ["odt"] = "odt",
+ ["rtf"] = "rtf",
+ ["html"] = "html",
+ ["rst"] = "rst",
+ ["tex"] = "latex",
+ };
+
+ /// <summary>Formats read without any optional engine.</summary>
+ public static IEnumerable<string> BuiltInFormats => BuiltIn.Keys;
+
+ /// <summary>Formats that need Pandoc (those without a built-in reader).</summary>
+ public static IEnumerable<string> PandocFormats => ThroughPandoc.Keys.Where(f => !BuiltIn.ContainsKey(f));
+
+ /// <summary>Every readable format; the Pandoc ones only when Pandoc is available.</summary>
+ public static IEnumerable<string> Formats(bool pandoc) => pandoc ? BuiltInFormats.Concat(PandocFormats) : BuiltInFormats;
+
+ /// <summary>True when <paramref name="format"/> can only be read with Pandoc.</summary>
+ public static bool NeedsPandoc(string format) => !BuiltIn.ContainsKey(format) && ThroughPandoc.ContainsKey(format);
+
+ /// <summary>Reads <paramref name="path"/> (of format <paramref name="format"/>) into the document model.</summary>
+ /// <param name="workDirectory">Scratch folder of the job: extracted pictures go into a new folder inside it.</param>
+ public static async Task<HDocument> ReadAsync(string path, string format, string workDirectory, CancellationToken cancellationToken)
+ {
+ var media = Path.Combine(workDirectory, $"media-{Guid.NewGuid():N}");
+ if (BuiltIn.TryGetValue(format, out var reader))
+ return await Task.Run(() => reader(path, media), cancellationToken);
+ if (ThroughPandoc.TryGetValue(format, out var pandocReader))
+ return await ReadWithPandocAsync(path, pandocReader, workDirectory, media, cancellationToken);
+ throw new NotSupportedException($"There is no document reader for {format.ToUpperInvariant()} files.");
+ }
+
+ // ───────────────────────── Pandoc ─────────────────────────
+
+ private static async Task<HDocument> ReadWithPandocAsync(string path, string pandocReader, string workDirectory, string media, CancellationToken cancellationToken)
+ {
+ var pandoc = PandocConverter.Locate() ?? throw new InvalidOperationException("Pandoc was not found.");
+ var json = Path.Combine(workDirectory, $"ast-{Guid.NewGuid():N}.json");
+ var inputFolder = Path.GetDirectoryName(Path.GetFullPath(path))!;
+
+ // Working directory = the input's folder, so relative image paths in HTML and LaTeX resolve.
+ var result = await ProcessRunner.RunAsync(pandoc,
+ [path, "-f", pandocReader, "-t", "json", "--extract-media=" + media, "-o", json],
+ PandocTimeout, cancellationToken, workingDirectory: inputFolder);
+ if (!File.Exists(json))
+ throw new InvalidOperationException($"Pandoc failed (exit {result.ExitCode}). {result.StandardError.Trim()}");
+ var ast = JsonNode.Parse(await File.ReadAllTextAsync(json, cancellationToken))
+ ?? throw new InvalidDataException("Pandoc produced an empty document.");
+ return PandocAstReader.Read(ast, target => ResolveImage(target, inputFolder));
+ }
+
+ /// <summary>Images extracted by Pandoc have absolute paths; HTML may use paths relative to the input.</summary>
+ private static string? ResolveImage(string target, string inputFolder)
+ {
+ if (string.IsNullOrWhiteSpace(target) || target.Contains("://", StringComparison.Ordinal))
+ return null;
+ var path = Uri.UnescapeDataString(target);
+ foreach (var candidate in new[] { path, Path.Combine(inputFolder, path) })
+ {
+ try
+ {
+ if (File.Exists(candidate))
+ return Path.GetFullPath(candidate);
+ }
+ catch (ArgumentException) { }
+ }
+ return null;
+ }
+
+ // ───────────────────────── Plain text ─────────────────────────
+
+ /// <summary>Plain text: one paragraph per line, text kept verbatim.</summary>
+ internal static HDocument TextDocument(byte[] bytes)
+ {
+ var section = new HSection();
+ foreach (var line in DecodeText(bytes).Replace("\r\n", "\n").Split('\n'))
+ {
+ var paragraph = new HParagraph();
+ if (line.Length > 0)
+ paragraph.Inlines.Add(new HText(line, default));
+ section.Blocks.Add(paragraph);
+ }
+ var document = new HDocument();
+ document.Sections.Add(section);
+ return document;
+ }
+
+ /// <summary>UTF-8 (with or without BOM) or UTF-16 with BOM; anything else is read as CP949, common for Korean text.</summary>
+ internal static string DecodeText(byte[] bytes)
+ {
+ if (bytes is [0xFF, 0xFE, ..] or [0xFE, 0xFF, ..])
+ return new StreamReader(new MemoryStream(bytes), detectEncodingFromByteOrderMarks: true).ReadToEnd();
+ try
+ {
+ var text = new UTF8Encoding(false, throwOnInvalidBytes: true).GetString(bytes);
+ return text.Length > 0 && text[0] == '' ? text[1..] : text;
+ }
+ catch (DecoderFallbackException)
+ {
+ Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
+ return Encoding.GetEncoding(949).GetString(bytes);
+ }
+ }
+}
diff --cc src/Filee.Engines/Hwp/Hwpx/HwpxConverter.cs
index 72e20678,4c0b2c3a..e2932d98
--- a/src/Filee.Engines/Hwp/Hwpx/HwpxConverter.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxConverter.cs
@@@ -23,8 -37,7 +23,10 @@@ public sealed class HwpxConverter : ICo
public string DisplayName => "HWPX writer (built-in)";
public int MaxParallelism => 0;
- public IReadOnlyList<ConversionEdge> Edges => BuildEdges(_pandoc is not null || PandocConverter.Locate() is not null);
+ public IReadOnlyList<ConversionEdge> Edges =>
- DocumentReaders.Formats(_pandoc ?? PandocConverter.Locate() is not null).Select(from => new ConversionEdge(from, "hwpx")).ToList();
++ DocumentReaders.Formats(_pandoc ?? PandocConverter.Locate() is not null)
++ .Where(from => from != "hwpx") // HWPX is read only to write other formats (DOCX, HTML, EPUB, ...)
++ .Select(from => new ConversionEdge(from, "hwpx")).ToList();
public EngineStatus GetStatus()
{