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.

Add DOCX writer, PDF reader, OOXML variants, e-mail and more formats

KnifeLemon09677884c1f6
diff --git a/Directory.Packages.props b/Directory.Packages.props
index 7fbcbe54..9ac931fb 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -34,11 +34,15 @@
<PackageVersion Include="Unhwp" Version="0.13.0" />
<PackageVersion Include="Markdig" Version="1.4.0" />
<PackageVersion Include="ExcelNumberFormat" Version="1.1.0" />
+ <PackageVersion Include="PdfPig" Version="0.1.16" />
+ <PackageVersion Include="MimeKitLite" Version="4.18.1" />
</ItemGroup>
<ItemGroup Label="Tests">
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.10.1" />
<PackageVersion Include="xunit.v3" Version="3.2.2" />
<PackageVersion Include="xunit.runner.visualstudio" Version="3.1.5" />
+ <!-- Tests only: validates generated DOCX files against the Office Open XML schemas. -->
+ <PackageVersion Include="DocumentFormat.OpenXml" Version="3.5.1" />
</ItemGroup>
</Project>
diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md
index 05fb3bc0..1726deff 100644
--- a/THIRD-PARTY-NOTICES.md
+++ b/THIRD-PARTY-NOTICES.md
@@ -20,9 +20,13 @@ Each component remains under its own license.
| Unhwp | MIT | https://github.com/iyulab/unhwp |
| Markdig | BSD-2-Clause | https://github.com/xoofx/markdig |
| ExcelNumberFormat | MIT | https://github.com/andersnm/ExcelNumberFormat |
+| PdfPig (PDF text, layout and pictures) | Apache-2.0 | https://github.com/UglyToad/PdfPig |
+| MimeKitLite (e-mail / MIME parsing) | MIT | https://github.com/jstedfast/MimeKit |
| pypandoc-hwpx (Pandoc AST mapping and package layout in `Filee.Engines/Hwp/Hwpx`, incl. the `blank.hwpx` reference document) | MIT, Copyright (c) 2024 pypandoc-hwpx Contributors | https://github.com/msjang/pypandoc-hwpx |
| Microsoft.Extensions.* | MIT | https://github.com/dotnet/runtime |
+Used by the tests only (not redistributed): DocumentFormat.OpenXml (Open XML SDK, MIT, https://github.com/dotnet/Open-XML-SDK) validates the DOCX files Filee writes.
+
## Engines
Bundled with the installer:
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 15adb4d1..777e7bd3 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -10,14 +10,23 @@ Filee chooses engines automatically. Settings → *Engines* shows their status,
| PDFium | built in (library) | PDF → images (multi-page TIFF/GIF supported) |
| Unhwp | built in (library) | HWP/HWPX → TXT, Markdown, HTML |
| Markdown (Markdig) | built in (library) | **Markdown → HTML, TXT** (and → PDF / DOCX through the HWPX writer, rhwp or LibreOffice) |
-| Spreadsheets | built in | **XLSX ↔ CSV** (one CSV per sheet) |
-| **HWPX writer** | built in | **DOCX, XLSX, CSV, PPTX, TXT, Markdown → HWPX** (and with rhwp → PDF and images); HTML, ODT, RTF → HWPX with Pandoc |
+| Spreadsheets | built in | **XLSX ↔ CSV** (one CSV per sheet), XLSM / XLTX → CSV |
+| Office Open XML | built in | **DOCM / DOTX / DOTM ↔ DOCX, XLSM / XLTX ↔ XLSX, PPTM / POTX / PPSX ↔ PPTX** (macros removed for macro-free types) |
+| **HWPX writer** | built in | **DOCX (+ DOCM/DOTX/DOTM), XLSX (+ XLSM/XLTX), CSV, PPTX (+ PPTM/POTX/PPSX), PDF, TXT, Markdown → HWPX** (and with rhwp → PDF and images); HTML, ODT, RTF, reStructuredText, LaTeX → HWPX with Pandoc |
+| **DOCX writer** | built in | **Markdown, TXT, XLSX, CSV, PPTX (+ variants), PDF → DOCX** |
+| PDF text | built in (PdfPig) | **PDF → TXT** (reading order, also two columns; no OCR) |
+| E-mail | built in (MimeKit) | **EML → HTML** (headers + body, inline pictures), **TXT**, **ZIP** (the attachments) |
| rhwp | bundled with the installer (`engines/rhwp`) | HWP/HWPX → PDF, **HWP → HWPX, HWPX → HWP** |
-| LibreOffice + H2Orestart + Java | **optional download** (~420 MB, 1.3 GB on disk) | older and rare formats only: DOC, XLS, PPT, RTF and OpenDocument → PDF and to each other, output as DOCX/ODT/ODS; HWP/HWPX → DOCX/ODT |
-| Pandoc | **optional download** (~42 MB, 240 MB on disk) | Markdown ↔ DOCX/ODT/RTF, DOCX/ODT/HTML/RTF → Markdown, HTML ↔ DOCX/ODT |
+| LibreOffice + H2Orestart + Java | **optional download** (~420 MB, 1.3 GB on disk) | older and rare formats only: DOC, XLS, PPT, RTF and OpenDocument → PDF and to each other, output as DOCX/ODT/ODS/ODP; HWP/HWPX → DOCX/ODT; read-only formats (see below) → PDF and their kind's editable formats |
+| Pandoc | **optional download** (~42 MB, 240 MB on disk) | Markdown ↔ DOCX/ODT/RTF, DOCX/ODT/HTML/RTF → Markdown, HTML ↔ DOCX/ODT, reStructuredText and LaTeX ↔ Markdown/HTML/DOCX/ODT (and → RTF, EPUB, TXT) |
DOCX, XLSX and PPTX → PDF need neither Microsoft Office nor LibreOffice: they are read in-process, written as HWPX
-and rendered by rhwp. LibreOffice's cost is set so the built-in route always wins where one exists.
+and 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.
+
+All built-in document readers are registered in one place, `Hwp/Hwpx/DocumentReaders.cs` (format id → reader, and
+which formats need Pandoc). The HWPX writer and the DOCX writer take their input formats from it: adding a reader
+there is one line and makes both writers (and every route through them) accept the format.
Filee never uses software installed on the system (Microsoft Office, an installed LibreOffice, programs on `PATH`):
every engine is built in, bundled or downloaded into Filee's own folder, so a conversion behaves the same on every
@@ -74,7 +83,9 @@ Readers turn the source into a small document model (`Hwp/Hwpx/HwpxModel.cs`) an
- **TXT** needs no reader (one paragraph per line; UTF-8, UTF-16 or the Korean code page CP949).
- **Markdown** is parsed with Markdig (`MarkdownReader.cs`): headings, emphasis, code, lists (1. / a. / i. with
start numbers), task lists, quotes, tables with spans, links, images, footnotes and math. No Pandoc needed.
-- **HTML, ODT, RTF** are parsed by Pandoc into its JSON AST (`PandocAstReader.cs`, following
+- **PDF** is read with PdfPig (see *PDF reader* below); DOCM / DOTX / DOTM, XLSM / XLTX and PPTM / POTX / PPSX
+ are read like DOCX, XLSX and PPTX.
+- **HTML, ODT, RTF, reStructuredText, LaTeX** are parsed by Pandoc into its JSON AST (`PandocAstReader.cs`, following
[pypandoc-hwpx](https://github.com/msjang/pypandoc-hwpx)).
- Markdown and Pandoc keep structure only, so page setup comes from the built-in template (A4).
@@ -92,6 +103,80 @@ text) and LibreOffice + H2Orestart (opens it), see `tests/Filee.Engines.Tests/Do
Not converted: Word charts, SmartArt, equations (kept as text), free-form shapes, tracked changes and comments.
+## 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.
+
## HWP ↔ HWPX
rhwp converts between the two 한글 formats without Hancom Office (`export-hwpx` and `convert`). Anything → HWP goes
@@ -103,3 +188,18 @@ through the HWPX writer and then rhwp.
fails when two conversions share a profile).
- HWP/HWPX import comes from the H2Orestart extension, which is written in Java; Filee points LibreOffice at the
downloaded JRE (`-env:UNO_JAVA_JFW_JREHOME`).
+- It is the only reader of rarer formats, converted to PDF and to the editable formats of their kind: DOT, Works /
+ WPS Writer, WordPerfect, Lotus Word Pro, AbiWord, Apple Pages and StarWriter (→ DOCX, ODT, DOC, RTF, TXT, HTML);
+ WPS Spreadsheets (ET), Apple Numbers and StarCalc (→ XLSX, ODS, XLS, CSV, HTML); Apple Keynote, WPS
+ Presentation (DPS) and StarImpress / StarDraw (→ PPTX, ODP, PPT); Publisher, CorelDRAW, Visio, CGM and ODG
+ (→ ODG, SVG, PNG). The `--convert-to` filter follows the application that opens the file (checked against
+ LibreOffice's filter registry): Publisher, CorelDRAW and Visio open in Draw, CGM in Impress, and "SDA" files
+ in Draw (.sda) or Impress (.sdd). SVG and PNG export the first page.
+
+## DjVu
+
+Not supported: DjVuLibre (GPL) has no pinned, redistributable Windows build in an archive the installer can unpack.
+The official Windows release is an NSIS installer (`DjVuLibre-3.5.29_DjView-4.12_Setup.exe` on SourceForge), which
+would have to be run (a system install) or unpacked with 7-Zip; MSYS2's packages are `.pkg.tar.zst` archives with
+five dependency packages. A DjVu engine needs a zip of `ddjvu.exe` / `djvutxt.exe` and their DLLs published for
+Filee (with the GPL source offer), then an `engines.json` component and an optional package.
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index ca855ad4..fc66636c 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -237,9 +237,9 @@
"engines.optional_description": "Large engines are only downloaded when you want them. They are kept when Filee updates and removed when you uninstall it.",
"engines.all_title": "All engines",
"engines.package.libreoffice.name": "LibreOffice (older and rare formats)",
- "engines.package.libreoffice.description": "Only needed for older and less common formats: DOC, XLS, PPT and OpenDocument files, conversions to DOCX, ODT and ODS, and HWP → DOCX (includes the H2Orestart filter and Java). DOCX, XLSX, PPTX and CSV convert without it.",
- "engines.package.pandoc.name": "Pandoc (HTML and Markdown ↔ Word)",
- "engines.package.pandoc.description": "Markdown ↔ DOCX, ODT and RTF, and HTML, ODT and RTF → HWPX. Markdown → PDF, HWPX, HTML and TXT, and DOCX → HWPX work without it.",
+ "engines.package.libreoffice.description": "Only needed for older and less common formats: DOC, XLS, PPT and OpenDocument files, WordPerfect, Works, Apple Pages, Numbers and Keynote, Publisher, CorelDRAW and Visio, conversions to ODT, ODS and ODP, and HWP → DOCX (includes the H2Orestart filter and Java). DOCX, XLSX, PPTX, CSV and PDF convert without it.",
+ "engines.package.pandoc.name": "Pandoc (Markdown, HTML, LaTeX ↔ Word)",
+ "engines.package.pandoc.description": "DOCX, ODT and RTF → Markdown, reStructuredText and LaTeX ↔ Markdown, HTML and DOCX, and HTML, ODT, RTF, reStructuredText and LaTeX → HWPX. Markdown → PDF, DOCX, HWPX, HTML and TXT work without it.",
"engines.package.size": "Download {0} · {1} on disk",
"engines.install": "Install",
"engines.cancel": "Cancel",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index c45e8822..9888c1a5 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -237,9 +237,9 @@
"engines.optional_description": "용량이 큰 엔진은 원할 때만 내려받습니다. Filee를 업데이트해도 유지되고, 제거하면 함께 지워집니다.",
"engines.all_title": "전체 엔진",
"engines.package.libreoffice.name": "LibreOffice (오래되었거나 드문 형식)",
- "engines.package.libreoffice.description": "오래되었거나 흔하지 않은 형식에만 필요해요: DOC·XLS·PPT·OpenDocument 파일, DOCX·ODT·ODS로 변환, HWP → DOCX (H2Orestart 필터와 Java 포함). DOCX·XLSX·PPTX·CSV는 없어도 변환돼요.",
- "engines.package.pandoc.name": "Pandoc (HTML·마크다운 ↔ 워드)",
- "engines.package.pandoc.description": "마크다운 ↔ DOCX·ODT·RTF 변환과 HTML·ODT·RTF → HWPX 변환을 추가합니다. 마크다운 → PDF·HWPX·HTML·TXT와 DOCX → HWPX는 없어도 됩니다.",
+ "engines.package.libreoffice.description": "오래되었거나 흔하지 않은 형식에만 필요해요: DOC·XLS·PPT·OpenDocument 파일, 워드퍼펙트·Works, Apple Pages·Numbers·Keynote, Publisher·CorelDRAW·Visio, ODT·ODS·ODP로 변환, HWP → DOCX (H2Orestart 필터와 Java 포함). DOCX·XLSX·PPTX·CSV·PDF는 없어도 변환돼요.",
+ "engines.package.pandoc.name": "Pandoc (마크다운·HTML·LaTeX ↔ 워드)",
+ "engines.package.pandoc.description": "DOCX·ODT·RTF → 마크다운, reStructuredText·LaTeX ↔ 마크다운·HTML·DOCX, HTML·ODT·RTF·reStructuredText·LaTeX → HWPX 변환을 추가해요. 마크다운 → PDF·DOCX·HWPX·HTML·TXT는 없어도 돼요.",
"engines.package.size": "다운로드 {0} · 설치 후 {1}",
"engines.install": "설치",
"engines.cancel": "취소",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index de9260d8..f3c02285 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -237,9 +237,9 @@
"engines.optional_description": "体积较大的引擎仅在需要时下载。更新 Filee 时会保留,卸载时一并删除。",
"engines.all_title": "全部引擎",
"engines.package.libreoffice.name": "LibreOffice(旧版和少见格式)",
- "engines.package.libreoffice.description": "仅用于较旧或不常见的格式:DOC、XLS、PPT 和 OpenDocument 文件,转换为 DOCX、ODT 和 ODS,以及 HWP → DOCX(含 H2Orestart 过滤器和 Java)。DOCX、XLSX、PPTX 和 CSV 无需它即可转换。",
- "engines.package.pandoc.name": "Pandoc(HTML 与 Markdown ↔ Word)",
- "engines.package.pandoc.description": "支持 Markdown ↔ DOCX、ODT、RTF,以及 HTML、ODT、RTF → HWPX。Markdown → PDF、HWPX、HTML、TXT 和 DOCX → HWPX 无需此引擎。",
+ "engines.package.libreoffice.description": "仅用于较旧或不常见的格式:DOC、XLS、PPT 和 OpenDocument 文件,WordPerfect、Works,Apple Pages、Numbers 和 Keynote,Publisher、CorelDRAW 和 Visio,转换为 ODT、ODS 和 ODP,以及 HWP → DOCX(含 H2Orestart 过滤器和 Java)。DOCX、XLSX、PPTX、CSV 和 PDF 无需它即可转换。",
+ "engines.package.pandoc.name": "Pandoc(Markdown、HTML、LaTeX ↔ Word)",
+ "engines.package.pandoc.description": "支持 DOCX、ODT、RTF → Markdown,reStructuredText 和 LaTeX ↔ Markdown、HTML、DOCX,以及 HTML、ODT、RTF、reStructuredText、LaTeX → HWPX。Markdown → PDF、DOCX、HWPX、HTML 和 TXT 无需此引擎。",
"engines.package.size": "下载 {0} · 占用 {1}",
"engines.install": "安装",
"engines.cancel": "取消",
diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.cs
index 06547816..b794b560 100644
--- a/src/Filee.Core/Settings/AppSettings.cs
+++ b/src/Filee.Core/Settings/AppSettings.cs
@@ -81,7 +81,8 @@ public sealed class AppSettings
public List<string> EnginePriority { get; set; } =
[
"magick", "pdfium", "pdfsharp", "rhwp", "unhwp", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer",
- "vector", "icns", "font", "cad", "archive", "ebook", "ffmpeg", "pandoc", "ghostscript", "calibre", "libreoffice",
+ "pdf-text", "email", "vector", "icns", "font", "cad", "archive", "ebook", "ffmpeg", "pandoc", "ghostscript", "calibre",
+ "libreoffice",
];
/// <summary>Set once the first-run welcome has been shown.</summary>
diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.cs
index 129e1500..81ccd976 100644
--- a/src/Filee.Core/Settings/UserDataStore.cs
+++ b/src/Filee.Core/Settings/UserDataStore.cs
@@ -244,7 +244,7 @@ internal static class SettingsMigrations
if (settings.SchemaVersion < 6)
{
InsertBefore(settings.EnginePriority, "ooxml", "hwpx-writer");
- foreach (var id in new[] { "docx-writer", "vector", "icns", "font", "cad", "archive", "ebook", "ffmpeg" })
+ foreach (var id in new[] { "docx-writer", "pdf-text", "email", "vector", "icns", "font", "cad", "archive", "ebook", "ffmpeg" })
InsertBefore(settings.EnginePriority, id, "pandoc");
foreach (var id in new[] { "ghostscript", "calibre" })
InsertBefore(settings.EnginePriority, id, "libreoffice");
diff --git a/src/Filee.Engines/Email/EmlConverter.cs b/src/Filee.Engines/Email/EmlConverter.cs
new file mode 100644
index 00000000..446962cb
--- /dev/null
+++ b/src/Filee.Engines/Email/EmlConverter.cs
@@ -0,0 +1,273 @@
+// E-mail messages (.eml, RFC 5322 / MIME) with MimeKitLite (MIT): the message as a web page (the headers and the HTML
+// body, or the plain text; pictures sent inline with "cid:" links become data URIs), as plain text, or its attachments
+// as a ZIP. MimeKit decodes the transfer encodings (quoted-printable, base64), encoded headers (RFC 2047 / 2231) and
+// charsets, including the Korean ones (EUC-KR / CP949, ISO-2022-KR); header text in raw 8-bit that is not UTF-8 is read
+// as CP949, as older Korean mail programs wrote it.
+
+using System.Globalization;
+using System.IO.Compression;
+using System.Net;
+using System.Text;
+using System.Text.RegularExpressions;
+using Filee.Core.Conversion;
+using MimeKit;
+
+namespace Filee.Engines.Email;
+
+/// <summary>EML → HTML, TXT and ZIP (attachments).</summary>
+public sealed partial class EmlConverter : IConverter
+{
+ public string Id => "email";
+ public string DisplayName => "E-mail (built-in)";
+ public int MaxParallelism => 0;
+
+ public IReadOnlyList<ConversionEdge> Edges { get; } = [new("eml", "html"), new("eml", "txt"), new("eml", "zip")];
+
+ public EngineStatus GetStatus() => EngineStatus.Available("EML → HTML, TXT, ZIP (attachments)");
+
+ public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>
+ Task.Run<IReadOnlyList<string>>(() =>
+ {
+ progress?.Report(0.1);
+ var message = Load(step.InputPath, cancellationToken);
+ progress?.Report(0.5);
+ if (step.To == "zip")
+ {
+ var attachments = Attachments(message);
+ if (attachments.Count == 0)
+ throw new InvalidOperationException("The e-mail has no attachments.");
+ if (step.Output.Allocate("zip") is not { } zip)
+ return [];
+ WriteZip(attachments, zip, cancellationToken);
+ progress?.Report(1);
+ return [zip];
+ }
+
+ var output = step.Output.Allocate(step.To);
+ if (output is null)
+ return [];
+ var text = step.To == "html" ? Html(message) : PlainText(message);
+ File.WriteAllText(output, text, new UTF8Encoding(encoderShouldEmitUTF8Identifier: step.To == "txt"));
+ progress?.Report(1);
+ return [output];
+ }, cancellationToken);
+
+ /// <summary>Parses a message; 8-bit header text that is not UTF-8 is read as CP949 (Korean).</summary>
+ internal static MimeMessage Load(string path, CancellationToken cancellationToken = default)
+ {
+ Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
+ var options = ParserOptions.Default.Clone();
+ options.CharsetEncoding = Encoding.GetEncoding(949);
+ using var stream = File.OpenRead(path);
+ return MimeMessage.Load(options, stream, cancellationToken);
+ }
+
+ // ───────────────────────── Headers ─────────────────────────
+
+ /// <summary>The headers shown above the body: name and value, only those the message has.</summary>
+ private static List<(string Name, string Value)> Headers(MimeMessage message)
+ {
+ var headers = new List<(string, string)>();
+ void Add(string name, string? value)
+ {
+ if (!string.IsNullOrWhiteSpace(value))
+ headers.Add((name, value.Trim()));
+ }
+ Add("From", Addresses(message.From));
+ Add("To", Addresses(message.To));
+ Add("Cc", Addresses(message.Cc));
+ if (message.Headers.Contains(HeaderId.Date))
+ Add("Date", message.Date.ToString("yyyy-MM-dd HH:mm:ss zzz", CultureInfo.InvariantCulture));
+ Add("Subject", message.Subject);
+ var attachments = Attachments(message).Select(a => a.Name).ToList();
+ if (attachments.Count > 0)
+ Add("Attachments", string.Join(", ", attachments));
+ return headers;
+ }
+
+ private static string Addresses(InternetAddressList list) =>
+ string.Join(", ", list.Mailboxes.Select(m => string.IsNullOrWhiteSpace(m.Name) ? m.Address : $"{m.Name} <{m.Address}>"));
+
+ // ───────────────────────── HTML ─────────────────────────
+
+ /// <summary>A standalone web page: the headers in a table, then the HTML body (or the text body, escaped).</summary>
+ internal static string Html(MimeMessage message)
+ {
+ var styles = new StringBuilder();
+ string body;
+ if (message.HtmlBody is { } html)
+ {
+ html = RemoveScripts(InlinePictures(html, message));
+ // Keep the style sheets of the message's own <head>, and the content of its <body>.
+ foreach (Match style in StyleBlock().Matches(html))
+ styles.Append(style.Value);
+ var match = BodyContent().Match(html);
+ body = match.Success ? match.Groups[1].Value : HeadBlock().Replace(html, "");
+ }
+ else
+ {
+ body = $"<pre class=\"filee-mail-text\">{WebUtility.HtmlEncode(message.TextBody ?? "")}</pre>";
+ }
+
+ var sb = new StringBuilder();
+ sb.Append("<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n");
+ sb.Append($"<title>{WebUtility.HtmlEncode(message.Subject ?? "")}</title>\n");
+ sb.Append("<style>\n.filee-mail-headers { border-collapse: collapse; margin: 0 0 12px 0; font-family: sans-serif; font-size: 14px; }\n")
+ .Append(".filee-mail-headers th { text-align: left; vertical-align: top; padding: 2px 16px 2px 0; color: #555; font-weight: 600; }\n")
+ .Append(".filee-mail-headers td { padding: 2px 0; }\n")
+ .Append(".filee-mail-text { white-space: pre-wrap; font-family: inherit; }\n</style>\n");
+ sb.Append(styles);
+ sb.Append("</head>\n<body>\n<table class=\"filee-mail-headers\">\n");
+ foreach (var (name, value) in Headers(message))
+ sb.Append($"<tr><th>{name}</th><td>{WebUtility.HtmlEncode(value)}</td></tr>\n");
+ sb.Append("</table>\n<hr>\n");
+ sb.Append(body);
+ sb.Append("\n</body>\n</html>\n");
+ return sb.ToString();
+ }
+
+ /// <summary>"cid:" references → data URIs of the parts with that Content-ID, so the page needs no other files.</summary>
+ private static string InlinePictures(string html, MimeMessage message)
+ {
+ var parts = new Dictionary<string, MimePart>(StringComparer.OrdinalIgnoreCase);
+ foreach (var part in message.BodyParts.OfType<MimePart>())
+ {
+ if (part.ContentId is { Length: > 0 } id)
+ parts.TryAdd(id.Trim('<', '>'), part);
+ }
+ if (parts.Count == 0)
+ return html;
+ return ContentIdReference().Replace(html, match =>
+ {
+ var id = Uri.UnescapeDataString(match.Groups[1].Value);
+ if (!parts.TryGetValue(id, out var part) || part.Content is null)
+ return match.Value;
+ using var data = new MemoryStream();
+ part.Content.DecodeTo(data);
+ return $"data:{part.ContentType.MimeType};base64,{Convert.ToBase64String(data.ToArray())}";
+ });
+ }
+
+ /// <summary>A converted page is opened in a browser: scripts of the message are not carried over.</summary>
+ private static string RemoveScripts(string html) => ScriptBlock().Replace(html, "");
+
+ // ───────────────────────── Text ─────────────────────────
+
+ /// <summary>The headers, an empty line and the text body (or the HTML body as text).</summary>
+ internal static string PlainText(MimeMessage message)
+ {
+ var sb = new StringBuilder();
+ foreach (var (name, value) in Headers(message))
+ sb.Append(name).Append(": ").Append(value).Append("\r\n");
+ sb.Append("\r\n");
+ var text = message.TextBody ?? (message.HtmlBody is { } html ? HtmlToText(html) : "");
+ sb.Append(text.Replace("\r\n", "\n").Replace("\n", "\r\n").TrimEnd()).Append("\r\n");
+ return sb.ToString();
+ }
+
+ /// <summary>Rough text of an HTML body: blocks and line breaks become new lines, tags go, entities are decoded.</summary>
+ internal static string HtmlToText(string html)
+ {
+ var text = ScriptBlock().Replace(html, "");
+ text = StyleBlock().Replace(text, "");
+ text = HeadBlock().Replace(text, "");
+ text = LineBreakTag().Replace(text, "\n");
+ text = BlockEndTag().Replace(text, "\n");
+ text = AnyTag().Replace(text, "");
+ text = WebUtility.HtmlDecode(text).Replace(' ', ' ');
+ var lines = text.Replace("\r\n", "\n").Split('\n').Select(l => SpaceRun().Replace(l, " ").Trim());
+ return MultipleBlankLines().Replace(string.Join("\n", lines), "\n\n").Trim();
+ }
+
+ // ───────────────────────── Attachments ─────────────────────────
+
+ /// <summary>Attached files and messages with a unique, safe file name each.</summary>
+ internal static List<(string Name, MimeEntity Entity)> Attachments(MimeMessage message)
+ {
+ var result = new List<(string, MimeEntity)>();
+ var names = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
+ foreach (var entity in message.BodyParts)
+ {
+ string? name = entity switch
+ {
+ MessagePart attached => (attached.ContentDisposition?.FileName ?? attached.Message?.Subject ?? "message") + ".eml",
+ MimePart part when part.IsAttachment || (part.FileName is { Length: > 0 } && part.ContentId is null) =>
+ part.FileName ?? $"attachment{MimeTypes.TryGetExtension(part.ContentType.MimeType, out var extension) switch { true => extension, false => ".bin" }}",
+ _ => null,
+ };
+ if (name is null)
+ continue;
+ name = SafeName(name);
+ var unique = name;
+ for (var i = 2; !names.Add(unique); i++)
+ unique = $"{Path.GetFileNameWithoutExtension(name)} ({i}){Path.GetExtension(name)}";
+ result.Add((unique, entity));
+ }
+ return result;
+ }
+
+ private static void WriteZip(List<(string Name, MimeEntity Entity)> attachments, string path, CancellationToken cancellationToken)
+ {
+ var temp = path + ".tmp";
+ using (var file = File.Create(temp))
+ using (var zip = new ZipArchive(file, ZipArchiveMode.Create))
+ {
+ foreach (var (name, entity) in attachments)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ using var target = zip.CreateEntry(name, CompressionLevel.Optimal).Open();
+ switch (entity)
+ {
+ case MessagePart { Message: { } attached }:
+ attached.WriteTo(target, cancellationToken);
+ break;
+ case MimePart { Content: { } content }:
+ content.DecodeTo(target, cancellationToken);
+ break;
+ }
+ }
+ }
+ File.Move(temp, path, overwrite: true);
+ }
+
+ /// <summary>A file name without folders or characters Windows does not allow.</summary>
+ private static string SafeName(string name)
+ {
+ name = Path.GetFileName(name.Replace('\\', '/').Split('/')[^1]);
+ var invalid = Path.GetInvalidFileNameChars();
+ name = new string([.. name.Select(ch => invalid.Contains(ch) || char.IsControl(ch) ? '_' : ch)]).Trim(' ', '.');
+ return name.Length == 0 ? "attachment" : name.Length > 150 ? name[..150] : name;
+ }
+
+ // ───────────────────────── Patterns ─────────────────────────
+
+ [GeneratedRegex("<body[^>]*>(.*)</body>", RegexOptions.IgnoreCase | RegexOptions.Singleline)]
+ private static partial Regex BodyContent();
+
+ [GeneratedRegex("<head[^>]*>.*?</head>", RegexOptions.IgnoreCase | RegexOptions.Singleline)]
+ private static partial Regex HeadBlock();
+
+ [GeneratedRegex("<style[^>]*>.*?</style>", RegexOptions.IgnoreCase | RegexOptions.Singleline)]
+ private static partial Regex StyleBlock();
+
+ [GeneratedRegex("<script[^>]*>.*?</script>", RegexOptions.IgnoreCase | RegexOptions.Singleline)]
+ private static partial Regex ScriptBlock();
+
+ [GeneratedRegex("cid:([^\"'\\s)>]+)", RegexOptions.IgnoreCase)]
+ private static partial Regex ContentIdReference();
+
+ [GeneratedRegex("<br\\s*/?>", RegexOptions.IgnoreCase)]
+ private static partial Regex LineBreakTag();
+
+ [GeneratedRegex("</(p|div|tr|li|h[1-6]|table|blockquote)>", RegexOptions.IgnoreCase)]
+ private static partial Regex BlockEndTag();
+
+ [GeneratedRegex("<[^>]+>")]
+ private static partial Regex AnyTag();
+
+ [GeneratedRegex("[ \\t]+")]
+ private static partial Regex SpaceRun();
+
+ [GeneratedRegex("\\n{3,}")]
+ private static partial Regex MultipleBlankLines();
+}
diff --git a/src/Filee.Engines/EngineRegistry.cs b/src/Filee.Engines/EngineRegistry.cs
index 31b45a74..9e9ca0ba 100644
--- a/src/Filee.Engines/EngineRegistry.cs
+++ b/src/Filee.Engines/EngineRegistry.cs
@@ -1,6 +1,7 @@
// THE place where conversion engines are registered. Adding an engine = one line in CreateAll.
using Filee.Core.Conversion;
+using Filee.Engines.Email;
using Filee.Engines.Hwp;
using Filee.Engines.Hwp.Hwpx;
using Filee.Engines.Infrastructure;
@@ -28,7 +29,11 @@ public static class EngineRegistry
new UnhwpConverter(),
new MarkdownConverter(),
new SpreadsheetConverter(),
+ new OoxmlConverter(),
new HwpxConverter(),
+ new DocxWriterConverter(),
+ new PdfTextConverter(),
+ new EmlConverter(),
new PandocConverter(),
new LibreOfficeConverter(env),
];
diff --git a/src/Filee.Engines/Filee.Engines.csproj b/src/Filee.Engines/Filee.Engines.csproj
index af7d20a6..07bd092b 100644
--- a/src/Filee.Engines/Filee.Engines.csproj
+++ b/src/Filee.Engines/Filee.Engines.csproj
@@ -18,6 +18,8 @@
<PackageReference Include="Unhwp" />
<PackageReference Include="Markdig" />
<PackageReference Include="ExcelNumberFormat" />
+ <PackageReference Include="PdfPig" />
+ <PackageReference Include="MimeKitLite" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" />
</ItemGroup>
diff --git a/src/Filee.Engines/Hwp/Hwpx/DocumentReaders.cs b/src/Filee.Engines/Hwp/Hwpx/DocumentReaders.cs
new file mode 100644
index 00000000..1d784d09
--- /dev/null
+++ b/src/Filee.Engines/Hwp/Hwpx/DocumentReaders.cs
@@ -0,0 +1,152 @@
+// 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)),
+ ["pptx"] = PptxReader.Read,
+ ["pptm"] = PptxReader.Read,
+ ["potx"] = PptxReader.Read,
+ ["ppsx"] = PptxReader.Read,
+ ["pdf"] = PdfDocumentReader.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 --git a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Drawing.cs b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Drawing.cs
index 1bf67d03..c006700c 100644
--- a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Drawing.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Drawing.cs
@@ -123,8 +123,15 @@ internal sealed partial class DocxReader
var geometry = Attr(spPr?.Element(A + "prstGeom"), "prst");
if (wsp.Element(Wps + "txbx")?.Element(W + "txbxContent") is { } content)
{
- if (geometry is "rect" or "roundRect" or "flowChartProcess" or "flowChartAlternateProcess")
- return TextBox(wsp, content, width, height, anchor, fill ?? gradient?.Colors[0]);
+ if (geometry is "rect" or "roundRect" or "flowChartProcess" or "flowChartAlternateProcess" or "ellipse" or "flowChartConnector")
+ {
+ var framed = TextBox(wsp, content, width, height, anchor, fill ?? gradient?.Colors[0]);
+ if (geometry is "ellipse" or "flowChartConnector")
+ framed.Shape = HShapeKind.Ellipse;
+ else if (geometry is "roundRect" or "flowChartAlternateProcess")
+ framed.CornerRatio = 20;
+ return framed;
+ }
// Text on a free-form or decorative shape: keep the text, drop the outline 한글 cannot draw.
if (string.IsNullOrWhiteSpace(content.Value))
return null;
diff --git a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxWriter.Body.cs b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxWriter.Body.cs
new file mode 100644
index 00000000..d2df5d35
--- /dev/null
+++ b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxWriter.Body.cs
@@ -0,0 +1,617 @@
+// Document body: sections (page setup, columns, headers and footers), paragraphs, runs and tables.
+//
+// Word keeps a section's properties at its end: in the last paragraph of the section (w:pPr/w:sectPr) and, for the
+// last section, as the last child of w:body. Columns that change mid-page (HParagraph.ColumnsChange) become
+// continuous section breaks, which is how Word itself does it. Element order follows the schema sequences
+// (CT_PPr, CT_RPr, CT_SectPr, CT_TblPr, CT_TcPr), which Word enforces.
+
+using System.Text;
+
+namespace Filee.Engines.Hwp.Hwpx.Docx;
+
+internal sealed partial class DocxWriter
+{
+ /// <summary>A4 with one-inch margins and headers/footers 1.5 cm from the edge (Word's A4 default).</summary>
+ private static readonly HPage DefaultPage = new(59528, 84188, 7200, 7200, 4255, 4255, 2945, 2945, 0);
+
+ /// <summary>Word's highlight colours (the ones DocxReader turns into shades), by "#RRGGBB".</summary>
+ private static readonly Dictionary<string, string> Highlights = new(StringComparer.OrdinalIgnoreCase)
+ {
+ ["#FFFF00"] = "yellow",
+ ["#00FF00"] = "green",
+ ["#00FFFF"] = "cyan",
+ ["#FF00FF"] = "magenta",
+ ["#0000FF"] = "blue",
+ ["#FF0000"] = "red",
+ ["#000080"] = "darkBlue",
+ ["#008080"] = "darkCyan",
+ ["#008000"] = "darkGreen",
+ ["#800080"] = "darkMagenta",
+ ["#800000"] = "darkRed",
+ ["#808000"] = "darkYellow",
+ ["#808080"] = "darkGray",
+ ["#C0C0C0"] = "lightGray",
+ ["#000000"] = "black",
+ };
+
+ /// <summary>Width (HWPUNIT) available to the content being written: column, table cell or text box.</summary>
+ private int _width = DefaultPage.TextWidth;
+
+ /// <summary>Header / footer types referenced by earlier sections (Word would let later sections inherit them).</summary>
+ private readonly HashSet<string> _headerTypes = [];
+ private readonly HashSet<string> _footerTypes = [];
+
+ /// <summary>What the paragraph style of the current paragraph already sets (explicit "off" values override it).</summary>
+ private readonly record struct RunContext(bool StyleBold, bool Link);
+
+ // ───────────────────────── Sections ─────────────────────────
+
+ private string Body(HDocument document)
+ {
+ var sections = document.Sections.Count > 0 ? document.Sections : [new HSection()];
+ _evenAndOddHeaders = sections.Any(s => s.Headers.Concat(s.Footers).Any(h => h.Pages == HPageType.Even));
+
+ var sb = new StringBuilder();
+ for (var s = 0; s < sections.Count; s++)
+ {
+ var section = sections[s];
+ var page = section.Page ?? DefaultPage;
+ var parts = SplitAtColumnChanges(section);
+ for (var p = 0; p < parts.Count; p++)
+ {
+ var (columns, blocks) = parts[p];
+ _width = page.TextWidth;
+ var sectPr = SectionProperties(section, page, columns, continuous: p > 0);
+ _width = ColumnWidth(page.TextWidth, columns);
+ var last = s == sections.Count - 1 && p == parts.Count - 1;
+ if (last)
+ sb.Append(Blocks(blocks, requireParagraph: true)).Append(sectPr);
+ else
+ sb.Append(Blocks(blocks, sectionEnd: sectPr));
+ }
+ }
+ return sb.ToString();
+ }
+
+ /// <summary>Splits a section where its columns change: each piece becomes a Word section of its own.</summary>
+ private static List<(HColumns Columns, List<HBlock> Blocks)> SplitAtColumnChanges(HSection section)
+ {
+ var parts = new List<(HColumns, List<HBlock>)>();
+ var columns = section.Columns;
+ var current = new List<HBlock>();
+ foreach (var block in section.Blocks)
+ {
+ if (block is HParagraph { ColumnsChange: { } change })
+ {
+ if (current.Count > 0)
+ {
+ parts.Add((columns, current));
+ current = [];
+ }
+ columns = change;
+ }
+ current.Add(block);
+ }
+ parts.Add((columns, current));
+ return parts;
+ }
+
+ private static int ColumnWidth(int textWidth, HColumns columns) =>
+ columns.Count <= 1 ? textWidth : Math.Max(2000, (textWidth - columns.Gap * (columns.Count - 1)) / columns.Count);
+
+ /// <summary>w:sectPr in schema order: references, type, pgSz, pgMar, pgNumType, cols, titlePg.</summary>
+ private string SectionProperties(HSection section, HPage page, HColumns columns, bool continuous)
+ {
+ var sb = new StringBuilder("<w:sectPr>");
+ var titlePage = !continuous && (section.HideFirstHeader || section.HideFirstFooter);
+ if (!continuous)
+ {
+ HeaderFooterReferences(sb, "header", section.Headers, section.HideFirstHeader, titlePage, _headerTypes);
+ HeaderFooterReferences(sb, "footer", section.Footers, section.HideFirstFooter, titlePage, _footerTypes);
+ }
+ else
+ {
+ sb.Append("<w:type w:val=\"continuous\"/>");
+ }
+
+ // The model's Top / Bottom run from the paper edge to the header / footer and Header / Footer are their
+ // heights (as in 한글); Word's top / bottom margins reach the body and header / footer are the distances.
+ sb.Append($"<w:pgSz w:w=\"{Number(Twips(page.Width))}\" w:h=\"{Number(Twips(page.Height))}\"{(page.Landscape ? " w:orient=\"landscape\"" : "")}/>");
+ sb.Append($"<w:pgMar w:top=\"{Number(Twips(page.Top + page.Header))}\" w:right=\"{Number(Twips(page.Right))}\" w:bottom=\"{Number(Twips(page.Bottom + page.Footer))}\" w:left=\"{Number(Twips(page.Left))}\" ")
+ .Append($"w:header=\"{Number(Twips(page.Top))}\" w:footer=\"{Number(Twips(page.Bottom))}\" w:gutter=\"{Number(Twips(page.Gutter))}\"/>");
+ if (!continuous && section.StartPageNumber is { } start)
+ sb.Append($"<w:pgNumType w:start=\"{Number(start)}\"/>");
+ sb.Append(columns.Count > 1
+ ? $"<w:cols w:num=\"{Number(Math.Min(columns.Count, 45))}\" w:space=\"{Number(Twips(columns.Gap))}\"{(columns.Separator ? " w:sep=\"1\"" : "")}/>"
+ : "<w:cols w:space=\"720\"/>");
+ if (titlePage)
+ sb.Append("<w:titlePg/>");
+ return sb.Append("</w:sectPr>").ToString();
+ }
+
+ /// <summary>
+ /// Header or footer references of a section. Word lets a section without a reference inherit the previous
+ /// section's, so a type used before but missing here gets an empty part; "different first page" gets a first
+ /// header that is empty or a copy of the default one.
+ /// </summary>
+ private void HeaderFooterReferences(StringBuilder sb, string kind, List<HHeaderFooter> items, bool hideFirst, bool titlePage, HashSet<string> used)
+ {
+ var byType = new Dictionary<string, List<HBlock>>();
+ foreach (var item in items)
+ byType[item.Pages == HPageType.Even ? "even" : "default"] = item.Blocks;
+ // With different odd and even pages, a header for both kinds of page must be given for even pages too.
+ if (_evenAndOddHeaders && !byType.ContainsKey("even") && items.LastOrDefault(i => i.Pages == HPageType.Both) is { } both)
+ byType["even"] = both.Blocks;
+ if (titlePage)
+ byType["first"] = hideFirst ? [] : byType.GetValueOrDefault("default") ?? [];
+ foreach (var type in used)
+ byType.TryAdd(type, []);
+
+ foreach (var (type, blocks) in byType)
+ {
+ var id = HeaderFooterPart(kind, () => Blocks(blocks, requireParagraph: true));
+ sb.Append($"<w:{kind}Reference w:type=\"{type}\" r:id=\"{id}\"/>");
+ used.Add(type);
+ }
+ }
+
+ // ───────────────────────── Blocks ─────────────────────────
+
+ /// <param name="sectionEnd">sectPr to put into the last paragraph (a paragraph is added if the last block is a table).</param>
+ /// <param name="requireParagraph">The container must end with a paragraph (cells, text boxes, notes, the body).</param>
+ /// <param name="paragraphStyle">Style of plain paragraphs (footnote text inside notes).</param>
+ /// <param name="leadingRuns">Runs put first into the first paragraph (the number of a note).</param>
+ private string Blocks(IReadOnlyList<HBlock> blocks, string? sectionEnd = null, bool requireParagraph = false,
+ string? paragraphStyle = null, string? leadingRuns = null)
+ {
+ var sb = new StringBuilder();
+ if (leadingRuns is not null && (blocks.Count == 0 || blocks[0] is not HParagraph))
+ blocks = [new HParagraph(), .. blocks];
+ for (var i = 0; i < blocks.Count; i++)
+ {
+ switch (blocks[i])
+ {
+ case HParagraph paragraph:
+ var isLast = i == blocks.Count - 1;
+ sb.Append(Paragraph(paragraph, isLast ? sectionEnd : null, paragraphStyle, i == 0 ? leadingRuns : null));
+ break;
+ case HTable table:
+ // Two tables in a row would merge into one in Word.
+ if (i > 0 && blocks[i - 1] is HTable)
+ sb.Append("<w:p/>");
+ sb.Append(Table(table));
+ break;
+ }
+ }
+ var endsWithParagraph = blocks.Count > 0 && blocks[^1] is HParagraph;
+ if (sectionEnd is not null && !endsWithParagraph)
+ sb.Append($"<w:p><w:pPr>{sectionEnd}</w:pPr></w:p>");
+ else if (requireParagraph && !endsWithParagraph)
+ sb.Append("<w:p/>");
+ return sb.ToString();
+ }
+
+ // ───────────────────────── Paragraphs ─────────────────────────
+
+ private string Paragraph(HParagraph paragraph, string? sectPr = null, string? style = null, string? leadingRuns = null)
+ {
+ var heading = paragraph.HeadingLevel is >= 1 and <= 9 ? paragraph.HeadingLevel : 0;
+ if (heading > 0)
+ style = $"Heading{heading}";
+ var context = new RunContext(StyleBold: heading > 0, Link: false);
+
+ var sb = new StringBuilder("<w:p>");
+ sb.Append(ParagraphProperties(paragraph, style, heading > 0, sectPr, context));
+ if (paragraph.ColumnBreakBefore)
+ sb.Append("<w:r><w:br w:type=\"column\"/></w:r>");
+ sb.Append(leadingRuns);
+ Inlines(paragraph.Inlines, sb, context);
+ return 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>
+ private string ParagraphProperties(HParagraph paragraph, string? style, bool heading, string? sectPr, RunContext context)
+ {
+ var format = paragraph.Format;
+ var sb = new StringBuilder();
+ if (style is not null)
+ sb.Append($"<w:pStyle w:val=\"{style}\"/>");
+ if (format.KeepWithNext == true)
+ sb.Append("<w:keepNext/>");
+ else if (format.KeepWithNext == false && heading)
+ sb.Append("<w:keepNext w:val=\"0\"/>");
+ if (format.KeepLines == true)
+ sb.Append("<w:keepLines/>");
+ else if (format.KeepLines == false && heading)
+ sb.Append("<w:keepLines w:val=\"0\"/>");
+ if (paragraph.PageBreakBefore)
+ sb.Append("<w:pageBreakBefore/>");
+ if (format.WidowOrphan == false)
+ sb.Append("<w:widowControl w:val=\"0\"/>");
+ if (paragraph.List is { Numbered: true } list)
+ sb.Append($"<w:numPr><w:ilvl w:val=\"{Number(Math.Clamp(list.Level, 0, 8))}\"/><w:numId w:val=\"{Number(NumberingId(list.Numbering))}\"/></w:numPr>");
+
+ if (format.Tabs is { Count: > 0 } tabs)
+ {
+ sb.Append("<w:tabs>");
+ foreach (var tab in tabs.OrderBy(t => t.Position))
+ {
+ var kind = tab.Kind switch
+ {
+ HTabKind.Right => "right",
+ HTabKind.Center => "center",
+ HTabKind.Decimal => "decimal",
+ _ => "left",
+ };
+ var leader = tab.Leader switch
+ {
+ "DOT" => " w:leader=\"dot\"",
+ "DASH" => " w:leader=\"hyphen\"",
+ "SOLID" => " w:leader=\"underscore\"",
+ _ => "",
+ };
+ sb.Append($"<w:tab w:val=\"{kind}\"{leader} w:pos=\"{Number(Twips(tab.Position))}\"/>");
+ }
+ sb.Append("</w:tabs>");
+ }
+
+ var spacing = new StringBuilder();
+ if (format.Before is { } before)
+ spacing.Append($" w:before=\"{Number(Math.Max(0, Twips(before)))}\"");
+ if (format.After is { } after)
+ spacing.Append($" w:after=\"{Number(Math.Max(0, Twips(after)))}\"");
+ if (format.LineSpacing is { } line)
+ {
+ // 한글 percentages are of the font size, Word's "auto" lines of the font's line height (≈ 1.3 em):
+ // the inverse of DocxReader's mapping.
+ spacing.Append(line.Kind switch
+ {
+ HLineSpacingKind.Fixed => $" w:line=\"{Number(Math.Max(20, Twips(line.Value)))}\" w:lineRule=\"exact\"",
+ HLineSpacingKind.AtLeast => $" w:line=\"{Number(Math.Max(20, Twips(line.Value)))}\" w:lineRule=\"atLeast\"",
+ _ => $" w:line=\"{Number(Math.Clamp((int)Math.Round(line.Value * 240 / 130.0), 24, 2400))}\" w:lineRule=\"auto\"",
+ });
+ }
+ if (spacing.Length > 0)
+ sb.Append("<w:spacing").Append(spacing).Append("/>");
+
+ var left = format.Left;
+ var firstLine = format.FirstLine;
+ if (paragraph.List is { } item && left is null)
+ {
+ // Continuation paragraphs of a list item line up with the item's text.
+ if (!item.Numbered)
+ sb.Append($"<w:ind w:left=\"{Number(ListIndent(item.Level))}\"/>");
+ }
+ else if (left is not null || format.Right is not null || firstLine is not null)
+ {
+ if (paragraph.List is not null || (left ?? 0) != 0 || (format.Right ?? 0) != 0 || (firstLine ?? 0) != 0)
+ {
+ sb.Append("<w:ind");
+ if (left is { } l)
+ sb.Append($" w:left=\"{Number(Twips(l))}\"");
+ if (format.Right is { } r)
+ sb.Append($" w:right=\"{Number(Twips(r))}\"");
+ if (firstLine is < 0)
+ sb.Append($" w:hanging=\"{Number(Twips(-firstLine.Value))}\"");
+ else if (firstLine is { } f)
+ sb.Append($" w:firstLine=\"{Number(Twips(f))}\"");
+ sb.Append("/>");
+ }
+ }
+
+ if (format.Align is { } align and not HAlign.Left)
+ {
+ sb.Append(align switch
+ {
+ HAlign.Center => "<w:jc w:val=\"center\"/>",
+ HAlign.Right => "<w:jc w:val=\"right\"/>",
+ HAlign.Distribute => "<w:jc w:val=\"distribute\"/>",
+ _ => "<w:jc w:val=\"both\"/>",
+ });
+ }
+
+ var mark = RunProperties(paragraph.MarkFormat, context);
+ if (mark.Length > 0)
+ sb.Append("<w:rPr>").Append(mark).Append("</w:rPr>");
+ sb.Append(sectPr);
+ return sb.Length == 0 ? "" : $"<w:pPr>{sb}</w:pPr>";
+ }
+
+ // ───────────────────────── Runs ─────────────────────────
+
+ private void Inlines(IEnumerable<HInline> inlines, StringBuilder sb, RunContext context)
+ {
+ foreach (var inline in inlines)
+ {
+ switch (inline)
+ {
+ case HText text:
+ TextRuns(sb, text.Text, text.Format, context);
+ break;
+ case HLineBreak lineBreak:
+ sb.Append("<w:r>").Append(RunPr(lineBreak.Format, context)).Append("<w:br/></w:r>");
+ break;
+ case HTab tab:
+ sb.Append("<w:r>").Append(RunPr(tab.Format, context)).Append("<w:tab/></w:r>");
+ break;
+ case HLink link:
+ Hyperlink(link, sb, context);
+ break;
+ case HBookmark bookmark:
+ {
+ var id = Number(_nextBookmarkId++);
+ sb.Append($"<w:bookmarkStart w:id=\"{id}\" w:name=\"{Escape(BookmarkName(bookmark.Name))}\"/><w:bookmarkEnd w:id=\"{id}\"/>");
+ break;
+ }
+ case HField field:
+ Field(sb, field.Kind == HFieldKind.PageNumber ? "PAGE" : "NUMPAGES", RunPr(field.Format, context));
+ break;
+ case HNote note:
+ sb.Append(NoteReference(note));
+ break;
+ case HImage image:
+ sb.Append(Picture(image));
+ break;
+ case HTextBox box:
+ sb.Append(TextBox(box, context));
+ break;
+ case HShape shape:
+ sb.Append(Shape(shape));
+ break;
+ }
+ }
+ }
+
+ /// <summary>Text runs; line feeds and tabs inside the text become w:br and w:tab.</summary>
+ private static void TextRuns(StringBuilder sb, string text, HCharFormat format, RunContext context)
+ {
+ if (text.Length == 0)
+ return;
+ sb.Append("<w:r>").Append(RunPr(format, context));
+ var start = 0;
+ for (var i = 0; i <= text.Length; i++)
+ {
+ if (i < text.Length && text[i] is not ('\n' or '\t' or '\r'))
+ continue;
+ if (i > start)
+ sb.Append("<w:t xml:space=\"preserve\">").Append(Escape(text[start..i])).Append("</w:t>");
+ if (i < text.Length)
+ {
+ if (text[i] == '\t')
+ sb.Append("<w:tab/>");
+ else if (text[i] == '\n' || (text[i] == '\r' && (i + 1 >= text.Length || text[i + 1] != '\n')))
+ sb.Append("<w:br/>");
+ }
+ start = i + 1;
+ }
+ sb.Append("</w:r>");
+ }
+
+ private static string RunPr(HCharFormat format, RunContext context, string? characterStyle = null)
+ {
+ var properties = RunProperties(format, context, characterStyle);
+ 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)
+ {
+ var sb = new StringBuilder();
+ characterStyle ??= context.Link ? "Hyperlink" : null;
+ if (characterStyle is not null)
+ sb.Append($"<w:rStyle w:val=\"{characterStyle}\"/>");
+ if (format.Font is not null || format.EastAsianFont is not null)
+ {
+ sb.Append("<w:rFonts");
+ if (format.Font is { } latin)
+ sb.Append($" w:ascii=\"{Escape(latin)}\" w:hAnsi=\"{Escape(latin)}\"");
+ if ((format.EastAsianFont ?? format.Font) is { } eastAsian)
+ sb.Append($" w:eastAsia=\"{Escape(eastAsian)}\"");
+ if (format.Font is { } complex)
+ sb.Append($" w:cs=\"{Escape(complex)}\"");
+ sb.Append("/>");
+ }
+ if (format.Bold == true)
+ sb.Append("<w:b/><w:bCs/>");
+ else if (format.Bold == false && context.StyleBold)
+ sb.Append("<w:b w:val=\"0\"/><w:bCs w:val=\"0\"/>");
+ if (format.Italic == true)
+ sb.Append("<w:i/><w:iCs/>");
+ if (format.Strike == true)
+ sb.Append("<w:strike/>");
+ if (Hex(format.Color) is { } color)
+ sb.Append($"<w:color w:val=\"{color}\"/>");
+ var size = format.Size ?? DefaultSize;
+ if (format.Spacing is { } spacing and not 0)
+ {
+ // 한글 letter spacing is a percentage of the font size, Word's an absolute distance in twips.
+ sb.Append($"<w:spacing w:val=\"{Number((int)Math.Round(spacing * size / 500.0))}\"/>");
+ }
+ if (format.Size is { } explicitSize)
+ {
+ var halfPoints = Number(Math.Clamp((int)Math.Round(explicitSize / 50.0), 2, 3276));
+ sb.Append($"<w:sz w:val=\"{halfPoints}\"/><w:szCs w:val=\"{halfPoints}\"/>");
+ }
+ var highlight = format.Shade is { } shade ? Highlights.GetValueOrDefault(shade) : null;
+ if (highlight is not null)
+ sb.Append($"<w:highlight w:val=\"{highlight}\"/>");
+ if (format.Underline == true)
+ sb.Append("<w:u w:val=\"single\"/>");
+ else if (format.Underline == false && characterStyle == "Hyperlink")
+ sb.Append("<w:u w:val=\"none\"/>");
+ if (highlight is null && Hex(format.Shade) is { } fill)
+ sb.Append($"<w:shd w:val=\"clear\" w:color=\"auto\" w:fill=\"{fill}\"/>");
+ if (format.Superscript == true)
+ sb.Append("<w:vertAlign w:val=\"superscript\"/>");
+ else if (format.Subscript == true)
+ sb.Append("<w:vertAlign w:val=\"subscript\"/>");
+ return sb.ToString();
+ }
+
+ /// <summary>A complex field (PAGE, NUMPAGES) with a cached result Word updates when it lays out the page.</summary>
+ private static void Field(StringBuilder sb, string instruction, string runProperties)
+ {
+ sb.Append($"<w:r>{runProperties}<w:fldChar w:fldCharType=\"begin\"/></w:r>");
+ sb.Append($"<w:r>{runProperties}<w:instrText xml:space=\"preserve\"> {instruction} </w:instrText></w:r>");
+ sb.Append($"<w:r>{runProperties}<w:fldChar w:fldCharType=\"separate\"/></w:r>");
+ sb.Append($"<w:r>{runProperties}<w:t>1</w:t></w:r>");
+ sb.Append($"<w:r>{runProperties}<w:fldChar w:fldCharType=\"end\"/></w:r>");
+ }
+
+ /// <summary>
+ /// A footnote or endnote: the reference in the text, the note itself in footnotes.xml / endnotes.xml. Word only
+ /// allows notes in the body text (not in notes, headers, footers or text boxes): there the note's text stays in
+ /// place, in brackets.
+ /// </summary>
+ private string NoteReference(HNote note)
+ {
+ var (kind, style) = note.Endnote ? ("endnote", "Endnote") : ("footnote", "Footnote");
+ if (_part != _document || _textBoxDepth > 0)
+ {
+ var text = string.Concat(note.Blocks.OfType<HParagraph>().SelectMany(p => p.Inlines).OfType<HText>().Select(t => t.Text));
+ var sb = new StringBuilder();
+ TextRuns(sb, $" ({text})", default, default);
+ return sb.ToString();
+ }
+
+ var part = note.Endnote
+ ? _endnotesPart ??= new Part("word/endnotes.xml", ContentTypeBase + "endnotes+xml")
+ : _footnotesPart ??= new Part("word/footnotes.xml", ContentTypeBase + "footnotes+xml");
+ var notes = note.Endnote ? _endnotes : _footnotes;
+ var id = notes.Count + 1;
+ notes.Add("");
+ var number = $"<w:r><w:rPr><w:rStyle w:val=\"{style}Reference\"/></w:rPr><w:{kind}Ref/></w:r><w:r><w:t xml:space=\"preserve\"> </w:t></w:r>";
+ notes[id - 1] = WithPart(part, () => Blocks(note.Blocks, requireParagraph: true, paragraphStyle: style + "Text", leadingRuns: number));
+ return $"<w:r><w:rPr><w:rStyle w:val=\"{style}Reference\"/></w:rPr><w:{kind}Reference w:id=\"{Number(id)}\"/></w:r>";
+ }
+
+ // ───────────────────────── Tables ─────────────────────────
+
+ private string Table(HTable table)
+ {
+ if (table.Rows.Count == 0)
+ return "";
+ var (placed, columnCount) = HwpxWriter.PlaceCells(table);
+ var available = Math.Max(4000, _width - (table.Align == HAlign.Left ? table.Indent : 0));
+ var widths = HwpxWriter.ColumnWidths(table, columnCount, available);
+ var borders = table.Borders ?? HBorders.Grid;
+ var margin = table.CellMargin;
+
+ // Cells that span rows: the positions below their first row are continuation cells (w:vMerge).
+ var continuations = new Dictionary<(int Row, int Column), HCell>();
+ for (var r = 0; r < placed.Count; r++)
+ {
+ foreach (var (cell, column) in placed[r])
+ {
+ for (var below = 1; below < cell.RowSpan; below++)
+ continuations[(r + below, column)] = cell;
+ }
+ }
+
+ var sb = new StringBuilder("<w:tbl><w:tblPr>");
+ sb.Append($"<w:tblW w:w=\"{Number(Twips(widths.Sum()))}\" w:type=\"dxa\"/>");
+ if (table.Align is HAlign.Center or HAlign.Right)
+ sb.Append($"<w:jc w:val=\"{(table.Align == HAlign.Center ? "center" : "right")}\"/>");
+ else if (table.Indent != 0)
+ sb.Append($"<w:tblInd w:w=\"{Number(Twips(table.Indent))}\" w:type=\"dxa\"/>");
+ sb.Append("<w:tblBorders>")
+ .Append(Border("top", borders.Top)).Append(Border("left", borders.Left))
+ .Append(Border("bottom", borders.Bottom)).Append(Border("right", borders.Right))
+ .Append(Border("insideH", borders.Top)).Append(Border("insideV", borders.Left))
+ .Append("</w:tblBorders>");
+ sb.Append("<w:tblLayout w:type=\"fixed\"/>");
+ if (margin is { } m)
+ sb.Append($"<w:tblCellMar><w:top w:w=\"{Number(Twips(m.Top))}\" w:type=\"dxa\"/><w:left w:w=\"{Number(Twips(m.Left))}\" w:type=\"dxa\"/><w:bottom w:w=\"{Number(Twips(m.Bottom))}\" w:type=\"dxa\"/><w:right w:w=\"{Number(Twips(m.Right))}\" w:type=\"dxa\"/></w:tblCellMar>");
+ sb.Append("<w:tblLook w:val=\"04A0\"/></w:tblPr>");
+ sb.Append("<w:tblGrid>").Append(string.Concat(widths.Select(w => $"<w:gridCol w:w=\"{Number(Twips(w))}\"/>"))).Append("</w:tblGrid>");
+
+ var horizontalPadding = margin is { } cellMargin ? cellMargin.Left + cellMargin.Right : 1080;
+ var outerWidth = _width;
+ var headerRows = table.Rows.TakeWhile(r => r.Header).Count();
+ for (var r = 0; r < table.Rows.Count; r++)
+ {
+ var row = table.Rows[r];
+ sb.Append("<w:tr>");
+ if (row.Height is > 0 || r < headerRows)
+ {
+ sb.Append("<w:trPr>");
+ if (row.Height is > 0 and var height)
+ sb.Append($"<w:trHeight w:val=\"{Number(Twips(height))}\" w:hRule=\"atLeast\"/>");
+ if (r < headerRows)
+ sb.Append("<w:tblHeader/>");
+ sb.Append("</w:trPr>");
+ }
+
+ var starts = r < placed.Count ? placed[r].GroupBy(p => p.Column).ToDictionary(g => g.Key, g => g.First().Cell) : [];
+ for (var column = 0; column < columnCount;)
+ {
+ if (starts.TryGetValue(column, out var cell))
+ {
+ var span = Math.Clamp(cell.ColSpan, 1, columnCount - column);
+ var width = widths.Skip(column).Take(span).Sum();
+ _width = Math.Max(1000, width - horizontalPadding);
+ sb.Append(Cell(cell, width, span, cell.RowSpan > 1 ? "<w:vMerge w:val=\"restart\"/>" : "", Blocks(cell.Blocks, requireParagraph: true)));
+ column += span;
+ }
+ else if (continuations.TryGetValue((r, column), out var origin))
+ {
+ var span = Math.Clamp(origin.ColSpan, 1, columnCount - column);
+ sb.Append(Cell(origin, widths.Skip(column).Take(span).Sum(), span, "<w:vMerge/>", "<w:p/>"));
+ column += span;
+ }
+ else
+ {
+ // A gap in a ragged row: an empty cell keeps the grid rectangular.
+ sb.Append($"<w:tc><w:tcPr><w:tcW w:w=\"{Number(Twips(widths[column]))}\" w:type=\"dxa\"/></w:tcPr><w:p/></w:tc>");
+ column++;
+ }
+ }
+ sb.Append("</w:tr>");
+ }
+ _width = outerWidth;
+ sb.Append("</w:tbl>");
+ if (table.Caption.Count > 0)
+ sb.Append(Blocks(table.Caption));
+ return sb.ToString();
+ }
+
+ /// <summary>w:tc with w:tcPr in CT_TcPr order: tcW, gridSpan, vMerge, tcBorders, shd, vAlign.</summary>
+ private static string Cell(HCell cell, int width, int span, string vMerge, string content)
+ {
+ var sb = new StringBuilder("<w:tc><w:tcPr>");
+ sb.Append($"<w:tcW w:w=\"{Number(Twips(width))}\" w:type=\"dxa\"/>");
+ if (span > 1)
+ sb.Append($"<w:gridSpan w:val=\"{Number(span)}\"/>");
+ sb.Append(vMerge);
+ if (cell.Borders is { } borders)
+ {
+ sb.Append("<w:tcBorders>")
+ .Append(Border("top", borders.Top)).Append(Border("left", borders.Left))
+ .Append(Border("bottom", borders.Bottom)).Append(Border("right", borders.Right))
+ .Append("</w:tcBorders>");
+ }
+ if (Hex(cell.Fill) is { } fill)
+ sb.Append($"<w:shd w:val=\"clear\" w:color=\"auto\" w:fill=\"{fill}\"/>");
+ if (cell.VerticalAlign != HVerticalAlign.Top)
+ sb.Append($"<w:vAlign w:val=\"{(cell.VerticalAlign == HVerticalAlign.Center ? "center" : "bottom")}\"/>");
+ sb.Append("</w:tcPr>").Append(content);
+ return sb.Append("</w:tc>").ToString();
+ }
+
+ /// <summary>A border edge: style, width in eighths of a point (2..96), colour.</summary>
+ private static string Border(string edge, HBorder border)
+ {
+ if (border.Style == HBorderStyle.None)
+ return $"<w:{edge} w:val=\"nil\"/>";
+ var style = border.Style switch
+ {
+ HBorderStyle.Dash => "dashed",
+ HBorderStyle.Dot => "dotted",
+ HBorderStyle.DashDot => "dotDash",
+ HBorderStyle.Double => "double",
+ _ => "single",
+ };
+ var eighths = Math.Clamp((int)Math.Round(border.WidthMm / 25.4 * 72 * 8), 2, 96);
+ return $"<w:{edge} w:val=\"{style}\" w:sz=\"{Number(eighths)}\" w:space=\"0\" w:color=\"{Hex(border.Color) ?? "auto"}\"/>";
+ }
+}
diff --git a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxWriter.Objects.cs b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxWriter.Objects.cs
new file mode 100644
index 00000000..16e1884c
--- /dev/null
+++ b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxWriter.Objects.cs
@@ -0,0 +1,313 @@
+// Objects inside runs: pictures (DrawingML, inline or floating), text boxes and simple shapes (Word 2010 "wps"
+// shapes inside mc:AlternateContent, as Word writes them), hyperlinks and bookmarks.
+//
+// Child order follows CT_Inline / CT_Anchor (extent, effectExtent, wrap, docPr, cNvGraphicFramePr, graphic) and
+// CT_WordprocessingShape (cNvSpPr, spPr, txbx, bodyPr). Every drawing gets a document-wide unique docPr id.
+
+using System.Globalization;
+using System.Text;
+using ImageMagick;
+
+namespace Filee.Engines.Hwp.Hwpx.Docx;
+
+internal sealed partial class DocxWriter
+{
+ private const string PictureUri = "http://schemas.openxmlformats.org/drawingml/2006/picture";
+ private const string ShapeUri = "http://schemas.microsoft.com/office/word/2010/wordprocessingShape";
+
+ /// <summary>Z order of floating objects (Word counts up from this value).</summary>
+ private int _relativeHeight = 251659264;
+ private int _textBoxDepth;
+
+ // ───────────────────────── Pictures ─────────────────────────
+
+ private string Picture(HImage image)
+ {
+ if (!File.Exists(image.Path) || MediaTarget(image.Path) is not { } target)
+ return ""; // missing or unreadable picture: skip rather than write a broken reference
+
+ var (width, height) = (image.Width, image.Height);
+ if (width is null || height is null)
+ {
+ try
+ {
+ // Pixels at 96 dpi, like Word and browsers show pictures without a physical size.
+ var info = new MagickImageInfo(image.Path);
+ double pxW = info.Width, pxH = info.Height;
+ if (pxW > 0 && pxH > 0)
+ {
+ if (width is null && height is null)
+ (width, height) = ((int)(pxW * HwpxUnits.PerPixel), (int)(pxH * HwpxUnits.PerPixel));
+ else if (width is not null)
+ height = (int)(width.Value * pxH / pxW);
+ else
+ width = (int)(height!.Value * pxW / pxH);
+ }
+ }
+ catch (MagickException)
+ {
+ // Unknown size: a square placeholder size below.
+ }
+ }
+ var w = Math.Max(1, width ?? 8504);
+ var h = Math.Max(1, height ?? w);
+ if (image.Anchor is null && w > _width)
+ {
+ // Inline pictures never overflow the text width.
+ h = (int)((long)h * _width / w);
+ w = _width;
+ }
+
+ var relationship = _part.Relate(RelationshipBase + "image", target);
+ var id = _nextDrawingId++;
+ var name = $"Picture {id}";
+ var graphic =
+ $"<a:graphic><a:graphicData uri=\"{PictureUri}\"><pic:pic>" +
+ $"<pic:nvPicPr><pic:cNvPr id=\"{Number(id)}\" name=\"{name}\"/><pic:cNvPicPr/></pic:nvPicPr>" +
+ $"<pic:blipFill><a:blip r:embed=\"{relationship}\"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill>" +
+ $"<pic:spPr><a:xfrm><a:off x=\"0\" y=\"0\"/><a:ext cx=\"{Number(Emu(w))}\" cy=\"{Number(Emu(h))}\"/></a:xfrm><a:prstGeom prst=\"rect\"><a:avLst/></a:prstGeom></pic:spPr>" +
+ "</pic:pic></a:graphicData></a:graphic>";
+ return $"<w:r><w:drawing>{Frame(image.Anchor, w, h, id, name, graphic, "<a:graphicFrameLocks noChangeAspect=\"1\"/>")}</w:drawing></w:r>";
+ }
+
+ /// <summary>
+ /// Zip path (relative to word/) of a picture, added to the package once. Formats Word may not show are converted
+ /// to PNG when the package is written; null when the file is no picture Magick can read.
+ /// </summary>
+ private string? MediaTarget(string path)
+ {
+ if (_media.TryGetValue(path, out var known))
+ return known.ZipPath["word/".Length..];
+ var extension = Path.GetExtension(path).TrimStart('.').ToLowerInvariant();
+ if (extension == "jpeg")
+ extension = "jpg";
+ if (!PictureTypes.ContainsKey(extension))
+ {
+ try
+ {
+ _ = new MagickImageInfo(path);
+ }
+ catch (MagickException)
+ {
+ return null;
+ }
+ extension = "png";
+ }
+ var zipPath = $"word/media/image{_media.Count + 1}.{extension}";
+ _media[path] = (zipPath, extension);
+ return zipPath["word/".Length..];
+ }
+
+ /// <summary>wp:inline for objects in the text, wp:anchor for floating ones.</summary>
+ private string Frame(HAnchor? anchor, int width, int height, int id, string name, string graphic, string locks = "")
+ {
+ var extent = $"<wp:extent cx=\"{Number(Emu(width))}\" cy=\"{Number(Emu(height))}\"/><wp:effectExtent l=\"0\" t=\"0\" r=\"0\" b=\"0\"/>";
+ var docPr = $"<wp:docPr id=\"{Number(id)}\" name=\"{name}\"/><wp:cNvGraphicFramePr>{locks}</wp:cNvGraphicFramePr>";
+ if (anchor is null)
+ return $"<wp:inline distT=\"0\" distB=\"0\" distL=\"0\" distR=\"0\">{extent}{docPr}{graphic}</wp:inline>";
+
+ var behind = anchor.Wrap == "BEHIND_TEXT";
+ var wrap = anchor.Wrap switch
+ {
+ "SQUARE" => "<wp:wrapSquare wrapText=\"bothSides\"/>",
+ "TOP_AND_BOTTOM" => "<wp:wrapTopAndBottom/>",
+ _ => "<wp:wrapNone/>",
+ };
+ var horizontal = Position("positionH", anchor.HorizontalRelativeTo switch
+ {
+ "PAPER" => "page",
+ "PAGE" => "margin",
+ "PARA" => "character",
+ _ => "column",
+ }, anchor.HorizontalAlign, anchor.HorizontalOffset, "LEFT");
+ var vertical = Position("positionV", anchor.VerticalRelativeTo switch
+ {
+ "PAPER" => "page",
+ "PAGE" => "margin",
+ _ => "paragraph",
+ }, anchor.VerticalAlign, anchor.VerticalOffset, "TOP");
+ return $"<wp:anchor distT=\"0\" distB=\"0\" distL=\"114300\" distR=\"114300\" simplePos=\"0\" relativeHeight=\"{Number(_relativeHeight++)}\" " +
+ $"behindDoc=\"{(behind ? 1 : 0)}\" locked=\"0\" layoutInCell=\"1\" allowOverlap=\"{(anchor.AllowOverlap ? 1 : 0)}\">" +
+ $"<wp:simplePos x=\"0\" y=\"0\"/>{horizontal}{vertical}{extent}{wrap}{docPr}{graphic}</wp:anchor>";
+ }
+
+ /// <summary>An aligned position (left, center, ...) without an offset, or an offset from the reference.</summary>
+ private static string Position(string element, string relativeFrom, string align, int offset, string start)
+ {
+ var content = offset == 0 && align != start && align is "CENTER" or "RIGHT" or "BOTTOM" or "INSIDE" or "OUTSIDE"
+ ? $"<wp:align>{align.ToLowerInvariant()}</wp:align>"
+ : $"<wp:posOffset>{Number(Emu(offset))}</wp:posOffset>";
+ return $"<wp:{element} relativeFrom=\"{relativeFrom}\">{content}</wp:{element}>";
+ }
+
+ // ───────────────────────── Text boxes and shapes ─────────────────────────
+
+ private string TextBox(HTextBox box, RunContext context)
+ {
+ if (_textBoxDepth > 0)
+ {
+ // Word has no text boxes inside text boxes: keep the text in place.
+ var text = new StringBuilder();
+ foreach (var paragraph in box.Blocks.OfType<HParagraph>())
+ Inlines(paragraph.Inlines.Where(i => i is HText or HLineBreak or HTab), text, context);
+ return text.ToString();
+ }
+
+ var w = Math.Max(1, box.Width);
+ var h = Math.Max(1, box.Height);
+ var outerWidth = _width;
+ _width = Math.Max(1000, w - box.Padding.Left - box.Padding.Right);
+ _textBoxDepth++;
+ string content;
+ try
+ {
+ content = Blocks(box.Blocks, requireParagraph: true);
+ }
+ finally
+ {
+ _textBoxDepth--;
+ _width = outerWidth;
+ }
+
+ var geometry = box.Shape == HShapeKind.Ellipse ? "ellipse" : box.CornerRatio > 0 ? "roundRect" : "rect";
+ var anchor = box.VerticalAlign switch
+ {
+ HVerticalAlign.Center => "ctr",
+ HVerticalAlign.Bottom => "b",
+ _ => "t",
+ };
+ var shape =
+ "<wps:wsp><wps:cNvSpPr txBox=\"1\"/>" +
+ ShapeProperties(w, h, geometry, box.CornerRatio, box.Fill, box.Gradient, box.Line, flipH: false, flipV: false) +
+ $"<wps:txbx><w:txbxContent>{content}</w:txbxContent></wps:txbx>" +
+ $"<wps:bodyPr rot=\"0\" vert=\"horz\" wrap=\"square\" lIns=\"{Number(Emu(box.Padding.Left))}\" tIns=\"{Number(Emu(box.Padding.Top))}\" " +
+ $"rIns=\"{Number(Emu(box.Padding.Right))}\" bIns=\"{Number(Emu(box.Padding.Bottom))}\" anchor=\"{anchor}\" anchorCtr=\"0\"><a:noAutofit/></wps:bodyPr>" +
+ "</wps:wsp>";
+ return DrawingRun(box.Anchor, w, h, "Text Box", shape);
+ }
+
+ private string Shape(HShape shape)
+ {
+ var w = Math.Max(1, shape.Width);
+ var h = Math.Max(1, shape.Height);
+ var geometry = shape.Kind switch
+ {
+ HShapeKind.Ellipse => "ellipse",
+ HShapeKind.Line => "line",
+ _ => shape.CornerRatio > 0 ? "roundRect" : "rect",
+ };
+ var line = shape.Kind == HShapeKind.Line;
+ var xml =
+ "<wps:wsp><wps:cNvSpPr/>" +
+ ShapeProperties(w, h, geometry, shape.CornerRatio, line ? null : shape.Fill, line ? null : shape.Gradient, shape.Line, shape.FlipHorizontal, shape.FlipVertical) +
+ "<wps:bodyPr/></wps:wsp>";
+ return DrawingRun(shape.Anchor, w, h, "Shape", xml);
+ }
+
+ /// <summary>A wps shape in a run, inside mc:AlternateContent like Word writes it (Word 2007 would need VML).</summary>
+ private string DrawingRun(HAnchor? anchor, int width, int height, string kind, string shape)
+ {
+ var id = _nextDrawingId++;
+ var graphic = $"<a:graphic><a:graphicData uri=\"{ShapeUri}\">{shape}</a:graphicData></a:graphic>";
+ return $"<w:r><mc:AlternateContent><mc:Choice Requires=\"wps\"><w:drawing>{Frame(anchor, width, height, id, $"{kind} {id}", graphic)}</w:drawing></mc:Choice></mc:AlternateContent></w:r>";
+ }
+
+ /// <summary>wps:spPr: xfrm, preset geometry, fill (solid, linear gradient or none) and outline.</summary>
+ private static string ShapeProperties(int width, int height, string geometry, int cornerRatio, string? fill, HGradient? gradient, HBorder line, bool flipH, bool flipV)
+ {
+ var sb = new StringBuilder("<wps:spPr>");
+ sb.Append($"<a:xfrm{(flipH ? " flipH=\"1\"" : "")}{(flipV ? " flipV=\"1\"" : "")}><a:off x=\"0\" y=\"0\"/><a:ext cx=\"{Number(Emu(width))}\" cy=\"{Number(Emu(height))}\"/></a:xfrm>");
+ // 한글's corner ratio (50 = half circle) and DrawingML's "adj" (50000 = half the shorter side) scale alike.
+ sb.Append(geometry == "roundRect"
+ ? $"<a:prstGeom prst=\"roundRect\"><a:avLst><a:gd name=\"adj\" fmla=\"val {Number(Math.Clamp(cornerRatio, 0, 50) * 1000)}\"/></a:avLst></a:prstGeom>"
+ : $"<a:prstGeom prst=\"{geometry}\"><a:avLst/></a:prstGeom>");
+ if (gradient is { Colors.Count: >= 2 })
+ {
+ sb.Append("<a:gradFill rotWithShape=\"1\"><a:gsLst>");
+ for (var i = 0; i < gradient.Colors.Count; i++)
+ {
+ var position = (int)Math.Round(100000.0 * i / (gradient.Colors.Count - 1));
+ sb.Append($"<a:gs pos=\"{Number(position)}\"><a:srgbClr val=\"{Hex(gradient.Colors[i]) ?? "FFFFFF"}\"/></a:gs>");
+ }
+ sb.Append($"</a:gsLst><a:lin ang=\"{Number(((gradient.Angle % 360) + 360) % 360 * 60000)}\" scaled=\"0\"/></a:gradFill>");
+ }
+ else if (Hex(fill) is { } solid)
+ {
+ sb.Append($"<a:solidFill><a:srgbClr val=\"{solid}\"/></a:solidFill>");
+ }
+ else if (geometry != "line")
+ {
+ sb.Append("<a:noFill/>");
+ }
+
+ if (line.Style == HBorderStyle.None)
+ {
+ sb.Append("<a:ln><a:noFill/></a:ln>");
+ }
+ else
+ {
+ var dash = line.Style switch
+ {
+ HBorderStyle.Dash => "<a:prstDash val=\"dash\"/>",
+ HBorderStyle.Dot => "<a:prstDash val=\"sysDot\"/>",
+ HBorderStyle.DashDot => "<a:prstDash val=\"dashDot\"/>",
+ _ => "",
+ };
+ var widthEmu = Math.Max(3175, (long)Math.Round(line.WidthMm * 36000));
+ sb.Append($"<a:ln w=\"{Number(widthEmu)}\"{(line.Style == HBorderStyle.Double ? " cmpd=\"dbl\"" : "")}><a:solidFill><a:srgbClr val=\"{Hex(line.Color) ?? "000000"}\"/></a:solidFill>{dash}</a:ln>");
+ }
+ return sb.Append("</wps:spPr>").ToString();
+ }
+
+ // ───────────────────────── Links and bookmarks ─────────────────────────
+
+ private void Hyperlink(HLink link, StringBuilder sb, RunContext context)
+ {
+ var content = new StringBuilder();
+ Inlines(link.Content, content, context with { Link = true });
+ if (content.Length == 0)
+ return;
+ if (link.Target.StartsWith('#'))
+ {
+ sb.Append($"<w:hyperlink w:anchor=\"{Escape(BookmarkName(link.Target[1..]))}\" w:history=\"1\">").Append(content).Append("</w:hyperlink>");
+ }
+ else if (link.Target.Length > 0)
+ {
+ var id = _part.Relate(RelationshipBase + "hyperlink", SafeUri(link.Target), external: true);
+ sb.Append($"<w:hyperlink r:id=\"{id}\" w:history=\"1\">").Append(content).Append("</w:hyperlink>");
+ }
+ else
+ {
+ sb.Append(content);
+ }
+ }
+
+ /// <summary>A relationship target must be a URI: absolute ones are normalised, spaces in others escaped.</summary>
+ private static string SafeUri(string target)
+ {
+ if (Uri.TryCreate(target, UriKind.Absolute, out var uri) && !uri.IsFile)
+ return uri.AbsoluteUri;
+ return target.Replace("\\", "/", StringComparison.Ordinal).Replace(" ", "%20", StringComparison.Ordinal);
+ }
+
+ /// <summary>
+ /// Word bookmark names start with a letter, hold letters, digits and underscores and are at most 40 characters.
+ /// Names are mapped once, so a link to "#name" finds the bookmark written for "name".
+ /// </summary>
+ private string BookmarkName(string name)
+ {
+ if (_bookmarks.TryGetValue(name, out var known))
+ return known;
+ var clean = new StringBuilder();
+ foreach (var ch in name)
+ clean.Append(char.IsLetterOrDigit(ch) || ch == '_' ? ch : '_');
+ if (clean.Length == 0 || !char.IsLetter(clean[0]))
+ clean.Insert(0, 'b');
+ var baseName = clean.Length > 36 ? clean.ToString(0, 36) : clean.ToString();
+ var result = baseName;
+ for (var i = 2; !_bookmarkNames.Add(result); i++)
+ result = baseName + i.ToString(CultureInfo.InvariantCulture);
+ _bookmarks[name] = result;
+ return result;
+ }
+}
diff --git a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxWriter.cs b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxWriter.cs
new file mode 100644
index 00000000..6664d61b
--- /dev/null
+++ b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxWriter.cs
@@ -0,0 +1,403 @@
+// Writes DOCX (WordprocessingML, ECMA-376) from the HDocument model — the counterpart of DocxReader, written by hand
+// like HwpxWriter, so anything the readers understand (Markdown, TXT, spreadsheets, slides, PDF, ...) becomes an
+// editable Word document without Word, LibreOffice or Pandoc.
+//
+// Split over partial files:
+// * DocxWriter.cs package: parts, relationships, content types, styles, settings, numbering, notes;
+// * DocxWriter.Body.cs sections (page setup, columns, headers/footers), paragraphs, runs and tables;
+// * DocxWriter.Objects.cs pictures (inline and floating), text boxes and shapes (wps), links, bookmarks, fields.
+//
+// Child elements are written in schema order (Word refuses files where they are not), see the notes in each file.
+
+using System.Globalization;
+using System.IO.Compression;
+using System.Text;
+using ImageMagick;
+
+namespace Filee.Engines.Hwp.Hwpx.Docx;
+
+/// <summary>Converts an <see cref="HDocument"/> into a .docx package.</summary>
+internal sealed partial class DocxWriter
+{
+ private const string RelationshipBase = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/";
+ private const string ContentTypeBase = "application/vnd.openxmlformats-officedocument.wordprocessingml.";
+
+ /// <summary>Namespaces of every WordprocessingML part (declared on the root, as Word does).</summary>
+ private const string Namespaces =
+ "xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\" " +
+ "xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" " +
+ "xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" " +
+ "xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" " +
+ "xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" " +
+ "xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\" " +
+ "xmlns:wps=\"http://schemas.microsoft.com/office/word/2010/wordprocessingShape\"";
+
+ private const string Declaration = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>";
+
+ /// <summary>Default body font size (1/100 pt), the size of the Normal style.</summary>
+ private const int DefaultSize = 1000;
+
+ /// <summary>Picture types Word shows as they are; others are converted to PNG.</summary>
+ private static readonly Dictionary<string, string> PictureTypes = new(StringComparer.OrdinalIgnoreCase)
+ {
+ ["png"] = "image/png",
+ ["jpg"] = "image/jpeg",
+ ["jpeg"] = "image/jpeg",
+ ["gif"] = "image/gif",
+ ["bmp"] = "image/bmp",
+ ["emf"] = "image/x-emf",
+ ["wmf"] = "image/x-wmf",
+ };
+
+ private readonly List<Part> _parts = [];
+ private readonly Dictionary<string, (string ZipPath, string Extension)> _media = new(StringComparer.OrdinalIgnoreCase);
+ private readonly List<string> _footnotes = [];
+ private readonly List<string> _endnotes = [];
+ private readonly Dictionary<HNumbering, int> _numberings = new(ReferenceEqualityComparer.Instance);
+ private readonly Dictionary<string, string> _bookmarks = [];
+ private readonly HashSet<string> _bookmarkNames = new(StringComparer.OrdinalIgnoreCase);
+ private readonly Part _document = new("word/document.xml", ContentTypeBase + "document.main+xml");
+ private Part? _footnotesPart;
+ private Part? _endnotesPart;
+ private Part _part;
+ private int _nextDrawingId = 1;
+ private int _nextBookmarkId;
+ private bool _evenAndOddHeaders;
+
+ private DocxWriter() => _part = _document;
+
+ // ───────────────────────── Entry point ─────────────────────────
+
+ /// <summary>Writes <paramref name="document"/> as a .docx file (replaced atomically).</summary>
+ public static void Write(HDocument document, string outputPath)
+ {
+ var writer = new DocxWriter();
+ var body = writer.Body(document);
+ writer.WritePackage(document, body, outputPath);
+ }
+
+ // ───────────────────────── Parts and relationships ─────────────────────────
+
+ /// <summary>A part of the package with its relationships (pictures and links are related per part).</summary>
+ private sealed class Part(string path, string contentType)
+ {
+ public string Path { get; } = path;
+ public string ContentType { get; } = contentType;
+ public string Xml { get; set; } = "";
+ public List<(string Id, string Type, string Target, bool External)> Relationships { get; } = [];
+
+ /// <summary>Id of a relationship from this part (reused when the same target is related twice).</summary>
+ public string Relate(string type, string target, bool external = false)
+ {
+ foreach (var rel in Relationships)
+ {
+ if (rel.Type == type && rel.Target == target && rel.External == external)
+ return rel.Id;
+ }
+ var id = "rId" + (Relationships.Count + 1).ToString(CultureInfo.InvariantCulture);
+ Relationships.Add((id, type, target, external));
+ return id;
+ }
+ }
+
+ /// <summary>Runs <paramref name="write"/> with pictures and links related to <paramref name="part"/>.</summary>
+ private T WithPart<T>(Part part, Func<T> write)
+ {
+ var previous = _part;
+ _part = part;
+ try
+ {
+ return write();
+ }
+ finally
+ {
+ _part = previous;
+ }
+ }
+
+ /// <summary>Creates a header or footer part (content already written) and relates it to the document.</summary>
+ private string HeaderFooterPart(string kind, Func<string> content)
+ {
+ var index = _parts.Count(p => p.Path.StartsWith($"word/{kind}", StringComparison.Ordinal)) + 1;
+ var part = new Part($"word/{kind}{index}.xml", ContentTypeBase + kind + "+xml");
+ var root = kind == "header" ? "w:hdr" : "w:ftr";
+ part.Xml = $"<{root} {Namespaces}>{WithPart(part, content)}</{root}>";
+ _parts.Add(part);
+ return _document.Relate(RelationshipBase + kind, $"{kind}{index}.xml");
+ }
+
+ // ───────────────────────── Package ─────────────────────────
+
+ private void WritePackage(HDocument document, string body, string outputPath)
+ {
+ _document.Xml = $"<w:document {Namespaces}><w:body>{body}</w:body></w:document>";
+ _document.Relate(RelationshipBase + "styles", "styles.xml");
+ _document.Relate(RelationshipBase + "settings", "settings.xml");
+ if (_numberings.Count > 0)
+ _document.Relate(RelationshipBase + "numbering", "numbering.xml");
+ if (_footnotes.Count > 0)
+ _document.Relate(RelationshipBase + "footnotes", "footnotes.xml");
+ if (_endnotes.Count > 0)
+ _document.Relate(RelationshipBase + "endnotes", "endnotes.xml");
+
+ var parts = new List<Part> { _document };
+ parts.AddRange(_parts);
+ parts.Add(new Part("word/styles.xml", ContentTypeBase + "styles+xml") { Xml = Styles() });
+ parts.Add(new Part("word/settings.xml", ContentTypeBase + "settings+xml") { Xml = Settings() });
+ if (_numberings.Count > 0)
+ parts.Add(new Part("word/numbering.xml", ContentTypeBase + "numbering+xml") { Xml = Numbering() });
+ if (_footnotesPart is not null)
+ {
+ _footnotesPart.Xml = Notes("footnote", _footnotes);
+ parts.Add(_footnotesPart);
+ }
+ if (_endnotesPart is not null)
+ {
+ _endnotesPart.Xml = Notes("endnote", _endnotes);
+ parts.Add(_endnotesPart);
+ }
+ parts.Add(new Part("docProps/core.xml", "application/vnd.openxmlformats-package.core-properties+xml") { Xml = CoreProperties(document.Title) });
+ parts.Add(new Part("docProps/app.xml", "application/vnd.openxmlformats-officedocument.extended-properties+xml")
+ {
+ Xml = "<Properties xmlns=\"http://schemas.openxmlformats.org/officeDocument/2006/extended-properties\"><Application>Filee</Application></Properties>",
+ });
+
+ var temp = outputPath + ".tmp";
+ using (var file = File.Create(temp))
+ using (var zip = new ZipArchive(file, ZipArchiveMode.Create))
+ {
+ WriteText(zip, "[Content_Types].xml", ContentTypes(parts));
+ WriteText(zip, "_rels/.rels",
+ "<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">" +
+ $"<Relationship Id=\"rId1\" Type=\"{RelationshipBase}officeDocument\" Target=\"word/document.xml\"/>" +
+ "<Relationship Id=\"rId2\" Type=\"http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties\" Target=\"docProps/core.xml\"/>" +
+ $"<Relationship Id=\"rId3\" Type=\"{RelationshipBase}extended-properties\" Target=\"docProps/app.xml\"/>" +
+ "</Relationships>");
+ foreach (var part in parts)
+ {
+ WriteText(zip, part.Path, part.Xml);
+ if (part.Relationships.Count > 0)
+ {
+ var folder = part.Path[..part.Path.LastIndexOf('/')];
+ var name = part.Path[(part.Path.LastIndexOf('/') + 1)..];
+ WriteText(zip, $"{folder}/_rels/{name}.rels",
+ "<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">" +
+ string.Concat(part.Relationships.Select(r =>
+ $"<Relationship Id=\"{r.Id}\" Type=\"{r.Type}\" Target=\"{Escape(r.Target)}\"{(r.External ? " TargetMode=\"External\"" : "")}/>")) +
+ "</Relationships>");
+ }
+ }
+ foreach (var (source, (zipPath, extension)) in _media)
+ {
+ using var target = zip.CreateEntry(zipPath, CompressionLevel.Optimal).Open();
+ if (string.Equals(Path.GetExtension(source).TrimStart('.'), extension, StringComparison.OrdinalIgnoreCase)
+ || (extension == "jpg" && Path.GetExtension(source).Equals(".jpeg", StringComparison.OrdinalIgnoreCase)))
+ {
+ using var input = File.OpenRead(source);
+ input.CopyTo(target);
+ }
+ else
+ {
+ // WEBP, TIFF, SVG, AVIF ... → PNG, which every Word version shows.
+ using var image = new MagickImage(source);
+ image.Write(target, MagickFormat.Png);
+ }
+ }
+ }
+ File.Move(temp, outputPath, overwrite: true);
+ }
+
+ private string ContentTypes(List<Part> parts)
+ {
+ var sb = new StringBuilder("<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">");
+ sb.Append("<Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>");
+ sb.Append("<Default Extension=\"xml\" ContentType=\"application/xml\"/>");
+ foreach (var extension in _media.Values.Select(m => m.Extension).Distinct(StringComparer.OrdinalIgnoreCase))
+ sb.Append($"<Default Extension=\"{extension}\" ContentType=\"{PictureTypes[extension]}\"/>");
+ foreach (var part in parts)
+ sb.Append($"<Override PartName=\"/{part.Path}\" ContentType=\"{part.ContentType}\"/>");
+ return sb.Append("</Types>").ToString();
+ }
+
+ private static string CoreProperties(string? title)
+ {
+ var now = DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture);
+ return "<cp:coreProperties xmlns:cp=\"http://schemas.openxmlformats.org/package/2006/metadata/core-properties\" " +
+ "xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:dcterms=\"http://purl.org/dc/terms/\" " +
+ "xmlns:dcmitype=\"http://purl.org/dc/dcmitype/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" +
+ (string.IsNullOrWhiteSpace(title) ? "" : $"<dc:title>{Escape(title)}</dc:title>") +
+ $"<dcterms:created xsi:type=\"dcterms:W3CDTF\">{now}</dcterms:created>" +
+ $"<dcterms:modified xsi:type=\"dcterms:W3CDTF\">{now}</dcterms:modified>" +
+ "</cp:coreProperties>";
+ }
+
+ // ───────────────────────── Styles and settings ─────────────────────────
+
+ /// <summary>
+ /// Heading sizes (half-points) of "heading 1".."heading 9". The names are Word's built-in ones, so the navigation
+ /// pane, the table of contents and DocxReader (outline levels) recognise them.
+ /// </summary>
+ private static readonly int[] HeadingSizes = [32, 28, 26, 24, 22, 20, 20, 20, 20];
+
+ private static string Styles()
+ {
+ var sb = new StringBuilder($"<w:styles {Namespaces}>");
+ // Normal matches the HWPX writer's body text: 10 pt, 160 % of the font size ≈ 1.23 Word lines, no spacing.
+ sb.Append("<w:docDefaults><w:rPrDefault><w:rPr>")
+ .Append("<w:rFonts w:ascii=\"Calibri\" w:eastAsia=\"맑은 고딕\" w:hAnsi=\"Calibri\" w:cs=\"Calibri\"/>")
+ .Append("<w:sz w:val=\"20\"/><w:szCs w:val=\"20\"/></w:rPr></w:rPrDefault>")
+ .Append("<w:pPrDefault><w:pPr><w:widowControl/><w:spacing w:after=\"0\" w:line=\"295\" w:lineRule=\"auto\"/></w:pPr></w:pPrDefault></w:docDefaults>");
+ sb.Append("<w:style w:type=\"paragraph\" w:default=\"1\" w:styleId=\"Normal\"><w:name w:val=\"Normal\"/><w:qFormat/></w:style>");
+ sb.Append("<w:style w:type=\"character\" w:default=\"1\" w:styleId=\"DefaultParagraphFont\"><w:name w:val=\"Default Paragraph Font\"/><w:uiPriority w:val=\"1\"/><w:semiHidden/><w:unhideWhenUsed/></w:style>");
+ sb.Append("<w:style w:type=\"table\" w:default=\"1\" w:styleId=\"TableNormal\"><w:name w:val=\"Normal Table\"/><w:uiPriority w:val=\"99\"/><w:semiHidden/><w:unhideWhenUsed/>")
+ .Append("<w:tblPr><w:tblInd w:w=\"0\" w:type=\"dxa\"/><w:tblCellMar><w:top w:w=\"0\" w:type=\"dxa\"/><w:left w:w=\"108\" w:type=\"dxa\"/><w:bottom w:w=\"0\" w:type=\"dxa\"/><w:right w:w=\"108\" w:type=\"dxa\"/></w:tblCellMar></w:tblPr></w:style>");
+ sb.Append("<w:style w:type=\"numbering\" w:default=\"1\" w:styleId=\"NoList\"><w:name w:val=\"No List\"/><w:uiPriority w:val=\"99\"/><w:semiHidden/><w:unhideWhenUsed/></w:style>");
+ for (var level = 1; level <= 9; level++)
+ {
+ var size = HeadingSizes[level - 1];
+ sb.Append($"<w:style w:type=\"paragraph\" w:styleId=\"Heading{level}\"><w:name w:val=\"heading {level}\"/><w:basedOn w:val=\"Normal\"/><w:next w:val=\"Normal\"/>")
+ .Append($"<w:uiPriority w:val=\"9\"/>{(level > 1 ? "<w:unhideWhenUsed/>" : "")}<w:qFormat/>")
+ .Append($"<w:pPr><w:keepNext/><w:keepLines/><w:spacing w:before=\"{(level <= 2 ? 240 : 160)}\" w:after=\"80\"/><w:outlineLvl w:val=\"{level - 1}\"/></w:pPr>")
+ .Append($"<w:rPr><w:b/><w:bCs/><w:sz w:val=\"{size}\"/><w:szCs w:val=\"{size}\"/></w:rPr></w:style>");
+ }
+ sb.Append("<w:style w:type=\"character\" w:styleId=\"Hyperlink\"><w:name w:val=\"Hyperlink\"/><w:basedOn w:val=\"DefaultParagraphFont\"/><w:uiPriority w:val=\"99\"/><w:unhideWhenUsed/><w:rPr><w:color w:val=\"0563C1\"/><w:u w:val=\"single\"/></w:rPr></w:style>");
+ foreach (var kind in new[] { "Footnote", "Endnote" })
+ {
+ sb.Append($"<w:style w:type=\"paragraph\" w:styleId=\"{kind}Text\"><w:name w:val=\"{kind.ToLowerInvariant()} text\"/><w:basedOn w:val=\"Normal\"/><w:uiPriority w:val=\"99\"/><w:semiHidden/><w:unhideWhenUsed/>")
+ .Append("<w:pPr><w:spacing w:line=\"240\" w:lineRule=\"auto\"/></w:pPr><w:rPr><w:sz w:val=\"18\"/><w:szCs w:val=\"18\"/></w:rPr></w:style>");
+ sb.Append($"<w:style w:type=\"character\" w:styleId=\"{kind}Reference\"><w:name w:val=\"{kind.ToLowerInvariant()} reference\"/><w:basedOn w:val=\"DefaultParagraphFont\"/><w:uiPriority w:val=\"99\"/><w:semiHidden/><w:unhideWhenUsed/>")
+ .Append("<w:rPr><w:vertAlign w:val=\"superscript\"/></w:rPr></w:style>");
+ }
+ foreach (var kind in new[] { "Header", "Footer" })
+ {
+ sb.Append($"<w:style w:type=\"paragraph\" w:styleId=\"{kind}\"><w:name w:val=\"{kind.ToLowerInvariant()}\"/><w:basedOn w:val=\"Normal\"/><w:uiPriority w:val=\"99\"/><w:unhideWhenUsed/>")
+ .Append("<w:pPr><w:tabs><w:tab w:val=\"center\" w:pos=\"4513\"/><w:tab w:val=\"right\" w:pos=\"9026\"/></w:tabs><w:spacing w:line=\"240\" w:lineRule=\"auto\"/></w:pPr></w:style>");
+ }
+ sb.Append("<w:style w:type=\"table\" w:styleId=\"TableGrid\"><w:name w:val=\"Table Grid\"/><w:basedOn w:val=\"TableNormal\"/><w:uiPriority w:val=\"39\"/>")
+ .Append("<w:pPr><w:spacing w:line=\"240\" w:lineRule=\"auto\"/></w:pPr><w:tblPr><w:tblBorders>")
+ .Append(string.Concat(new[] { "top", "left", "bottom", "right", "insideH", "insideV" }.Select(e => $"<w:{e} w:val=\"single\" w:sz=\"4\" w:space=\"0\" w:color=\"auto\"/>")))
+ .Append("</w:tblBorders></w:tblPr></w:style>");
+ return sb.Append("</w:styles>").ToString();
+ }
+
+ /// <summary>settings.xml; children follow the CT_Settings sequence.</summary>
+ private string Settings()
+ {
+ var sb = new StringBuilder($"<w:settings {Namespaces}>");
+ sb.Append("<w:zoom w:percent=\"100\"/>");
+ sb.Append("<w:defaultTabStop w:val=\"800\"/>");
+ if (_evenAndOddHeaders)
+ sb.Append("<w:evenAndOddHeaders/>");
+ sb.Append("<w:characterSpacingControl w:val=\"doNotCompress\"/>");
+ if (_footnotes.Count > 0)
+ sb.Append("<w:footnotePr><w:footnote w:id=\"-1\"/><w:footnote w:id=\"0\"/></w:footnotePr>");
+ if (_endnotes.Count > 0)
+ sb.Append("<w:endnotePr><w:endnote w:id=\"-1\"/><w:endnote w:id=\"0\"/></w:endnotePr>");
+ // Word 2013+ layout; without it Word opens the file in compatibility mode.
+ sb.Append("<w:compat><w:compatSetting w:name=\"compatibilityMode\" w:uri=\"http://schemas.microsoft.com/office/word\" w:val=\"15\"/></w:compat>");
+ return sb.Append("</w:settings>").ToString();
+ }
+
+ // ───────────────────────── Numbering ─────────────────────────
+
+ /// <summary>numId of a list (one abstractNum + num per list definition, created on first use).</summary>
+ private int NumberingId(HNumbering numbering)
+ {
+ if (!_numberings.TryGetValue(numbering, out var id))
+ _numberings[numbering] = id = _numberings.Count + 1;
+ return id;
+ }
+
+ /// <summary>Indent of list level <paramref name="level"/> (twips): 400 per level with a 400 hanging number.</summary>
+ private static int ListIndent(int level) => (level + 1) * 400;
+
+ private string Numbering()
+ {
+ var sb = new StringBuilder($"<w:numbering {Namespaces}>");
+ foreach (var (numbering, id) in _numberings)
+ {
+ sb.Append($"<w:abstractNum w:abstractNumId=\"{id}\"><w:multiLevelType w:val=\"hybridMultilevel\"/>");
+ for (var level = 0; level < 9; level++)
+ {
+ var definition = level < numbering.Levels.Count ? numbering.Levels[level] : new HNumberingLevel("DIGIT", $"^{level + 1}.", 1, Bullet: false);
+ var (format, text) = definition.Bullet
+ ? ("bullet", definition.Text.Length > 0 ? definition.Text : "●")
+ : (NumberFormat(definition.Format), NumberText(definition.Text));
+ sb.Append($"<w:lvl w:ilvl=\"{level}\"><w:start w:val=\"{Math.Max(0, definition.Start)}\"/><w:numFmt w:val=\"{format}\"/>")
+ .Append($"<w:lvlText w:val=\"{Escape(text)}\"/><w:lvlJc w:val=\"left\"/>")
+ .Append($"<w:pPr><w:ind w:left=\"{ListIndent(level)}\" w:hanging=\"400\"/></w:pPr></w:lvl>");
+ }
+ sb.Append("</w:abstractNum>");
+ }
+ foreach (var id in _numberings.Values)
+ sb.Append($"<w:num w:numId=\"{id}\"><w:abstractNumId w:val=\"{id}\"/></w:num>");
+ return sb.Append("</w:numbering>").ToString();
+ }
+
+ /// <summary>OWPML number format → Word numFmt (the inverse of DocxReader.NumberFormat).</summary>
+ private static string NumberFormat(string owpml) => owpml switch
+ {
+ "ROMAN_CAPITAL" => "upperRoman",
+ "ROMAN_SMALL" => "lowerRoman",
+ "LATIN_CAPITAL" => "upperLetter",
+ "LATIN_SMALL" => "lowerLetter",
+ "HANGUL_SYLLABLE" => "ganada",
+ "HANGUL_JAMO" => "chosung",
+ "CIRCLED_DIGIT" => "decimalEnclosedCircle",
+ "HANGUL_PHONETIC" => "koreanDigital",
+ "IDEOGRAPH" => "ideographDigital",
+ _ => "decimal",
+ };
+
+ /// <summary>"^1.^2." → "%1.%2." (Word's level placeholders).</summary>
+ private static string NumberText(string text)
+ {
+ var chars = text.ToCharArray();
+ for (var i = 0; i + 1 < chars.Length; i++)
+ {
+ if (chars[i] == '^' && char.IsDigit(chars[i + 1]))
+ chars[i] = '%';
+ }
+ return new string(chars);
+ }
+
+ // ───────────────────────── Notes ─────────────────────────
+
+ /// <summary>footnotes.xml / endnotes.xml: the two separators Word expects (ids -1 and 0), then the notes from id 1.</summary>
+ private static string Notes(string kind, List<string> notes)
+ {
+ var sb = new StringBuilder($"<w:{kind}s {Namespaces}>");
+ sb.Append($"<w:{kind} w:type=\"separator\" w:id=\"-1\"><w:p><w:pPr><w:spacing w:after=\"0\" w:line=\"240\" w:lineRule=\"auto\"/></w:pPr><w:r><w:separator/></w:r></w:p></w:{kind}>");
+ sb.Append($"<w:{kind} w:type=\"continuationSeparator\" w:id=\"0\"><w:p><w:pPr><w:spacing w:after=\"0\" w:line=\"240\" w:lineRule=\"auto\"/></w:pPr><w:r><w:continuationSeparator/></w:r></w:p></w:{kind}>");
+ for (var i = 0; i < notes.Count; i++)
+ sb.Append($"<w:{kind} w:id=\"{i + 1}\">{notes[i]}</w:{kind}>");
+ return sb.Append($"</w:{kind}s>").ToString();
+ }
+
+ // ───────────────────────── Helpers ─────────────────────────
+
+ /// <summary>HWPUNIT (1/7200 inch) → twips (1/1440 inch).</summary>
+ private static int Twips(int hwpUnit) => (int)Math.Round(hwpUnit / 5.0);
+
+ /// <summary>HWPUNIT → EMU (1/914400 inch).</summary>
+ private static long Emu(int hwpUnit) => hwpUnit * 127L;
+
+ /// <summary>"#RRGGBB" → "RRGGBB", or null when it is not a colour.</summary>
+ private static string? Hex(string? color) =>
+ color is { Length: 7 } && color[0] == '#' && int.TryParse(color.AsSpan(1), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out _)
+ ? color[1..].ToUpperInvariant()
+ : null;
+
+ private static string Escape(string text) => HwpxWriter.Escape(text);
+
+ private static string Number(int value) => value.ToString(CultureInfo.InvariantCulture);
+
+ private static string Number(long value) => value.ToString(CultureInfo.InvariantCulture);
+
+ private static void WriteText(ZipArchive zip, string name, string xml)
+ {
+ using var writer = new StreamWriter(zip.CreateEntry(name, CompressionLevel.Optimal).Open(), new UTF8Encoding(false));
+ writer.Write(Declaration);
+ writer.Write(xml);
+ }
+}
diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxConverter.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxConverter.cs
index 4c0b2c3a..428c7a7a 100644
--- a/src/Filee.Engines/Hwp/Hwpx/HwpxConverter.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxConverter.cs
@@ -1,67 +1,45 @@
-// Anything → HWPX without Hancom Office: a reader turns the source into the HWPX document model and HwpxWriter
-// writes the OWPML package.
-// * DOCX is read directly (Docx/DocxReader), keeping page setup, headers/footers, columns, text boxes and formatting.
-// * TXT needs no reader: one paragraph per line.
-// * Markdown is parsed with Markdig (MarkdownReader), no external engine needed.
-// * XLSX and CSV are read directly (Office/Sheets); every sheet becomes a table (SheetDocument).
-// * PPTX is read directly (Pptx/PptxReader): one page per slide with the objects floating at their places.
-// * HTML, ODT and RTF are parsed by Pandoc (optional engine) into its JSON AST (PandocAstReader).
+// Anything → HWPX without Hancom Office: a reader from DocumentReaders turns the source into the HWPX document model
+// and HwpxWriter writes the OWPML package.
+// * DOCX (and DOCM / DOTX / DOTM) is read directly (Docx/DocxReader), keeping page setup, headers/footers, columns,
+// text boxes and formatting.
+// * TXT needs no reader: one paragraph per line. Markdown is parsed with Markdig (MarkdownReader).
+// * XLSX / XLSM / XLTX and CSV are read directly (Office/Sheets); every sheet becomes a table (SheetDocument).
+// * PPTX / PPTM / POTX / PPSX are read directly (Pptx/PptxReader): one page per slide.
+// * PDF is read with PdfPig (Pdf/PdfDocumentReader): text in reading order, headings, pictures, scans as images.
+// * HTML, ODT, RTF, reStructuredText and LaTeX are parsed by Pandoc (optional engine) into its JSON AST.
-using System.Text;
-using System.Text.Json.Nodes;
using Filee.Core.Conversion;
-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;
namespace Filee.Engines.Hwp.Hwpx;
/// <summary>Writes HWPX files with the built-in OWPML writer.</summary>
public sealed class HwpxConverter : IConverter
{
- private static readonly TimeSpan Timeout = TimeSpan.FromMinutes(2);
-
- /// <summary>Filee format id → Pandoc reader name.</summary>
- private static readonly Dictionary<string, string> PandocReaders = new()
- {
- ["odt"] = "odt",
- ["rtf"] = "rtf",
- ["html"] = "html",
- };
-
- private string? _pandoc;
+ private bool? _pandoc;
public string Id => "hwpx-writer";
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();
public EngineStatus GetStatus()
{
- _pandoc = PandocConverter.Locate();
- return EngineStatus.Available(_pandoc is null
- ? "DOCX, XLSX, PPTX, CSV, TXT, Markdown → HWPX. HTML, ODT and RTF need Pandoc."
- : $"DOCX, XLSX, PPTX, CSV, TXT, Markdown; HTML, ODT, RTF with Pandoc ({_pandoc})");
+ var pandoc = PandocConverter.Locate();
+ _pandoc = pandoc is not null;
+ var builtIn = string.Join(", ", DocumentReaders.BuiltInFormats.Select(f => f.ToUpperInvariant()));
+ var withPandoc = string.Join(", ", DocumentReaders.PandocFormats.Select(f => f.ToUpperInvariant()));
+ return EngineStatus.Available(pandoc is null
+ ? $"{builtIn} → HWPX. {withPandoc} need Pandoc."
+ : $"{builtIn}; {withPandoc} with Pandoc ({pandoc})");
}
public async Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken)
{
progress?.Report(0.1);
- var media = Path.Combine(step.WorkDirectory, $"media-{Guid.NewGuid():N}");
- var document = step.From switch
- {
- "docx" => DocxReader.Read(step.InputPath, media),
- "txt" => TextDocument(await File.ReadAllBytesAsync(step.InputPath, cancellationToken)),
- "md" => MarkdownReader.Read(DecodeText(await File.ReadAllBytesAsync(step.InputPath, cancellationToken)),
- Path.GetDirectoryName(Path.GetFullPath(step.InputPath))!),
- "xlsx" => SheetDocument.Build(XlsxReader.Read(step.InputPath)),
- "csv" => SheetDocument.Build(CsvFormat.Read(step.InputPath)),
- "pptx" => PptxReader.Read(step.InputPath, media),
- _ => await ReadWithPandocAsync(step, media, cancellationToken),
- };
+ var document = await DocumentReaders.ReadAsync(step.InputPath, step.From, step.WorkDirectory, cancellationToken);
progress?.Report(0.6);
var output = step.Output.Allocate("hwpx");
@@ -72,79 +50,9 @@ public sealed class HwpxConverter : IConverter
return [output];
}
- private async Task<HDocument> ReadWithPandocAsync(ConversionStep step, string media, CancellationToken cancellationToken)
- {
- var pandoc = _pandoc ?? PandocConverter.Locate() ?? throw new InvalidOperationException("Pandoc was not found.");
- var json = Path.Combine(step.WorkDirectory, $"ast-{Guid.NewGuid():N}.json");
-
- // Working directory = the input's folder, so relative image paths in HTML resolve.
- var result = await ProcessRunner.RunAsync(pandoc,
- [step.InputPath, "-f", PandocReaders[step.From], "-t", "json", "--extract-media=" + media, "-o", json],
- Timeout, cancellationToken, workingDirectory: Path.GetDirectoryName(Path.GetFullPath(step.InputPath)));
- 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.");
- var inputFolder = Path.GetDirectoryName(Path.GetFullPath(step.InputPath))!;
- 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;
- }
+ /// <summary>Plain text: one paragraph per line (see <see cref="DocumentReaders.TextDocument"/>).</summary>
+ internal static HDocument TextDocument(byte[] bytes) => DocumentReaders.TextDocument(bytes);
- /// <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] == '\uFEFF' ? text[1..] : text;
- }
- catch (DecoderFallbackException)
- {
- Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
- return Encoding.GetEncoding(949).GetString(bytes);
- }
- }
-
- private static List<ConversionEdge> BuildEdges(bool pandoc)
- {
- List<ConversionEdge> edges = [new("txt", "hwpx"), new("docx", "hwpx"), new("md", "hwpx"), new("xlsx", "hwpx"), new("csv", "hwpx"), new("pptx", "hwpx")];
- if (pandoc)
- edges.AddRange(PandocReaders.Keys.Select(from => new ConversionEdge(from, "hwpx")));
- return edges;
- }
+ /// <summary>UTF-8, UTF-16 with BOM or CP949 (see <see cref="DocumentReaders.DecodeText"/>).</summary>
+ internal static string DecodeText(byte[] bytes) => DocumentReaders.DecodeText(bytes);
}
diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Body.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Body.cs
index 46149b20..f4172498 100644
--- a/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Body.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Body.cs
@@ -343,7 +343,7 @@ internal sealed partial class HwpxWriter
/// Grid position of every cell: explicit cell columns (DOCX) or the next free position (Pandoc), skipping
/// positions covered by cells spanning rows from above.
/// </summary>
- private static (List<List<(HCell Cell, int Column)>> Placed, int Columns) PlaceCells(HTable table)
+ internal static (List<List<(HCell Cell, int Column)>> Placed, int Columns) PlaceCells(HTable table)
{
var placed = new List<List<(HCell, int)>>();
var occupied = new HashSet<(int Row, int Column)>();
@@ -373,7 +373,7 @@ internal sealed partial class HwpxWriter
}
/// <summary>Column widths that fit <paramref name="available"/>: absolute (scaled down if too wide), relative or equal.</summary>
- private static int[] ColumnWidths(HTable table, int columns, int available)
+ internal static int[] ColumnWidths(HTable table, int columns, int available)
{
if (table.ColumnWidths is { Length: > 0 } absolute)
{
diff --git a/src/Filee.Engines/Office/DocxWriterConverter.cs b/src/Filee.Engines/Office/DocxWriterConverter.cs
new file mode 100644
index 00000000..24b042cb
--- /dev/null
+++ b/src/Filee.Engines/Office/DocxWriterConverter.cs
@@ -0,0 +1,43 @@
+// Anything → DOCX without Word, LibreOffice or Pandoc: a built-in reader (DocumentReaders) turns the source into the
+// document model and DocxWriter writes WordprocessingML. Its edges cost less than Pandoc's and LibreOffice's, so the
+// built-in writer is used wherever it can read the source.
+
+using Filee.Core.Conversion;
+using Filee.Engines.Hwp.Hwpx;
+using Filee.Engines.Hwp.Hwpx.Docx;
+
+namespace Filee.Engines.Office;
+
+/// <summary>Writes DOCX files with the built-in WordprocessingML writer.</summary>
+public sealed class DocxWriterConverter : IConverter
+{
+ /// <summary>Below Pandoc's and LibreOffice's direct edges (10 and more), so the built-in writer wins.</summary>
+ private const int Cost = 8;
+
+ /// <summary>Word files themselves: DOCX → DOCX is no conversion, the variants are the OOXML engine's job.</summary>
+ private static readonly HashSet<string> WordFormats = new(StringComparer.OrdinalIgnoreCase) { "docx", "docm", "dotx", "dotm" };
+
+ public string Id => "docx-writer";
+ public string DisplayName => "DOCX writer (built-in)";
+ public int MaxParallelism => 0;
+
+ public IReadOnlyList<ConversionEdge> Edges { get; } =
+ DocumentReaders.BuiltInFormats.Where(f => !WordFormats.Contains(f)).Select(f => new ConversionEdge(f, "docx", Cost)).ToList();
+
+ public EngineStatus GetStatus() =>
+ EngineStatus.Available(string.Join(", ", Edges.Select(e => e.From.ToUpperInvariant())) + " → DOCX");
+
+ public async Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken)
+ {
+ progress?.Report(0.1);
+ var document = await DocumentReaders.ReadAsync(step.InputPath, step.From, step.WorkDirectory, cancellationToken);
+ progress?.Report(0.6);
+
+ var output = step.Output.Allocate("docx");
+ if (output is null)
+ return [];
+ await Task.Run(() => DocxWriter.Write(document, output), cancellationToken);
+ progress?.Report(1);
+ return [output];
+ }
+}
diff --git a/src/Filee.Engines/Office/LibreOfficeConverter.cs b/src/Filee.Engines/Office/LibreOfficeConverter.cs
index 6235e846..488c5895 100644
--- a/src/Filee.Engines/Office/LibreOfficeConverter.cs
+++ b/src/Filee.Engines/Office/LibreOfficeConverter.cs
@@ -1,6 +1,7 @@
// Office documents via LibreOffice in headless mode (MPL-2.0): the optional fallback for formats the built-in engines
-// don't handle (DOC, XLS, PPT, OpenDocument, output as DOCX, ...). Filee downloads its own copy on request
-// (engines/libreoffice); a LibreOffice installed on the system is never used.
+// don't handle (DOC, XLS, PPT, OpenDocument, ...) and the only reader of rarer ones: Works / WPS, WordPerfect, Lotus
+// Word Pro, AbiWord, Apple Pages / Numbers / Keynote, StarOffice, WPS Office, Publisher, CorelDRAW, Visio, CGM.
+// Filee downloads its own copy on request (engines/libreoffice); a LibreOffice installed on the system is never used.
//
// Gotchas handled here:
// * Each concurrent soffice process needs its own user profile (-env:UserInstallation), otherwise
@@ -13,11 +14,12 @@
// * soffice reports no progress: ProgressEstimate keeps the progress ring moving while it runs.
using Filee.Core.Conversion;
+using Filee.Core.Formats;
using Filee.Engines.Infrastructure;
namespace Filee.Engines.Office;
-/// <summary>DOCX / DOC / ODT / RTF / XLSX / PPTX / HWP(X) conversions through LibreOffice.</summary>
+/// <summary>Word processor, spreadsheet, presentation and drawing conversions (and HWP / HWPX) through LibreOffice.</summary>
public sealed class LibreOfficeConverter : IConverter
{
private const int Workers = 2;
@@ -30,6 +32,18 @@ public sealed class LibreOfficeConverter : IConverter
private static readonly string[] Calc = ["xlsx", "xls", "ods", "csv"];
private static readonly string[] Impress = ["pptx", "ppt", "odp"];
+ // Formats LibreOffice only reads, by the application that opens them (checked against the filter registry of
+ // LibreOffice 26.2: the DocumentService of each type's preferred import filter).
+ private static readonly string[] WriterImport = ["dot", "wps", "wpd", "lwp", "abw", "pages", "sdw"];
+ private static readonly string[] CalcImport = ["et", "numbers", "sdc"];
+
+ /// <summary>"sda" also covers .sdd: StarDraw files (.sda) open in Draw, StarImpress files (.sdd) in Impress.</summary>
+ private static readonly string[] ImpressImport = ["key", "dps", "sda"];
+
+ /// <summary>CGM opens in Impress but is a drawing: exported like one (PDF, ODG, SVG, PNG).</summary>
+ private static readonly string[] ImpressGraphics = ["cgm"];
+ private static readonly string[] Draw = ["pub", "cdr", "vsd", "odg"];
+
private readonly EngineEnvironment _env;
// A worker profile must never be used by two soffice processes at once: conversions and the warm-up take a
@@ -72,7 +86,7 @@ public sealed class LibreOfficeConverter : IConverter
progress?.Report(0.1);
ProcessResult result;
using (ProgressEstimate.Start(progress, TypicalDuration))
- result = await RunAsync(soffice, slot, FilterFor(step.From, step.To, step.Preset.Document.PdfA), outDir, step.InputPath, cancellationToken);
+ result = await RunAsync(soffice, slot, FilterFor(step.From, step.To, step.Preset.Document.PdfA, FormatRegistry.ExtensionOf(step.InputPath)), outDir, step.InputPath, cancellationToken);
var produced = Directory.EnumerateFiles(outDir).FirstOrDefault(f => new FileInfo(f).Length > 0);
if (produced is null)
throw new InvalidOperationException(
@@ -176,9 +190,10 @@ public sealed class LibreOfficeConverter : IConverter
}
/// <summary>Maps a target format to a LibreOffice <c>--convert-to</c> filter specification.</summary>
- internal static string FilterFor(string from, string to, bool pdfA)
+ /// <param name="extension">Extension of the input file, for format ids that cover files of two applications.</param>
+ internal static string FilterFor(string from, string to, bool pdfA, string? extension = null)
{
- var family = Calc.Contains(from) ? "calc" : Impress.Contains(from) ? "impress" : "writer";
+ var family = FamilyOf(from, extension);
return to switch
{
// PDF/A-2b via the JSON filter options syntax (LibreOffice 7.4+).
@@ -198,10 +213,26 @@ public sealed class LibreOfficeConverter : IConverter
"pptx" => "pptx:Impress MS PowerPoint 2007 XML",
"ppt" => "ppt:MS PowerPoint 97",
"odp" => "odp",
+ "odg" when family == "impress" => "odg:impress8_draw",
+ "odg" => "odg:draw8",
+ "svg" => $"svg:{family}_svg_Export",
+ "png" => $"png:{family}_png_Export",
_ => to,
};
}
+ /// <summary>The LibreOffice application that opens a format: writer, calc, impress or draw.</summary>
+ private static string FamilyOf(string from, string? extension)
+ {
+ if (from == "sda")
+ return string.Equals(extension, "sda", StringComparison.OrdinalIgnoreCase) ? "draw" : "impress";
+ if (Calc.Contains(from) || CalcImport.Contains(from))
+ return "calc";
+ if (Impress.Contains(from) || ImpressImport.Contains(from) || ImpressGraphics.Contains(from))
+ return "impress";
+ return Draw.Contains(from) ? "draw" : "writer";
+ }
+
private static List<ConversionEdge> BuildEdges(bool hwp)
{
var edges = new List<ConversionEdge>();
@@ -221,6 +252,11 @@ public sealed class LibreOfficeConverter : IConverter
Add(Calc, [.. Calc, "pdf", "html"], Fallback);
Add(Impress, [.. Impress, "pdf"], Fallback);
Add(["txt", "html"], ["docx", "odt", "pdf"], Fallback + 3);
+ // Formats only LibreOffice reads, to PDF and the editable formats of their kind.
+ Add(WriterImport, [.. Writer, "pdf", "txt", "html"], Fallback);
+ Add(CalcImport, [.. Calc, "pdf", "html"], Fallback);
+ Add(ImpressImport, [.. Impress, "pdf"], Fallback);
+ Add([.. ImpressGraphics, .. Draw], ["pdf", "odg", "svg", "png"], Fallback);
if (hwp)
Add(["hwp", "hwpx"], ["pdf", "docx", "odt", "rtf"], Fallback + 6);
return edges;
diff --git a/src/Filee.Engines/Office/OoxmlConverter.cs b/src/Filee.Engines/Office/OoxmlConverter.cs
new file mode 100644
index 00000000..7fa6c9d2
--- /dev/null
+++ b/src/Filee.Engines/Office/OoxmlConverter.cs
@@ -0,0 +1,271 @@
+// Office Open XML variants without Office: DOCM / DOTX / DOTM ↔ DOCX, XLSM / XLTX ↔ XLSX and PPTM / POTX / PPSX ↔ PPTX.
+// A variant is the same package with another content type for its main part, so the package is copied with that type
+// rewritten. Going to a macro-free type also drops the VBA project, its signatures and data, Word's key map
+// customisations and Excel 4.0 macro sheets, with every relationship pointing to them (Office refuses a macro-free
+// file that still holds them).
+
+using System.IO.Compression;
+using System.Xml.Linq;
+using Filee.Core.Conversion;
+
+namespace Filee.Engines.Office;
+
+/// <summary>Converts between the variants of Word, Excel and PowerPoint files by rewriting the package.</summary>
+public sealed class OoxmlConverter : IConverter
+{
+ private static readonly XNamespace ContentTypesNs = "http://schemas.openxmlformats.org/package/2006/content-types";
+ private static readonly XNamespace RelationshipsNs = "http://schemas.openxmlformats.org/package/2006/relationships";
+ private static readonly XNamespace OfficeRelationshipsNs = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
+ private static readonly XNamespace SpreadsheetNs = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
+
+ /// <summary>Format id → family, content type of the main part, and whether macros are allowed.</summary>
+ internal static readonly Dictionary<string, (string Family, string ContentType, bool Macros)> Variants = new(StringComparer.OrdinalIgnoreCase)
+ {
+ ["docx"] = ("word", "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml", false),
+ ["docm"] = ("word", "application/vnd.ms-word.document.macroEnabled.main+xml", true),
+ ["dotx"] = ("word", "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml", false),
+ ["dotm"] = ("word", "application/vnd.ms-word.template.macroEnabledTemplate.main+xml", true),
+ ["xlsx"] = ("excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml", false),
+ ["xlsm"] = ("excel", "application/vnd.ms-excel.sheet.macroEnabled.main+xml", true),
+ ["xltx"] = ("excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml", false),
+ ["pptx"] = ("powerpoint", "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml", false),
+ ["pptm"] = ("powerpoint", "application/vnd.ms-powerpoint.presentation.macroEnabled.main+xml", true),
+ ["potx"] = ("powerpoint", "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml", false),
+ ["ppsx"] = ("powerpoint", "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml", false),
+ };
+
+ /// <summary>Content types of macro parts, which only macro-enabled files may contain.</summary>
+ internal static readonly HashSet<string> MacroContentTypes = new(StringComparer.OrdinalIgnoreCase)
+ {
+ "application/vnd.ms-office.vbaProject",
+ "application/vnd.ms-office.vbaProjectSignature",
+ "application/vnd.ms-office.vbaProjectSignatureAgile",
+ "application/vnd.ms-office.vbaProjectSignatureV3",
+ "application/vnd.ms-word.vbaData+xml",
+ "application/vnd.ms-word.keyMapCustomizations+xml",
+ "application/vnd.ms-excel.macrosheet+xml",
+ "application/vnd.ms-excel.intlmacrosheet+xml",
+ };
+
+ public string Id => "ooxml";
+ public string DisplayName => "Office Open XML (built-in)";
+ public int MaxParallelism => 0;
+
+ public IReadOnlyList<ConversionEdge> Edges { get; } =
+ [
+ .. from source in Variants
+ from target in Variants
+ where source.Key != target.Key && source.Value.Family == target.Value.Family
+ select new ConversionEdge(source.Key, target.Key),
+ ];
+
+ public EngineStatus GetStatus() => EngineStatus.Available("DOCM, DOTX, DOTM ↔ DOCX; XLSM, XLTX ↔ XLSX; PPTM, POTX, PPSX ↔ PPTX");
+
+ public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>
+ Task.Run<IReadOnlyList<string>>(() =>
+ {
+ progress?.Report(0.1);
+ var output = step.Output.Allocate(step.To);
+ if (output is null)
+ return [];
+ var temp = output + ".tmp";
+ try
+ {
+ Rewrite(step.InputPath, temp, step.To);
+ File.Move(temp, output, overwrite: true);
+ }
+ finally
+ {
+ if (File.Exists(temp))
+ File.Delete(temp);
+ }
+ progress?.Report(1);
+ return [output];
+ }, cancellationToken);
+
+ /// <summary>Copies the package <paramref name="input"/> to <paramref name="output"/> as the variant <paramref name="to"/>.</summary>
+ internal static void Rewrite(string input, string output, string to)
+ {
+ var target = Variants[to];
+ using var source = ZipFile.OpenRead(input);
+ var types = Load(source, "[Content_Types].xml") ?? throw new InvalidDataException("The file is not an Office Open XML package (no [Content_Types].xml).");
+ var root = types.Root!;
+ var main = Load(source, "_rels/.rels")?.Root?.Elements(RelationshipsNs + "Relationship")
+ .FirstOrDefault(r => ((string?)r.Attribute("Type"))?.EndsWith("/officeDocument", StringComparison.Ordinal) == true)
+ ?.Attribute("Target")?.Value.TrimStart('/')
+ ?? throw new InvalidDataException("The package has no main document part.");
+
+ // The main part gets the target's content type.
+ var mainOverride = root.Elements(ContentTypesNs + "Override")
+ .FirstOrDefault(o => string.Equals(((string?)o.Attribute("PartName"))?.TrimStart('/'), main, StringComparison.OrdinalIgnoreCase));
+ if (mainOverride is null)
+ root.Add(mainOverride = new XElement(ContentTypesNs + "Override", new XAttribute("PartName", "/" + main)));
+ mainOverride.SetAttributeValue("ContentType", target.ContentType);
+
+ // Macro parts (and the relationship parts of those parts) go when the target may not contain macros.
+ var removed = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
+ if (!target.Macros)
+ {
+ foreach (var entry in source.Entries)
+ {
+ if (ContentTypeOf(root, entry.FullName) is { } type && MacroContentTypes.Contains(type))
+ removed.Add(entry.FullName);
+ }
+ foreach (var part in removed.ToList())
+ removed.Add(RelationshipsPartOf(part));
+ root.Elements(ContentTypesNs + "Override")
+ .Where(o => removed.Contains(((string?)o.Attribute("PartName"))?.TrimStart('/') ?? ""))
+ .Remove();
+ root.Elements(ContentTypesNs + "Default")
+ .Where(d => MacroContentTypes.Contains((string?)d.Attribute("ContentType") ?? ""))
+ .Remove();
+ }
+
+ // Relationships to removed parts, by source part (the workbook's sheet list refers to them by id).
+ var removedIds = new Dictionary<string, HashSet<string>>(StringComparer.OrdinalIgnoreCase);
+ using (var file = File.Create(output))
+ using (var zip = new ZipArchive(file, ZipArchiveMode.Create))
+ {
+ foreach (var entry in source.Entries)
+ {
+ if (removed.Contains(entry.FullName) || entry.FullName.EndsWith('/'))
+ continue;
+ if (entry.FullName == "[Content_Types].xml")
+ {
+ Save(zip, entry.FullName, types);
+ }
+ else if (removed.Count > 0 && entry.FullName.EndsWith(".rels", StringComparison.OrdinalIgnoreCase))
+ {
+ var rels = Load(source, entry.FullName)!;
+ var owner = OwnerOf(entry.FullName);
+ var dropped = rels.Root!.Elements(RelationshipsNs + "Relationship")
+ .Where(r => (string?)r.Attribute("TargetMode") != "External"
+ && removed.Contains(Resolve(owner, (string?)r.Attribute("Target") ?? "")))
+ .ToList();
+ if (dropped.Count > 0)
+ removedIds[owner] = [.. dropped.Select(r => (string?)r.Attribute("Id") ?? "")];
+ dropped.Remove();
+ Save(zip, entry.FullName, rels);
+ }
+ else
+ {
+ Copy(entry, zip);
+ }
+ }
+ }
+
+ // Excel lists its sheets in the workbook part: a removed macro sheet leaves the list too.
+ if (target.Family == "excel" && removedIds.TryGetValue(main, out var sheetIds) && sheetIds.Count > 0)
+ RemoveSheets(output, main, sheetIds);
+ }
+
+ /// <summary>Removes &lt;sheet&gt; entries (and names scoped to them) whose relationship was removed.</summary>
+ private static void RemoveSheets(string package, string workbookPath, HashSet<string> ids)
+ {
+ using var zip = ZipFile.Open(package, ZipArchiveMode.Update);
+ var entry = zip.GetEntry(workbookPath);
+ if (entry is null)
+ return;
+ XDocument workbook;
+ using (var stream = entry.Open())
+ workbook = XDocument.Load(stream);
+ var sheets = workbook.Root?.Element(SpreadsheetNs + "sheets")?.Elements(SpreadsheetNs + "sheet").ToList() ?? [];
+ var kept = new List<int>();
+ for (var i = 0; i < sheets.Count; i++)
+ {
+ if (ids.Contains((string?)sheets[i].Attribute(OfficeRelationshipsNs + "id") ?? ""))
+ sheets[i].Remove();
+ else
+ kept.Add(i);
+ }
+ foreach (var name in workbook.Root?.Element(SpreadsheetNs + "definedNames")?.Elements(SpreadsheetNs + "definedName").ToList() ?? [])
+ {
+ if (!int.TryParse((string?)name.Attribute("localSheetId"), out var local))
+ continue;
+ var index = kept.IndexOf(local);
+ if (index < 0)
+ name.Remove();
+ else
+ name.SetAttributeValue("localSheetId", index);
+ }
+ foreach (var view in workbook.Descendants(SpreadsheetNs + "workbookView"))
+ {
+ view.Attribute("activeTab")?.Remove();
+ view.Attribute("firstSheet")?.Remove();
+ }
+ entry.Delete();
+ Save(zip, workbookPath, workbook);
+ }
+
+ // ───────────────────────── Package helpers ─────────────────────────
+
+ private static string? ContentTypeOf(XElement types, string partPath)
+ {
+ var name = "/" + partPath;
+ var over = types.Elements(ContentTypesNs + "Override")
+ .FirstOrDefault(o => string.Equals((string?)o.Attribute("PartName"), name, StringComparison.OrdinalIgnoreCase));
+ if (over is not null)
+ return (string?)over.Attribute("ContentType");
+ var extension = Path.GetExtension(partPath).TrimStart('.');
+ return (string?)types.Elements(ContentTypesNs + "Default")
+ .FirstOrDefault(d => string.Equals((string?)d.Attribute("Extension"), extension, StringComparison.OrdinalIgnoreCase))
+ ?.Attribute("ContentType");
+ }
+
+ /// <summary>"word/vbaProject.bin" → "word/_rels/vbaProject.bin.rels".</summary>
+ private static string RelationshipsPartOf(string part)
+ {
+ var slash = part.LastIndexOf('/');
+ return slash < 0 ? $"_rels/{part}.rels" : $"{part[..slash]}/_rels/{part[(slash + 1)..]}.rels";
+ }
+
+ /// <summary>"word/_rels/document.xml.rels" → "word/document.xml"; "_rels/.rels" → "".</summary>
+ private static string OwnerOf(string relsPath)
+ {
+ var folder = relsPath[..relsPath.IndexOf("_rels/", StringComparison.Ordinal)];
+ var name = Path.GetFileName(relsPath);
+ return folder + name[..^".rels".Length];
+ }
+
+ /// <summary>A relationship target resolved against its source part, as a zip path.</summary>
+ private static string Resolve(string sourcePart, string target)
+ {
+ if (target.StartsWith('/'))
+ return target.TrimStart('/');
+ var parts = new List<string>(sourcePart.Contains('/') ? sourcePart[..sourcePart.LastIndexOf('/')].Split('/') : []);
+ foreach (var segment in Uri.UnescapeDataString(target).Split('/'))
+ {
+ if (segment == "..")
+ {
+ if (parts.Count > 0)
+ parts.RemoveAt(parts.Count - 1);
+ }
+ else if (segment is not ("." or ""))
+ {
+ parts.Add(segment);
+ }
+ }
+ return string.Join('/', parts);
+ }
+
+ private static XDocument? Load(ZipArchive zip, string name)
+ {
+ if (zip.GetEntry(name) is not { } entry)
+ return null;
+ using var stream = entry.Open();
+ return XDocument.Load(stream);
+ }
+
+ private static void Save(ZipArchive zip, string name, XDocument xml)
+ {
+ using var stream = zip.CreateEntry(name, CompressionLevel.Optimal).Open();
+ xml.Save(stream, SaveOptions.DisableFormatting);
+ }
+
+ private static void Copy(ZipArchiveEntry entry, ZipArchive zip)
+ {
+ using var source = entry.Open();
+ using var target = zip.CreateEntry(entry.FullName, CompressionLevel.Optimal).Open();
+ source.CopyTo(target);
+ }
+}
diff --git a/src/Filee.Engines/Office/PandocConverter.cs b/src/Filee.Engines/Office/PandocConverter.cs
index 2fa7e8c8..8145cbe4 100644
--- a/src/Filee.Engines/Office/PandocConverter.cs
+++ b/src/Filee.Engines/Office/PandocConverter.cs
@@ -1,12 +1,13 @@
// General document conversions with Pandoc (GPL-2.0-or-later, bundled as a separate program in engines/pandoc).
-// Adds Markdown ↔ DOCX / ODT / RTF and HTML ↔ DOCX / ODT; Markdown → HTML / TXT / HWPX is built in (MarkdownConverter).
+// Adds Markdown ↔ DOCX / ODT / RTF, HTML ↔ DOCX / ODT, and reStructuredText and LaTeX ↔ Markdown / HTML / DOCX / ODT
+// (and → RTF, EPUB, TXT); Markdown → HTML / TXT / HWPX / DOCX is built in (MarkdownConverter, the HWPX and DOCX writers).
using Filee.Core.Conversion;
using Filee.Engines.Infrastructure;
namespace Filee.Engines.Office;
-/// <summary>Markdown, HTML, DOCX, ODT and RTF conversions through Pandoc.</summary>
+/// <summary>Markdown, HTML, DOCX, ODT, RTF, reStructuredText and LaTeX conversions through Pandoc.</summary>
public sealed class PandocConverter : IConverter
{
private static readonly TimeSpan Timeout = TimeSpan.FromMinutes(2);
@@ -18,6 +19,8 @@ public sealed class PandocConverter : IConverter
["docx"] = "docx",
["odt"] = "odt",
["rtf"] = "rtf",
+ ["rst"] = "rst",
+ ["tex"] = "latex",
};
private static readonly Dictionary<string, string> Writers = new()
@@ -28,8 +31,14 @@ public sealed class PandocConverter : IConverter
["odt"] = "odt",
["rtf"] = "rtf",
["txt"] = "plain",
+ ["rst"] = "rst",
+ ["tex"] = "latex",
+ ["epub"] = "epub",
};
+ /// <summary>reStructuredText and LaTeX: what Pandoc reads and writes well (no PDF, which would need a TeX engine).</summary>
+ private static readonly string[] Markup = ["rst", "tex"];
+
private string? _pandoc;
public string Id => "pandoc";
@@ -44,6 +53,14 @@ public sealed class PandocConverter : IConverter
// Overlaps with LibreOffice (the fallback engine, which costs more).
.. new[] { "docx", "odt" }.Select(to => new ConversionEdge("html", to, 14)),
.. new[] { "docx", "odt" }.Select(from => new ConversionEdge(from, "html", 14)),
+ // reStructuredText and LaTeX in / out: only Pandoc does this.
+ .. from markup in Markup
+ from to in new[] { "md", "html", "docx", "odt", "rtf", "epub", "txt", "rst", "tex" }
+ where to != markup
+ select new ConversionEdge(markup, to),
+ .. from markup in Markup
+ from source in new[] { "md", "html", "docx", "odt" }
+ select new ConversionEdge(source, markup),
];
public EngineStatus GetStatus()
@@ -61,9 +78,9 @@ public sealed class PandocConverter : IConverter
progress?.Report(0.1);
List<string> args = [step.InputPath, "-f", Readers[step.From], "-t", Writers[step.To], "-o", output];
- if (step.To == "html")
+ if (step.To is "html" or "tex")
args.Add("--standalone");
- if (step.To is "md" or "html")
+ if (step.To is "md" or "html" or "rst" or "tex")
args.Add("--extract-media=" + Path.Combine(Path.GetDirectoryName(output)!, Path.GetFileNameWithoutExtension(output) + "_files"));
ProcessResult result;
diff --git a/src/Filee.Engines/Office/SpreadsheetConverter.cs b/src/Filee.Engines/Office/SpreadsheetConverter.cs
index e28cf16c..0f300e47 100644
--- a/src/Filee.Engines/Office/SpreadsheetConverter.cs
+++ b/src/Filee.Engines/Office/SpreadsheetConverter.cs
@@ -1,4 +1,4 @@
-// XLSX → CSV and CSV → XLSX without Excel or LibreOffice. XLSX / CSV → PDF, HWPX and HTML go through the HWPX
+// XLSX (and XLSM / XLTX) → CSV and CSV → XLSX without Excel or LibreOffice. XLSX / CSV → PDF, HWPX and HTML go through the HWPX
// writer (sheets become 한글 tables), see HwpxConverter and SheetDocument.
using Filee.Core.Conversion;
@@ -13,9 +13,9 @@ public sealed class SpreadsheetConverter : IConverter
public string DisplayName => "Spreadsheets (built-in)";
public int MaxParallelism => 0;
- public IReadOnlyList<ConversionEdge> Edges { get; } = [new("xlsx", "csv"), new("csv", "xlsx")];
+ public IReadOnlyList<ConversionEdge> Edges { get; } = [new("xlsx", "csv"), new("xlsm", "csv"), new("xltx", "csv"), new("csv", "xlsx")];
- public EngineStatus GetStatus() => EngineStatus.Available("XLSX ↔ CSV");
+ public EngineStatus GetStatus() => EngineStatus.Available("XLSX ↔ CSV, XLSM / XLTX → CSV");
public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>
Task.Run<IReadOnlyList<string>>(() =>
diff --git a/src/Filee.Engines/Pdf/PdfDocumentReader.Layout.cs b/src/Filee.Engines/Pdf/PdfDocumentReader.Layout.cs
new file mode 100644
index 00000000..84bbc727
--- /dev/null
+++ b/src/Filee.Engines/Pdf/PdfDocumentReader.Layout.cs
@@ -0,0 +1,240 @@
+// Page layout analysis for PdfDocumentReader: words → lines (split at column gutters) → paragraphs → reading order.
+//
+// Reading order handles the usual layouts: one column; two or three columns, with titles, figures or footers that span
+// the columns in between. A gutter is a vertical strip that no narrow paragraph crosses while text sits next to it on
+// both sides; paragraphs wider than a column (or crossing a gutter) separate the page into bands read one after the
+// other, and inside a band the columns are read left to right.
+
+using System.Text.RegularExpressions;
+
+namespace Filee.Engines.Pdf;
+
+internal sealed partial class PdfDocumentReader
+{
+ /// <summary>Line starts that begin a new paragraph: bullets and "1." / "a)" / "(3)" numbers.</summary>
+ private static readonly Regex ListStart = new(
+ "^([•◦▪▫●○■□‣⁃∙·\\-–—*]|\\(?\\d{1,3}[.)]|\\(?[a-zA-Z][.)]|[ivxIVX]{1,4}[.)]|[①-⑳]|[가-하][.)])$",
+ RegexOptions.CultureInvariant | RegexOptions.Compiled);
+
+ // ───────────────────────── Lines ─────────────────────────
+
+ /// <summary>
+ /// Groups words on a common baseline into lines, top to bottom, and splits a line where the gap between two words
+ /// is much wider than a space (a column gutter or a tab stop far away).
+ /// </summary>
+ private static List<TextLine> Lines(List<TextWord> words)
+ {
+ var rows = new List<List<TextWord>>();
+ foreach (var word in words.OrderByDescending(w => w.Baseline).ThenBy(w => w.Left))
+ {
+ // Words belong to a recent row whose baseline is close; smaller superscripts sit a little higher.
+ List<TextWord>? row = null;
+ for (var r = rows.Count - 1; r >= Math.Max(0, rows.Count - 3) && row is null; r--)
+ {
+ var first = rows[r][0];
+ var tolerance = 0.5 * Math.Min(first.Size, word.Size);
+ if (Math.Abs(first.Baseline - word.Baseline) <= tolerance || (word.Bottom < first.Top && word.Top > first.Baseline && word.Size < first.Size * 0.8))
+ row = rows[r];
+ }
+ if (row is null)
+ rows.Add(row = []);
+ row.Add(word);
+ }
+
+ // A space is about a quarter of the font size; the median gap between words of a line tells the page's spacing.
+ var gaps = new List<double>();
+ foreach (var row in rows)
+ {
+ row.Sort((a, b) => a.Left.CompareTo(b.Left));
+ for (var i = 1; i < row.Count; i++)
+ gaps.Add(row[i].Left - row[i - 1].Right);
+ }
+ var space = gaps.Count > 0 ? Math.Max(0.5, Median(gaps.Where(g => g > 0))) : 3;
+
+ var lines = new List<TextLine>();
+ foreach (var row in rows)
+ {
+ var current = new List<TextWord> { row[0] };
+ for (var i = 1; i < row.Count; i++)
+ {
+ var gap = row[i].Left - row[i - 1].Right;
+ var size = Math.Min(row[i].Size, row[i - 1].Size);
+ if (gap > Math.Max(5 * space, 1.5 * size))
+ {
+ lines.Add(new TextLine(current));
+ current = [];
+ }
+ current.Add(row[i]);
+ }
+ lines.Add(new TextLine(current));
+ }
+ return lines;
+ }
+
+ // ───────────────────────── Paragraphs ─────────────────────────
+
+ /// <summary>
+ /// Stacks lines into paragraphs. A line continues the paragraph right above it when it is close below (at most
+ /// about one line pitch), overlaps it horizontally and has a similar size, unless it starts a new paragraph: a
+ /// bullet or number, a first-line indent, or a previous line that ended early (its next word would have fit).
+ /// </summary>
+ private static List<Item> Paragraphs(List<TextLine> lines)
+ {
+ var items = new List<Item>();
+ foreach (var line in lines)
+ {
+ Item? best = null;
+ var bestDistance = double.MaxValue;
+ foreach (var item in items)
+ {
+ var last = item.Lines[^1];
+ var distance = last.Baseline - line.Baseline;
+ var size = Math.Max(last.Size, line.Size);
+ if (distance <= 0 || distance > 1.9 * size || Math.Abs(last.Size - line.Size) > 0.2 * size)
+ continue;
+ if (item.Lines.Count >= 2 && distance > 1.3 * Pitch(item))
+ continue; // more space than between the lines so far: a new paragraph
+ var overlap = Math.Min(item.Right, line.Right) - Math.Max(item.Left, line.Left);
+ if (overlap < 0.3 * Math.Min(item.Width, line.Right - line.Left))
+ continue;
+ if (distance < bestDistance)
+ (best, bestDistance) = (item, distance);
+ }
+
+ if (best is not null && !StartsParagraph(best, line))
+ {
+ best.Lines.Add(line);
+ }
+ else
+ {
+ var item = new Item();
+ item.Lines.Add(line);
+ items.Add(item);
+ }
+ }
+ return items;
+ }
+
+ private static bool StartsParagraph(Item item, TextLine line)
+ {
+ var last = item.Lines[^1];
+ var em = line.Size;
+ if (ListStart.IsMatch(line.Words[0].Text))
+ return true;
+
+ // 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);
+ 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;
+ }
+
+ // ───────────────────────── Reading order ─────────────────────────
+
+ /// <summary>Orders a page's paragraphs and pictures for reading and sets the column each one sits in.</summary>
+ private static List<Item> ReadingOrder(List<Item> items)
+ {
+ if (items.Count == 0)
+ return items;
+ var areaLeft = items.Min(i => i.Left);
+ var areaRight = items.Max(i => i.Right);
+ foreach (var item in items)
+ (item.ContainerLeft, item.ContainerRight) = (areaLeft, areaRight);
+
+ var gutters = Gutters(items, areaLeft, areaRight);
+ if (gutters.Count == 0)
+ return [.. items.OrderByDescending(i => i.Top).ThenBy(i => i.Left)];
+
+ // Column bounds between the gutters.
+ var edges = new List<double> { areaLeft };
+ foreach (var (start, end) in gutters)
+ edges.AddRange([start, end]);
+ edges.Add(areaRight);
+ int ColumnOf(Item item)
+ {
+ var center = (item.Left + item.Right) / 2;
+ for (var c = 0; c < edges.Count / 2; c++)
+ {
+ if (center <= edges[2 * c + 1] + 1)
+ return c;
+ }
+ return edges.Count / 2 - 1;
+ }
+ bool Spans(Item item) => gutters.Any(g => item.Left < g.Start - 1 && item.Right > g.End + 1);
+
+ var columnItems = items.Where(i => !Spans(i)).ToList();
+ foreach (var item in columnItems)
+ {
+ var column = ColumnOf(item);
+ var members = columnItems.Where(i => ColumnOf(i) == column).ToList();
+ (item.ContainerLeft, item.ContainerRight) = (members.Min(i => i.Left), members.Max(i => i.Right));
+ }
+
+ // Spanning items split the page into bands; each band is read column by column.
+ var result = new List<Item>();
+ var remaining = columnItems.ToList();
+ foreach (var separator in items.Where(Spans).OrderByDescending(i => i.Top))
+ {
+ var above = remaining.Where(i => i.Top > separator.Top).ToList();
+ result.AddRange(above.OrderBy(ColumnOf).ThenByDescending(i => i.Top));
+ remaining.RemoveAll(above.Contains);
+ result.Add(separator);
+ }
+ result.AddRange(remaining.OrderBy(ColumnOf).ThenByDescending(i => i.Top));
+ return result;
+ }
+
+ /// <summary>
+ /// Vertical strips between columns: no narrow item crosses them, text lies on both sides next to each other over
+ /// several lines, and the strip is at least a few points wide.
+ /// </summary>
+ private static List<(double Start, double End)> Gutters(List<Item> items, double left, double right)
+ {
+ var width = right - left;
+ var narrow = items.Where(i => i.Width < width * 0.6).ToList();
+ if (narrow.Count < 2 || width < 100)
+ return [];
+
+ const double Bin = 2;
+ var bins = (int)Math.Ceiling(width / Bin);
+ var covered = new bool[bins];
+ foreach (var item in narrow)
+ {
+ for (var b = Math.Max(0, (int)((item.Left - left) / Bin)); b < Math.Min(bins, (int)Math.Ceiling((item.Right - left) / Bin)); b++)
+ covered[b] = true;
+ }
+
+ var gutters = new List<(double, double)>();
+ for (var b = 0; b < bins;)
+ {
+ if (covered[b])
+ {
+ b++;
+ continue;
+ }
+ var start = b;
+ while (b < bins && !covered[b])
+ b++;
+ var (gapLeft, gapRight) = (left + start * Bin, left + b * Bin);
+ if (start == 0 || b >= bins || gapRight - gapLeft < 6)
+ continue;
+
+ // Real columns: both sides hold a good share of the page's text height (a heading and a date on one line
+ // do not), with text next to each other over a few lines.
+ var leftSide = narrow.Where(i => i.Right <= gapLeft + 1).ToList();
+ var rightSide = narrow.Where(i => i.Left >= gapRight - 1).ToList();
+ var textHeight = Math.Max(1, (items.Max(i => i.Top) - items.Min(i => i.Bottom)) * 0.2);
+ static double Height(List<Item> side) => side.Sum(i => i.Top - i.Bottom);
+ static int Lines(List<Item> side) => side.Sum(i => Math.Max(1, i.Lines.Count));
+ var overlapping = leftSide.Any(l => rightSide.Any(r => Math.Min(l.Top, r.Top) - Math.Max(l.Bottom, r.Bottom) > 2 * Math.Max(l.Size, r.Size)));
+ if (Height(leftSide) >= textHeight && Height(rightSide) >= textHeight && Lines(leftSide) >= 3 && Lines(rightSide) >= 3 && overlapping)
+ gutters.Add((gapLeft, gapRight));
+ }
+ return gutters;
+ }
+}
diff --git a/src/Filee.Engines/Pdf/PdfDocumentReader.cs b/src/Filee.Engines/Pdf/PdfDocumentReader.cs
new file mode 100644
index 00000000..39d4a1fa
--- /dev/null
+++ b/src/Filee.Engines/Pdf/PdfDocumentReader.cs
@@ -0,0 +1,732 @@
+// PDF → HDocument with PdfPig (Apache-2.0), so PDF → DOCX / HWPX / TXT needs no Word, LibreOffice or OCR engine.
+//
+// Every page's words (with their positions, fonts, sizes and colours) become lines, lines become paragraphs, and the
+// paragraphs and pictures are put in reading order, also on two-column pages (PdfDocumentReader.Layout). Headings
+// come from font sizes, bold / italic from the fonts, page size and margins from the page. Headers and footers that
+// repeat on the pages (and bare page numbers) are left out. A page without text (a scan) becomes the rendered page as
+// a picture (PDFium via PDFtoImage), so the result is complete; there is no OCR.
+//
+// Not converted: tables (their cells come out as paragraphs in reading order), vector drawings on text pages,
+// annotations other than links, form fields.
+
+using System.Text;
+using System.Text.RegularExpressions;
+using Filee.Engines.Hwp.Hwpx;
+using PDFtoImage;
+using SkiaSharp;
+using UglyToad.PdfPig;
+using UglyToad.PdfPig.Content;
+using UglyToad.PdfPig.Core;
+using UglyToad.PdfPig.DocumentLayoutAnalysis.WordExtractor;
+using UglyToad.PdfPig.Exceptions;
+using UglyToad.PdfPig.Graphics.Colors;
+using UglyToad.PdfPig.Tokens;
+
+// PDFtoImage marks its API for the platforms PDFium ships for; Filee only targets desktop platforms, all covered.
+#pragma warning disable CA1416
+
+namespace Filee.Engines.Pdf;
+
+/// <summary>Reads a PDF into the document model (HWPX / DOCX writers, plain text).</summary>
+internal sealed partial class PdfDocumentReader
+{
+ /// <summary>Resolution of rendered scans and of pictures PdfPig cannot decode.</summary>
+ private const int RenderDpi = 150;
+
+ /// <summary>HWPUNIT per point.</summary>
+ private const double Unit = 100;
+
+ private static readonly Regex SubsetPrefix = new("^[A-Z]{6}\\+", RegexOptions.Compiled);
+
+ /// <summary>PostScript names of common fonts → the family names Word and 한글 know.</summary>
+ private static readonly Dictionary<string, string> KnownFonts = new(StringComparer.OrdinalIgnoreCase)
+ {
+ ["Helvetica"] = "Arial",
+ ["Arial"] = "Arial",
+ ["ArialMT"] = "Arial",
+ ["ArialNarrow"] = "Arial Narrow",
+ ["Times"] = "Times New Roman",
+ ["TimesNewRoman"] = "Times New Roman",
+ ["TimesNewRomanPS"] = "Times New Roman",
+ ["TimesNewRomanPSMT"] = "Times New Roman",
+ ["Courier"] = "Courier New",
+ ["CourierNew"] = "Courier New",
+ ["CourierNewPS"] = "Courier New",
+ ["CourierNewPSMT"] = "Courier New",
+ ["MalgunGothic"] = "Malgun Gothic",
+ ["SegoeUI"] = "Segoe UI",
+ ["TrebuchetMS"] = "Trebuchet MS",
+ ["CenturyGothic"] = "Century Gothic",
+ ["BookAntiqua"] = "Book Antiqua",
+ ["ComicSansMS"] = "Comic Sans MS",
+ ["LucidaConsole"] = "Lucida Console",
+ ["PalatinoLinotype"] = "Palatino Linotype",
+ };
+
+ private readonly string _path;
+ private readonly string _mediaFolder;
+ private readonly bool _textOnly;
+ private byte[]? _pdfBytes;
+ private int _pictures;
+
+ private PdfDocumentReader(string path, string mediaFolder, bool textOnly)
+ {
+ _path = path;
+ _mediaFolder = mediaFolder;
+ _textOnly = textOnly;
+ }
+
+ /// <summary>Reads <paramref name="path"/> with pictures (extracted into <paramref name="mediaFolder"/>) and scans.</summary>
+ public static HDocument Read(string path, string mediaFolder) => new PdfDocumentReader(path, mediaFolder, textOnly: false).ReadDocument();
+
+ /// <summary>
+ /// Reads only the text, including invisible text (the OCR layer of scanned PDFs); pictures and scans are left out.
+ /// </summary>
+ public static HDocument ReadText(string path) => new PdfDocumentReader(path, "", textOnly: true).ReadDocument();
+
+ // ───────────────────────── Model of a page ─────────────────────────
+
+ /// <summary>A word with its box (points, y upwards from the bottom of the visible page) and formatting.</summary>
+ private sealed record TextWord(string Text, double Left, double Right, double Top, double Bottom, double Baseline, double Size, HCharFormat Format, string? Link);
+
+ /// <summary>A text line (or the part of it in one column).</summary>
+ private sealed class TextLine(List<TextWord> words)
+ {
+ public List<TextWord> Words { get; } = words;
+ public double Left => Words[0].Left;
+ public double Right => Words[^1].Right;
+ public double Top => Words.Max(w => w.Top);
+ public double Bottom => Words.Min(w => w.Bottom);
+ public double Baseline => Words[0].Baseline;
+ public double Size => Words.Max(w => w.Size);
+ public string Text => string.Join(' ', Words.Select(w => w.Text));
+ }
+
+ /// <summary>A paragraph or a picture on a page, the unit of reading order.</summary>
+ private sealed class Item
+ {
+ public List<TextLine> Lines { get; } = [];
+ public string? PicturePath { get; init; }
+ public PdfRectangle? PictureBounds { get; init; }
+
+ public double Left => PictureBounds?.Left ?? Lines.Min(l => l.Left);
+ public double Right => PictureBounds?.Right ?? Lines.Max(l => l.Right);
+ public double Top => PictureBounds?.Top ?? Lines[0].Top;
+ public double Bottom => PictureBounds?.Bottom ?? Lines[^1].Bottom;
+ public double Width => Right - Left;
+ public bool IsPicture => PicturePath is not null;
+
+ /// <summary>Size of most of the text (by characters).</summary>
+ public double Size => Lines.SelectMany(l => l.Words).GroupBy(w => Math.Round(w.Size * 2) / 2)
+ .OrderByDescending(g => g.Sum(w => w.Text.Length)).Select(g => g.Key).FirstOrDefault(10);
+
+ public string Text => string.Join(' ', Lines.Select(l => l.Text));
+
+ /// <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; }
+ }
+
+ private sealed class PageContent(int index, double width, double height)
+ {
+ public int Index { get; } = index;
+ public double Width { get; } = width;
+ public double Height { get; } = height;
+ public List<Item> Items { get; set; } = [];
+ public bool Scanned { get; set; }
+ public string? ScanPath { get; set; }
+ }
+
+ // ───────────────────────── Document ─────────────────────────
+
+ private HDocument ReadDocument()
+ {
+ PdfDocument pdf;
+ try
+ {
+ pdf = PdfDocument.Open(_path, new ParsingOptions { UseLenientParsing = true, SkipMissingFonts = true });
+ }
+ catch (PdfDocumentEncryptedException)
+ {
+ throw PasswordProtected();
+ }
+
+ using (pdf)
+ {
+ var pages = new List<PageContent>();
+ try
+ {
+ foreach (var page in pdf.GetPages())
+ pages.Add(ReadPage(page));
+ }
+ catch (PdfDocumentEncryptedException)
+ {
+ throw PasswordProtected();
+ }
+
+ RemoveRepeatedHeadersAndFooters(pages);
+ foreach (var page in pages.Where(p => !p.Scanned))
+ page.Items = ReadingOrder(page.Items);
+ var title = NullIfBlank(pdf.Information.Title);
+ return Build(pages, title);
+ }
+ }
+
+ private static InvalidOperationException PasswordProtected() =>
+ new("The PDF is password-protected. Open it with its password and save a copy without one, then convert that copy.");
+
+ private PageContent ReadPage(Page page)
+ {
+ var crop = page.CropBox.Bounds;
+ // A page turned by 90° is shown (and rendered) with width and height swapped.
+ var rotated = page.Rotation.Value % 180 != 0;
+ var content = new PageContent(page.Number - 1, rotated ? crop.Height : crop.Width, rotated ? crop.Width : crop.Height);
+
+ var links = page.GetHyperlinks()
+ .Where(h => h.Uri is { } uri && (uri.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || uri.StartsWith("https://", StringComparison.OrdinalIgnoreCase) || uri.StartsWith("mailto:", StringComparison.OrdinalIgnoreCase)))
+ .Select(h => (Bounds: Shift(h.Bounds, crop), Uri: h.Uri!))
+ .ToList();
+
+ var words = new List<TextWord>();
+ foreach (var word in page.GetWords(NearestNeighbourWordExtractor.Instance))
+ {
+ if (word.TextOrientation != TextOrientation.Horizontal || string.IsNullOrWhiteSpace(word.Text))
+ continue;
+ var letters = word.Letters.Where(l => !string.IsNullOrWhiteSpace(l.Value)).ToList();
+ if (letters.Count == 0)
+ continue;
+ // 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 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));
+ }
+
+ if (words.Count == 0 || (rotated && !_textOnly))
+ {
+ // A scan, a page of drawings, or a turned page: the rendered page keeps everything.
+ content.Scanned = true;
+ if (!_textOnly)
+ content.ScanPath = RenderScan(page.Number - 1);
+ return content;
+ }
+
+ content.Items = Paragraphs(Lines(words));
+ if (!_textOnly)
+ content.Items.AddRange(Pictures(page, content, crop));
+ return content;
+ }
+
+ private static PdfRectangle Shift(PdfRectangle box, PdfRectangle crop) =>
+ new(box.Left - crop.Left, box.Bottom - crop.Bottom, box.Right - crop.Left, box.Top - crop.Bottom);
+
+ private static bool Inside(PdfRectangle box, PdfPoint point) =>
+ point.X >= box.Left && point.X <= box.Right && point.Y >= box.Bottom && point.Y <= box.Top;
+
+ // ───────────────────────── Text formatting ─────────────────────────
+
+ private static HCharFormat Format(Letter letter, double size)
+ {
+ var name = letter.FontName ?? letter.FontDetails?.Name ?? "";
+ var bold = letter.FontDetails?.IsBold == true || letter.RenderingMode == TextRenderingMode.FillThenStroke
+ || Regex.IsMatch(name, "Bold|Black|Heavy|Semibold|SemiBold|Demi", RegexOptions.CultureInvariant);
+ var italic = letter.FontDetails?.IsItalic == true || Regex.IsMatch(name, "Italic|Oblique", RegexOptions.CultureInvariant);
+ return new HCharFormat(
+ Bold: bold,
+ Italic: italic,
+ Size: (int)(Math.Round(size * 2) * 50),
+ Font: FontFamily(name),
+ Color: Color(letter.Color));
+ }
+
+ /// <summary>"ABCDEF+TimesNewRomanPS-BoldMT" → "Times New Roman"; null for names that are no family (F1, T3Font_0).</summary>
+ internal static string? FontFamily(string postScriptName)
+ {
+ var name = SubsetPrefix.Replace(postScriptName, "");
+ var cut = name.IndexOfAny(['-', ',']);
+ if (cut > 0)
+ name = name[..cut];
+ foreach (var suffix in new[] { "PSMT", "MT", "PS" })
+ {
+ if (name.Length > suffix.Length + 2 && name.EndsWith(suffix, StringComparison.Ordinal))
+ {
+ if (KnownFonts.TryGetValue(name, out var mapped))
+ return mapped;
+ name = name[..^suffix.Length];
+ }
+ }
+ if (KnownFonts.TryGetValue(name, out var known))
+ return known;
+ return name.Length < 3 || Regex.IsMatch(name, "^(F|T3Font_?|Font)\\d+$", RegexOptions.CultureInvariant) ? null : name;
+ }
+
+ /// <summary>
+ /// "#RRGGBB" of a text colour, black included: heading styles of the HWPX template are coloured, the PDF's text
+ /// was not.
+ /// </summary>
+ private static string? Color(IColor? color)
+ {
+ if (color is null)
+ return null;
+ try
+ {
+ var (r, g, b) = color.ToRGBValues();
+ return $"#{Channel(r):X2}{Channel(g):X2}{Channel(b):X2}";
+ }
+ catch (Exception ex) when (ex is InvalidOperationException or NotSupportedException or ArgumentException or IndexOutOfRangeException)
+ {
+ return null; // pattern and other colours without an RGB value
+ }
+
+ static int Channel(double value) => (int)Math.Round(Math.Clamp(value, 0, 1) * 255);
+ }
+
+ /// <summary>Latin ligatures (fi, fl, ...) as letters, so the text can be searched and edited.</summary>
+ private static string CleanText(string text)
+ {
+ if (!text.Any(c => c is >= 'ff' and <= 'st'))
+ return text;
+ var sb = new StringBuilder(text.Length + 4);
+ foreach (var ch in text)
+ sb.Append(ch is >= 'ff' and <= 'st' ? ch.ToString().Normalize(NormalizationForm.FormKC) : ch.ToString());
+ return sb.ToString();
+ }
+
+ // ───────────────────────── Pictures ─────────────────────────
+
+ /// <summary>Pictures of a text page. A picture covering the page behind text is the scan under an OCR layer: skipped.</summary>
+ private IEnumerable<Item> Pictures(Page page, PageContent content, PdfRectangle crop)
+ {
+ var result = new List<Item>();
+ SKBitmap? rendered = null;
+ try
+ {
+ foreach (var image in page.GetImages().Take(200))
+ {
+ var bounds = Shift(image.BoundingBox, crop);
+ bounds = new PdfRectangle(Math.Max(0, bounds.Left), Math.Max(0, bounds.Bottom), Math.Min(content.Width, bounds.Right), Math.Min(content.Height, bounds.Top));
+ if (bounds.Width < 6 || bounds.Height < 6 || image.IsImageMask)
+ continue;
+ if (bounds.Width * bounds.Height > 0.85 * content.Width * content.Height)
+ continue;
+
+ string? path = null;
+ if (IsPlainJpeg(image))
+ {
+ path = NewMediaPath("jpg");
+ File.WriteAllBytes(path, image.RawMemory.ToArray());
+ }
+ else if (image.TryGetPng(out var png))
+ {
+ path = NewMediaPath("png");
+ File.WriteAllBytes(path, png);
+ }
+ else
+ {
+ // JPEG 2000, CCITT, unusual colour spaces ...: cut the picture out of the rendered page.
+ rendered ??= Render(content.Index);
+ path = Crop(rendered, bounds, content);
+ }
+ if (path is not null)
+ result.Add(new Item { PicturePath = path, PictureBounds = bounds });
+ }
+ }
+ finally
+ {
+ rendered?.Dispose();
+ }
+ return result;
+ }
+
+ /// <summary>A DCT (JPEG) stream in grey or RGB without a decode array: the bytes are a JPEG file as they are.</summary>
+ private static bool IsPlainJpeg(IPdfImage image)
+ {
+ var dictionary = image.ImageDictionary;
+ if (!dictionary.TryGet(NameToken.Filter, out var filter))
+ return false;
+ var name = filter switch
+ {
+ NameToken single => single.Data,
+ ArrayToken { Data.Count: 1 } array when array.Data[0] is NameToken only => only.Data,
+ _ => null,
+ };
+ if (name is not ("DCTDecode" or "DCT") || dictionary.ContainsKey(NameToken.Decode))
+ return false;
+ var components = image.ColorSpaceDetails?.NumberOfColorComponents ?? 3;
+ return components is 1 or 3;
+ }
+
+ private string NewMediaPath(string extension)
+ {
+ Directory.CreateDirectory(_mediaFolder);
+ return Path.Combine(_mediaFolder, $"pdf-{++_pictures}.{extension}");
+ }
+
+ private SKBitmap Render(int pageIndex)
+ {
+ _pdfBytes ??= File.ReadAllBytes(_path);
+ return Conversion.ToImage(_pdfBytes, pageIndex, null,
+ new RenderOptions(Dpi: RenderDpi, WithAnnotations: true, WithFormFill: true, BackgroundColor: SKColors.White));
+ }
+
+ /// <summary>The whole page as a JPEG, the format of scans.</summary>
+ private string RenderScan(int pageIndex)
+ {
+ using var bitmap = Render(pageIndex);
+ var path = NewMediaPath("jpg");
+ using var data = bitmap.Encode(SKEncodedImageFormat.Jpeg, 85);
+ File.WriteAllBytes(path, data.ToArray());
+ return path;
+ }
+
+ private string? Crop(SKBitmap page, PdfRectangle bounds, PageContent content)
+ {
+ var scaleX = page.Width / content.Width;
+ var scaleY = page.Height / content.Height;
+ var rect = SKRectI.Round(new SKRect(
+ (float)(bounds.Left * scaleX), (float)((content.Height - bounds.Top) * scaleY),
+ (float)(bounds.Right * scaleX), (float)((content.Height - bounds.Bottom) * scaleY)));
+ rect.Intersect(new SKRectI(0, 0, page.Width, page.Height));
+ if (rect.Width < 2 || rect.Height < 2)
+ return null;
+ using var part = new SKBitmap();
+ if (!page.ExtractSubset(part, rect))
+ return null;
+ var path = NewMediaPath("png");
+ using var image = SKImage.FromBitmap(part);
+ using var data = image.Encode(SKEncodedImageFormat.Png, 100);
+ File.WriteAllBytes(path, data.ToArray());
+ return path;
+ }
+
+ // ───────────────────────── Headers and footers ─────────────────────────
+
+ private static readonly Regex PageNumber = new(
+ "^[\\s\\-–—(\\[]*(page|p\\.|페이지|第)?\\s*\\d+\\s*(/|of|페이지|쪽|页)?\\s*\\d*[\\s\\-–—)\\]]*$",
+ RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
+
+ /// <summary>
+ /// Leaves out paragraphs at the top or bottom edge that repeat on most pages (running heads, footers; digits are
+ /// ignored so "Page 3" matches "Page 4") and bare page numbers there.
+ /// </summary>
+ private static void RemoveRepeatedHeadersAndFooters(List<PageContent> pages)
+ {
+ var textPages = pages.Where(p => !p.Scanned).ToList();
+ if (textPages.Count < 2)
+ return;
+ bool AtEdge(Item item, PageContent page) => item.Top > page.Height * 0.9 || item.Bottom < page.Height * 0.1;
+ static string Key(Item item) => Regex.Replace(item.Text, "\\d+", "#").Trim();
+
+ var counts = textPages
+ .SelectMany(p => p.Items.Where(i => !i.IsPicture && AtEdge(i, p)).Select(i => (Page: p.Index, Key: Key(i))).Distinct())
+ .GroupBy(x => x.Key)
+ .ToDictionary(g => g.Key, g => g.Count());
+ var needed = Math.Max(2, (int)Math.Ceiling(textPages.Count * 0.5));
+ foreach (var page in textPages)
+ {
+ page.Items.RemoveAll(i => !i.IsPicture && AtEdge(i, page) && i.Lines.Count <= 2
+ && (counts.GetValueOrDefault(Key(i)) >= needed || PageNumber.IsMatch(i.Text)));
+ }
+ }
+
+ // ───────────────────────── Building the document ─────────────────────────
+
+ private HDocument Build(List<PageContent> pages, string? title)
+ {
+ var document = new HDocument { Title = title };
+ var items = pages.SelectMany(p => p.Items.Where(i => !i.IsPicture)).ToList();
+ var bodySize = BodySize(items);
+ var headingLevels = HeadingLevels(items, bodySize);
+ var (left, right, top, bottom) = Margins(pages);
+ var lineRatio = TypicalLineRatio(items);
+
+ HSection? section = null;
+ foreach (var page in pages)
+ {
+ var hpage = new HPage(Hwp(page.Width), Hwp(page.Height), Hwp(left), Hwp(right), Hwp(top), Hwp(bottom), 0, 0, 0);
+ var newSection = section is null || section.Page != hpage;
+ if (newSection)
+ {
+ section = new HSection { Page = hpage };
+ document.Sections.Add(section);
+ }
+ var blocks = section!.Blocks;
+ var first = blocks.Count;
+
+ if (page.Scanned)
+ {
+ if (page.ScanPath is { } scan)
+ {
+ // Floating behind the (empty) paragraph at the paper's corner: the page image never pushes text.
+ var picture = new HImage(scan)
+ {
+ Width = hpage.Width,
+ Height = hpage.Height,
+ Anchor = new HAnchor("PAPER", "LEFT", 0, "PAPER", "TOP", 0, "BEHIND_TEXT", AllowOverlap: true),
+ };
+ var paragraph = new HParagraph { MarkFormat = new HCharFormat(Size: 100) };
+ paragraph.Inlines.Add(picture);
+ blocks.Add(paragraph);
+ }
+ else
+ {
+ blocks.Add(new HParagraph());
+ }
+ }
+ else
+ {
+ Item? previous = null;
+ foreach (var item in page.Items)
+ {
+ blocks.Add(item.IsPicture ? PictureParagraph(item, previous) : TextParagraph(item, previous, headingLevels, lineRatio));
+ previous = item;
+ }
+ if (blocks.Count == first)
+ blocks.Add(new HParagraph());
+ }
+
+ if (!newSection && blocks[first] is HParagraph startOfPage)
+ startOfPage.PageBreakBefore = true;
+ }
+ if (document.Sections.Count == 0)
+ {
+ var empty = new HSection();
+ empty.Blocks.Add(new HParagraph());
+ document.Sections.Add(empty);
+ }
+ return document;
+ }
+
+ private static int Hwp(double points) => (int)Math.Round(points * Unit);
+
+ /// <summary>The size of most body text (by characters, rounded to half points).</summary>
+ private static double BodySize(List<Item> items) =>
+ items.SelectMany(i => i.Lines).SelectMany(l => l.Words).GroupBy(w => Math.Round(w.Size * 2) / 2)
+ .OrderByDescending(g => g.Sum(w => w.Text.Length)).Select(g => g.Key).FirstOrDefault(10);
+
+ /// <summary>Heading level by size: short paragraphs clearly larger than the body text, the largest size first.</summary>
+ private static Dictionary<double, int> HeadingLevels(List<Item> items, double bodySize)
+ {
+ var sizes = items.Where(i => IsHeadingCandidate(i, bodySize)).Select(i => Math.Round(i.Size)).Distinct().OrderByDescending(s => s).ToList();
+ var levels = new Dictionary<double, int>();
+ for (var i = 0; i < sizes.Count; i++)
+ levels[sizes[i]] = Math.Min(6, i + 1);
+ return levels;
+ }
+
+ private static bool IsHeadingCandidate(Item item, double bodySize) =>
+ !item.IsPicture && item.Lines.Count <= 3 && item.Text.Length <= 200 && item.Size >= bodySize * 1.15 && item.Size >= bodySize + 1;
+
+ /// <summary>Margins shared by the text pages: the smallest distances from the paper edges to any text or picture.</summary>
+ private static (double Left, double Right, double Top, double Bottom) Margins(List<PageContent> pages)
+ {
+ const double Min = 18, Max = 108, Default = 72;
+ double? left = null, right = null, top = null, bottom = null;
+ foreach (var page in pages.Where(p => !p.Scanned && p.Items.Count > 0))
+ {
+ left = Math.Min(left ?? double.MaxValue, page.Items.Min(i => i.Left));
+ right = Math.Min(right ?? double.MaxValue, page.Width - page.Items.Max(i => i.Right));
+ top = Math.Min(top ?? double.MaxValue, page.Height - page.Items.Max(i => i.Top));
+ bottom = Math.Min(bottom ?? double.MaxValue, page.Items.Min(i => i.Bottom));
+ }
+ static double Clamp(double? value) => Math.Clamp(value ?? Default, Min, Max);
+ return (Clamp(left), Clamp(right), Clamp(top), Clamp(bottom));
+ }
+
+ /// <summary>Distance between baselines relative to the font size in multi-line paragraphs (1.2 when unknown).</summary>
+ private static double TypicalLineRatio(List<Item> items)
+ {
+ var ratios = items.Where(i => i.Lines.Count >= 2).Select(i => Pitch(i) / i.Size).Where(r => r is > 0.8 and < 3).ToList();
+ return ratios.Count == 0 ? 1.2 : Median(ratios);
+ }
+
+ private static double Pitch(Item item)
+ {
+ var gaps = new List<double>();
+ for (var i = 1; i < item.Lines.Count; i++)
+ gaps.Add(item.Lines[i - 1].Baseline - item.Lines[i].Baseline);
+ return gaps.Count == 0 ? item.Size * 1.2 : Median(gaps);
+ }
+
+ private static HParagraph PictureParagraph(Item item, Item? previous)
+ {
+ var bounds = item.PictureBounds!.Value;
+ var paragraph = new HParagraph();
+ var containerCenter = (item.ContainerLeft + item.ContainerRight) / 2;
+ var centered = Math.Abs((bounds.Left + bounds.Right) / 2 - containerCenter) < Math.Max(6, (item.ContainerRight - item.ContainerLeft) * 0.05)
+ && bounds.Width < (item.ContainerRight - item.ContainerLeft) * 0.9;
+ paragraph.Format = new HParaFormat(Align: centered ? HAlign.Center : HAlign.Left, Before: SpaceBefore(item, previous), After: 0,
+ // Word's single line spacing (130 % in the model): a smaller multiple would cut off the top of the picture.
+ LineSpacing: new HLineSpacing(HLineSpacingKind.Percent, 130));
+ paragraph.Inlines.Add(new HImage(item.PicturePath!) { Width = Hwp(bounds.Width), Height = Hwp(bounds.Height) });
+ return paragraph;
+ }
+
+ private static HParagraph TextParagraph(Item item, Item? previous, Dictionary<double, int> headingLevels, double lineRatio)
+ {
+ var size = item.Size;
+ var paragraph = new HParagraph();
+ if (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.
+ 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 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)
+ align = HAlign.Right;
+ else if (item.Lines.Count >= 2 && rights.Take(rights.Count - 1).All(r => r < 2.5) && item.Width > containerWidth * 0.5)
+ align = HAlign.Justify;
+ else
+ align = HAlign.Left;
+
+ int? left = null, firstLine = null;
+ if (align is HAlign.Left or HAlign.Justify)
+ {
+ var body = item.Lines.Count > 1 ? lefts.Skip(1).Min() : lefts[0];
+ if (body > 2)
+ left = Hwp(body);
+ var first = lefts[0] - Math.Max(0, body);
+ if (Math.Abs(first) > 2)
+ firstLine = Hwp(first);
+ }
+
+ var pitch = item.Lines.Count >= 2 ? Pitch(item) : size * lineRatio;
+ paragraph.Format = new HParaFormat(
+ Align: align,
+ Left: left,
+ FirstLine: firstLine,
+ 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))));
+ paragraph.MarkFormat = new HCharFormat(Size: (int)(Math.Round(size * 2) * 50));
+ Runs(item, paragraph.Inlines);
+ return paragraph;
+ }
+
+ /// <summary>
+ /// Extra space above an item: its distance to the item right above it (in the same column) minus what a line
+ /// (or a picture's own height) takes anyway. Items at the top of a column get none.
+ /// </summary>
+ private static int SpaceBefore(Item item, Item? previous, double lineRatio = 1.2)
+ {
+ if (previous is null || previous.Bottom <= item.Top - 1 || previous.Right <= item.Left || previous.Left >= item.Right)
+ return 0;
+ // Edges of the line boxes: a text line reaches about 0.25 em below its baseline and 0.95 em above it.
+ var above = previous.IsPicture ? previous.Bottom : previous.Lines[^1].Baseline - 0.25 * previous.Size;
+ var top = item.IsPicture ? item.Top : item.Lines[0].Baseline + 0.95 * item.Size;
+ var normal = item.IsPicture || previous.IsPicture ? 0 : (lineRatio - 1.2) * item.Size;
+ var extra = above - top - normal;
+ return extra > 1 ? Hwp(Math.Min(extra, 72)) : 0;
+ }
+
+ /// <summary>Words joined into runs of equal formatting; line ends become spaces (not inside CJK text or after a hyphen).</summary>
+ private static void Runs(Item item, List<HInline> output)
+ {
+ 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++)
+ {
+ var word = line.Words[w];
+ var text = word.Text;
+ if (pieces.Count > 0)
+ {
+ var (previousText, previousFormat, previousLink) = pieces[^1];
+ if (w > 0)
+ {
+ pieces[^1] = (previousText + " ", previousFormat, previousLink);
+ }
+ else if (previousText.EndsWith('-') && previousText.Length > 1 && char.IsLetter(previousText[^2]) && text.Length > 0 && char.IsLower(text[0]))
+ {
+ pieces[^1] = (previousText[..^1], previousFormat, previousLink); // hyphenated at the line end
+ }
+ else if (!(IsCjk(previousText[^1]) || IsCjk(text[0])))
+ {
+ pieces[^1] = (previousText + " ", previousFormat, previousLink);
+ }
+ }
+ pieces.Add((text, word.Format, word.Link));
+ }
+ }
+
+ HLink? link = null;
+ foreach (var group in Merge(pieces))
+ {
+ var text = new HText(group.Text, group.Format);
+ if (group.Link is null)
+ {
+ link = null;
+ output.Add(text);
+ }
+ else
+ {
+ if (link is null || link.Target != group.Link)
+ {
+ link = new HLink(group.Link);
+ output.Add(link);
+ }
+ link.Content.Add(text);
+ }
+ }
+ }
+
+ private static IEnumerable<(string Text, HCharFormat Format, string? Link)> Merge(List<(string Text, HCharFormat Format, string? Link)> pieces)
+ {
+ var sb = new StringBuilder();
+ HCharFormat format = default;
+ string? link = null;
+ var open = false;
+ foreach (var piece in pieces)
+ {
+ if (open && (piece.Format != format || piece.Link != link))
+ {
+ yield return (sb.ToString(), format, link);
+ sb.Clear();
+ }
+ sb.Append(piece.Text);
+ (format, link, open) = (piece.Format, piece.Link, true);
+ }
+ if (open)
+ yield return (sb.ToString().TrimEnd(), format, link);
+ }
+
+ /// <summary>Chinese and Japanese text has no spaces between words (Korean does).</summary>
+ private static bool IsCjk(char ch) => ch is >= '぀' and <= 'ヿ' or >= '㐀' and <= '鿿' or >= '豈' and <= '﫿' or >= '＀' and <= '⦆' or >= ' ' and <= '〿';
+
+ // ───────────────────────── Helpers ─────────────────────────
+
+ private static double Median(IEnumerable<double> values)
+ {
+ var sorted = values.OrderBy(v => v).ToList();
+ return sorted.Count == 0 ? 0 : sorted[sorted.Count / 2];
+ }
+
+ private static string? NullIfBlank(string? text) => string.IsNullOrWhiteSpace(text) ? null : text.Trim();
+
+ /// <summary>Plain text of a document read by <see cref="ReadText"/>: paragraphs separated by an empty line.</summary>
+ public static string PlainText(HDocument document)
+ {
+ var sb = new StringBuilder();
+ foreach (var paragraph in document.Sections.SelectMany(s => s.Blocks).OfType<HParagraph>())
+ {
+ var text = string.Concat(paragraph.Inlines.SelectMany(i => i is HLink link ? link.Content : [i]).OfType<HText>().Select(t => t.Text)).Trim();
+ if (text.Length == 0)
+ continue;
+ if (sb.Length > 0)
+ sb.Append("\r\n\r\n");
+ sb.Append(text);
+ }
+ return sb.Length == 0 ? "" : sb.Append("\r\n").ToString();
+ }
+}
diff --git a/src/Filee.Engines/Pdf/PdfTextConverter.cs b/src/Filee.Engines/Pdf/PdfTextConverter.cs
new file mode 100644
index 00000000..1fe4c1db
--- /dev/null
+++ b/src/Filee.Engines/Pdf/PdfTextConverter.cs
@@ -0,0 +1,38 @@
+// PDF → TXT with PdfPig (Apache-2.0): the text in reading order (also on two-column pages), one paragraph per line and
+// an empty line between paragraphs. The invisible text layer of OCR-processed scans is included; scans without one
+// have no text to extract (Filee does no OCR).
+
+using System.Text;
+using Filee.Core.Conversion;
+
+namespace Filee.Engines.Pdf;
+
+/// <summary>Extracts the text of PDF files.</summary>
+public sealed class PdfTextConverter : IConverter
+{
+ public string Id => "pdf-text";
+ public string DisplayName => "PDF text (built-in)";
+ public int MaxParallelism => 0;
+
+ public IReadOnlyList<ConversionEdge> Edges { get; } = [new("pdf", "txt")];
+
+ public EngineStatus GetStatus() => EngineStatus.Available("PDF → TXT");
+
+ public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>
+ Task.Run<IReadOnlyList<string>>(() =>
+ {
+ progress?.Report(0.1);
+ var text = PdfDocumentReader.PlainText(PdfDocumentReader.ReadText(step.InputPath));
+ cancellationToken.ThrowIfCancellationRequested();
+ if (text.Length == 0)
+ throw new InvalidOperationException("The PDF contains no text (it may be scanned; Filee does not recognise text in images).");
+
+ var output = step.Output.Allocate("txt");
+ if (output is null)
+ return [];
+ // UTF-8 with BOM, so Notepad and Excel-era tools pick the right encoding for Korean and Chinese text.
+ File.WriteAllText(output, text, new UTF8Encoding(encoderShouldEmitUTF8Identifier: true));
+ progress?.Report(1);
+ return [output];
+ }, cancellationToken);
+}
diff --git a/tests/Filee.Core.Tests/UserDataStoreTests.cs b/tests/Filee.Core.Tests/UserDataStoreTests.cs
index 8c8c81e1..675b75e1 100644
--- a/tests/Filee.Core.Tests/UserDataStoreTests.cs
+++ b/tests/Filee.Core.Tests/UserDataStoreTests.cs
@@ -40,7 +40,7 @@ public class UserDataStoreTests
var store = new UserDataStore(dir.Path);
store.Load();
- Assert.Equal(["magick", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer", "vector", "icns", "font", "cad", "archive", "ebook", "ffmpeg", "pandoc", "ghostscript", "calibre", "libreoffice"], store.Settings.EnginePriority);
+ Assert.Equal(["magick", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer", "pdf-text", "email", "vector", "icns", "font", "cad", "archive", "ebook", "ffmpeg", "pandoc", "ghostscript", "calibre", "libreoffice"], store.Settings.EnginePriority);
Assert.Equal(AppSettings.CurrentSchemaVersion, store.Settings.SchemaVersion);
}
@@ -92,7 +92,7 @@ public class UserDataStoreTests
var store = new UserDataStore(dir.Path);
store.Load();
- Assert.Equal(["magick", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer", "vector", "icns", "font", "cad", "archive", "ebook", "ffmpeg", "pandoc", "ghostscript", "calibre", "libreoffice"], store.Settings.EnginePriority);
+ Assert.Equal(["magick", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer", "pdf-text", "email", "vector", "icns", "font", "cad", "archive", "ebook", "ffmpeg", "pandoc", "ghostscript", "calibre", "libreoffice"], store.Settings.EnginePriority);
var ids = store.Profiles.Select(p => p.Id).ToList();
Assert.Equal(ids.IndexOf("office") + 1, ids.IndexOf("spreadsheets"));
Assert.Equal(ids.IndexOf("office") + 2, ids.IndexOf("presentations"));
diff --git a/tests/Filee.Engines.Tests/DocxAssert.cs b/tests/Filee.Engines.Tests/DocxAssert.cs
new file mode 100644
index 00000000..48ed7002
--- /dev/null
+++ b/tests/Filee.Engines.Tests/DocxAssert.cs
@@ -0,0 +1,127 @@
+// Shared checks for DOCX files written by Filee: the Open XML SDK schema validator (the element order Word enforces),
+// package structure, and an independent reader (LibreOffice) that must convert the file without error.
+
+using System.IO.Compression;
+using System.Xml.Linq;
+using DocumentFormat.OpenXml;
+using DocumentFormat.OpenXml.Packaging;
+using DocumentFormat.OpenXml.Validation;
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Filee.Engines.Hwp.Hwpx;
+using Filee.Engines.Hwp.Hwpx.Docx;
+
+namespace Filee.Engines.Tests;
+
+internal static class DocxAssert
+{
+ public static readonly XNamespace W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
+ public static readonly XNamespace Wp = "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing";
+ private static readonly XNamespace R = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
+ private static readonly XNamespace Rels = "http://schemas.openxmlformats.org/package/2006/relationships";
+ private static readonly XNamespace Types = "http://schemas.openxmlformats.org/package/2006/content-types";
+
+ /// <summary>
+ /// The package is what Word expects: schema-valid parts (element order included), every part with a content type,
+ /// every relationship target present, every r:id resolvable in its part, unique drawing ids.
+ /// </summary>
+ public static void ValidPackage(string docx)
+ {
+ using (var document = WordprocessingDocument.Open(docx, false))
+ {
+ var errors = new OpenXmlValidator(FileFormatVersions.Microsoft365).Validate(document)
+ .Select(e => $"{e.Part?.Uri} {e.Path?.XPath}: {e.Description}")
+ .ToList();
+ Assert.True(errors.Count == 0, string.Join("\n", errors));
+ }
+
+ using var zip = ZipFile.OpenRead(docx);
+ var types = XDocument.Load(zip.GetEntry("[Content_Types].xml")!.Open()).Root!;
+ var overrides = types.Elements(Types + "Override").Select(o => ((string)o.Attribute("PartName")!).TrimStart('/')).ToHashSet(StringComparer.OrdinalIgnoreCase);
+ var defaults = types.Elements(Types + "Default").Select(d => (string)d.Attribute("Extension")!).ToHashSet(StringComparer.OrdinalIgnoreCase);
+ foreach (var entry in zip.Entries.Where(e => e.FullName != "[Content_Types].xml"))
+ Assert.True(overrides.Contains(entry.FullName) || defaults.Contains(Path.GetExtension(entry.FullName).TrimStart('.')), $"{entry.FullName} has no content type");
+ Assert.All(overrides, part => Assert.NotNull(zip.GetEntry(part)));
+
+ foreach (var rels in zip.Entries.Where(e => e.FullName.EndsWith(".rels", StringComparison.Ordinal)))
+ {
+ var folder = rels.FullName[..rels.FullName.IndexOf("_rels/", StringComparison.Ordinal)];
+ var owner = folder + Path.GetFileName(rels.FullName)[..^".rels".Length];
+ var relationships = XDocument.Load(rels.Open()).Root!.Elements(Rels + "Relationship").ToList();
+ foreach (var rel in relationships.Where(r => (string?)r.Attribute("TargetMode") != "External"))
+ Assert.NotNull(zip.GetEntry(folder + (string)rel.Attribute("Target")!));
+ if (owner.Length > 0 && zip.GetEntry(owner) is { } part && owner.EndsWith(".xml", StringComparison.Ordinal))
+ {
+ var ids = relationships.Select(r => (string)r.Attribute("Id")!).ToHashSet();
+ var used = XDocument.Load(part.Open()).Descendants().SelectMany(e => e.Attributes().Where(a => a.Name.Namespace == R)).Select(a => a.Value);
+ Assert.All(used, id => Assert.Contains(id, ids));
+ }
+ }
+
+ var drawingIds = zip.Entries.Where(e => e.FullName.StartsWith("word/", StringComparison.Ordinal) && e.FullName.EndsWith(".xml", StringComparison.Ordinal))
+ .SelectMany(e => XDocument.Load(e.Open()).Descendants(Wp + "docPr").Select(d => (string)d.Attribute("id")!))
+ .ToList();
+ Assert.Equal(drawingIds.Count, drawingIds.Distinct().Count());
+ }
+
+ /// <summary>word/document.xml.</summary>
+ public static XElement Body(string docx, string part = "word/document.xml")
+ {
+ using var zip = ZipFile.OpenRead(docx);
+ return XDocument.Load(zip.GetEntry(part)!.Open(), LoadOptions.PreserveWhitespace).Root!;
+ }
+
+ /// <summary>The file read back with Filee's own DOCX reader.</summary>
+ public static HDocument ReadBack(string docx) => DocxReader.Read(docx, Path.Combine(Path.GetDirectoryName(docx)!, "readback-media"));
+
+ /// <summary>Plain text of a paragraph (links included).</summary>
+ public static string TextOf(HParagraph paragraph) =>
+ string.Concat(paragraph.Inlines.SelectMany(i => i is HLink link ? link.Content : [i]).OfType<HText>().Select(t => t.Text));
+
+ /// <summary>All paragraphs of the body, in tables and text boxes too.</summary>
+ public static IEnumerable<HParagraph> Paragraphs(IEnumerable<HBlock> blocks)
+ {
+ foreach (var block in blocks)
+ {
+ switch (block)
+ {
+ case HParagraph paragraph:
+ yield return paragraph;
+ foreach (var box in paragraph.Inlines.OfType<HTextBox>())
+ {
+ foreach (var inner in Paragraphs(box.Blocks))
+ yield return inner;
+ }
+ break;
+ case HTable table:
+ foreach (var inner in Paragraphs(table.Rows.SelectMany(r => r.Cells).SelectMany(c => c.Blocks)))
+ yield return inner;
+ break;
+ }
+ }
+ }
+
+ /// <summary>
+ /// Converts the file to PDF with LibreOffice (an independent DOCX reader) when it is installed.
+ /// </summary>
+ /// <returns>Number of PDF pages, or null when LibreOffice is not available.</returns>
+ public static async Task<int?> ConvertibleByLibreOfficeAsync(EngineFixture fx, string docx)
+ {
+ var libreOffice = fx.Converters.Single(c => c.Id == "libreoffice");
+ if (!fx.Catalog.StatusOf(libreOffice).IsAvailable || !OperatingSystem.IsWindows())
+ return null;
+ var pdf = Path.ChangeExtension(docx, ".lo.pdf");
+ await HwpxAssert.LibreOfficeGate.WaitAsync(TestContext.Current.CancellationToken);
+ try
+ {
+ var written = await libreOffice.ConvertAsync(new ConversionStep(docx, "docx", "pdf", new Preset(), new HwpxAssert.FixedPath(pdf), Path.GetDirectoryName(docx)!),
+ null, TestContext.Current.CancellationToken);
+ Assert.True(new FileInfo(written.Single()).Length > 1000);
+ }
+ finally
+ {
+ HwpxAssert.LibreOfficeGate.Release();
+ }
+ return PDFtoImage.Conversion.GetPageCount(await File.ReadAllBytesAsync(pdf, TestContext.Current.CancellationToken));
+ }
+}
diff --git a/tests/Filee.Engines.Tests/DocxWriterTests.cs b/tests/Filee.Engines.Tests/DocxWriterTests.cs
new file mode 100644
index 00000000..6a715d70
--- /dev/null
+++ b/tests/Filee.Engines.Tests/DocxWriterTests.cs
@@ -0,0 +1,314 @@
+// Anything → DOCX with the built-in writer (no Word, LibreOffice or Pandoc): every file is validated against the Office
+// Open XML schemas (the element order Word insists on), read back with Filee's DOCX reader and, when LibreOffice is
+// installed, converted to PDF by it as an independent reader. The round trip DOCX → model → DOCX → model checks that
+// the layout the model carries survives (page setup, sections, headers, tables, objects, notes, formatting).
+
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Filee.Engines.Hwp.Hwpx;
+using Filee.Engines.Hwp.Hwpx.Docx;
+using ImageMagick;
+using static Filee.Engines.Tests.DocxAssert;
+using static Filee.Engines.Tests.DocxBuilder;
+
+namespace Filee.Engines.Tests;
+
+public class DocxWriterTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ private static readonly string[] OptionalEngines = ["pandoc", "libreoffice"];
+
+ private RoutePlanner BuiltInPlanner() =>
+ new ConverterCatalog(fx.Converters.Where(c => !OptionalEngines.Contains(c.Id))) { Priority = fx.Catalog.Priority }.CreatePlanner();
+
+ private async Task<string> ConvertAsync(string input, string target = "docx")
+ {
+ var job = await fx.ConvertAsync([input], new Preset { TargetFormat = target });
+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+ return job.Outputs.Single();
+ }
+
+ [Fact]
+ public void Built_in_writer_is_preferred_for_docx()
+ {
+ var planner = fx.Catalog.CreatePlanner(["pandoc", "libreoffice"]);
+ foreach (var from in new[] { "md", "txt", "xlsx", "csv", "pptx", "pdf" })
+ Assert.Equal("docx-writer", Assert.Single(planner.Plan(from, "docx")!.Steps).Converter.Id);
+ Assert.Equal("ooxml", Assert.Single(planner.Plan("docm", "docx")!.Steps).Converter.Id);
+ Assert.DoesNotContain(fx.Converters.Single(c => c.Id == "docx-writer").Edges, e => e.From == "docx");
+ // No optional engine needed.
+ Assert.Equal("docx-writer", Assert.Single(BuiltInPlanner().Plan("md", "docx")!.Steps).Converter.Id);
+ }
+
+ [Fact]
+ public async Task Markdown_becomes_a_word_document_with_real_headings_lists_and_tables()
+ {
+ var dir = fx.NewFolder();
+ using (var chart = new MagickImage(MagickColors.Teal, 160, 90))
+ chart.Write(Path.Combine(dir, "chart.png"));
+ var md = Path.Combine(dir, "회의록.md");
+ await File.WriteAllTextAsync(md, """
+ # 주간 회의
+
+ 오늘 결정한 것: **배포**, *문서 정리*, ~~취소~~, [웹 페이지](https://example.com/?q=한글).
+
+ ## 할 일
+
+ 1. 설치 파일 만들기
+ - 서명하기
+ 2. 문서 고치기
+
+ | 항목 | 담당 |
+ |------|------|
+ | 설치 | 민지 |
+
+ ![그림](chart.png)
+
+ 각주가 있는 문장.[^1]
+
+ [^1]: 각주 내용
+ """, TestContext.Current.CancellationToken);
+
+ var docx = await ConvertAsync(md);
+
+ ValidPackage(docx);
+ var body = Body(docx);
+ Assert.Equal(["Heading1", "Heading2"], body.Descendants(W + "pStyle").Select(s => (string)s.Attribute(W + "val")!).Where(s => s.StartsWith("Heading", StringComparison.Ordinal)));
+ Assert.Contains(Body(docx, "word/styles.xml").Descendants(W + "name"), n => (string?)n.Attribute(W + "val") == "heading 1");
+
+ var model = ReadBack(docx);
+ var paragraphs = Paragraphs(model.Sections.SelectMany(s => s.Blocks)).ToList();
+ Assert.Equal(1, paragraphs.Single(p => TextOf(p) == "주간 회의").HeadingLevel);
+ Assert.Equal(2, paragraphs.Single(p => TextOf(p) == "할 일").HeadingLevel);
+
+ var sentence = paragraphs.Single(p => TextOf(p).StartsWith("오늘 결정한 것", StringComparison.Ordinal));
+ Assert.True(sentence.Inlines.OfType<HText>().Single(t => t.Text == "배포").Format.Bold);
+ Assert.True(sentence.Inlines.OfType<HText>().Single(t => t.Text == "문서 정리").Format.Italic);
+ Assert.True(sentence.Inlines.OfType<HText>().Single(t => t.Text == "취소").Format.Strike);
+ Assert.Equal("https://example.com/?q=%ED%95%9C%EA%B8%80", sentence.Inlines.OfType<HLink>().Single().Target);
+
+ // Lists are Word numbering, with the nested bullet on level 1.
+ var first = paragraphs.Single(p => TextOf(p) == "설치 파일 만들기");
+ Assert.Equal(("DIGIT", "^1.", 0), (first.List!.Numbering.Levels[0].Format, first.List.Numbering.Levels[0].Text, first.List.Level));
+ var nested = paragraphs.Single(p => TextOf(p) == "서명하기");
+ Assert.True(nested.List!.Numbering.Levels[1].Bullet);
+ Assert.Equal(1, nested.List.Level);
+ Assert.Same(first.List.Numbering, paragraphs.Single(p => TextOf(p) == "문서 고치기").List!.Numbering);
+
+ var table = model.Sections.SelectMany(s => s.Blocks).OfType<HTable>().Single();
+ Assert.Equal((2, 2), (table.Rows.Count, table.ColumnCount));
+ Assert.Equal("민지", TextOf((HParagraph)table.Rows[1].Cells[1].Blocks[0]));
+ Assert.True(table.Rows[0].Header);
+
+ var picture = paragraphs.SelectMany(p => p.Inlines).OfType<HImage>().Single();
+ Assert.Equal((160 * 75, 90 * 75), (picture.Width, picture.Height)); // 96 dpi pixels
+ var note = paragraphs.SelectMany(p => p.Inlines).OfType<HNote>().Single();
+ Assert.Contains("각주 내용", string.Concat(note.Blocks.OfType<HParagraph>().Select(TextOf)));
+
+ if (await ConvertibleByLibreOfficeAsync(fx, docx) is { } pages)
+ Assert.Equal(1, pages);
+ }
+
+ [Fact]
+ public async Task Text_becomes_one_paragraph_per_line_on_an_a4_page()
+ {
+ var txt = Path.Combine(fx.NewFolder(), "메모.txt");
+ await File.WriteAllTextAsync(txt, "첫 줄 한글\n\n文件转换 Hello\tTab", TestContext.Current.CancellationToken);
+
+ var docx = await ConvertAsync(txt);
+
+ ValidPackage(docx);
+ var model = ReadBack(docx);
+ var section = Assert.Single(model.Sections);
+ Assert.Equal(["첫 줄 한글", "", "文件转换 HelloTab"], section.Blocks.OfType<HParagraph>().Select(TextOf));
+ Assert.Single(((HParagraph)section.Blocks[2]).Inlines.OfType<HTab>());
+ Assert.Equal((59530, 84190), (section.Page!.Width, section.Page.Height)); // A4 in twips × 5
+ Assert.Equal(7200, section.Page.Left);
+ await ConvertibleByLibreOfficeAsync(fx, docx);
+ }
+
+ [Fact]
+ public async Task Spreadsheets_and_slides_become_tables_and_floating_objects()
+ {
+ var dir = fx.NewFolder();
+ var xlsx = new XlsxBuilder();
+ xlsx.Sheet("매출",
+ XlsxBuilder.Row(1, xlsx.Text("A1", "지점별 매출", XlsxBuilder.Header)) +
+ XlsxBuilder.Row(2, xlsx.Text("A2", "서울"), XlsxBuilder.Number("B2", 1350000, XlsxBuilder.Won)),
+ after: "<mergeCells count=\"1\"><mergeCell ref=\"A1:B1\"/></mergeCells>");
+ var sheetDocx = await ConvertAsync(xlsx.Save(Path.Combine(dir, "매출.xlsx")));
+
+ ValidPackage(sheetDocx);
+ var table = ReadBack(sheetDocx).Sections.SelectMany(s => s.Blocks).OfType<HTable>().Single();
+ var title = table.Rows[0].Cells[0];
+ Assert.Equal((2, "#1F4E79"), (title.ColSpan, title.Fill));
+ Assert.Equal("1,350,000원", TextOf((HParagraph)table.Rows[1].Cells[1].Blocks[0]));
+
+ var pptx = new PptxBuilder();
+ pptx.Slide(pptx.Title("사업 보고") + pptx.Shape("ellipse", 838200, 4400000, 3000000, 1500000, "#7F77DD", "강조"));
+ pptx.Slide(pptx.Title("둘째 장"));
+ var slidesDocx = await ConvertAsync(pptx.Save(Path.Combine(dir, "보고.pptx")));
+
+ ValidPackage(slidesDocx);
+ var slides = ReadBack(slidesDocx);
+ var page = slides.Sections[0].Page!;
+ Assert.True(page.Landscape);
+ var boxes = slides.Sections.SelectMany(s => s.Blocks).OfType<HParagraph>().SelectMany(p => p.Inlines).OfType<HTextBox>().ToList();
+ Assert.Contains(boxes, b => b.Shape == HShapeKind.Ellipse && b.Fill == "#7F77DD" && Paragraphs(b.Blocks).Any(p => TextOf(p) == "강조"));
+ Assert.Contains(Body(slidesDocx).Descendants(), e => e.Name.LocalName == "prstGeom" && (string?)e.Attribute("prst") == "ellipse");
+ Assert.All(boxes, b => Assert.NotNull(b.Anchor));
+ Assert.Single(slides.Sections.SelectMany(s => s.Blocks).OfType<HParagraph>(), p => p.PageBreakBefore);
+ if (await ConvertibleByLibreOfficeAsync(fx, slidesDocx) is { } pages)
+ Assert.Equal(2, pages);
+ }
+
+ /// <summary>A DOCX with most of what the model carries; read, written again by DocxWriter and read back.</summary>
+ [Fact]
+ public async Task Layout_survives_docx_to_model_to_docx()
+ {
+ var source = new DocxBuilder
+ {
+ Numbering = """
+ <w:abstractNum w:abstractNumId="1">
+ <w:lvl w:ilvl="0"><w:start w:val="3"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/><w:pPr><w:ind w:left="400" w:hanging="400"/></w:pPr></w:lvl>
+ <w:lvl w:ilvl="1"><w:start w:val="1"/><w:numFmt w:val="ganada"/><w:lvlText w:val="%2)"/><w:pPr><w:ind w:left="800" w:hanging="400"/></w:pPr></w:lvl>
+ </w:abstractNum>
+ <w:num w:numId="1"><w:abstractNumId w:val="1"/></w:num>
+ """,
+ };
+ using var image = new MagickImage(MagickColors.MediumPurple, 120, 60);
+ var picture = source.Image(image.ToByteArray(MagickFormat.Png));
+ var url = source.Hyperlink("https://example.com/?q=1");
+ source.Footnotes("<w:footnote w:id=\"1\"><w:p><w:r><w:footnoteRef/></w:r>" + R(" 각주 설명") + "</w:p></w:footnote>");
+ var header = source.Header(P(R("머리말") + "<w:r><w:tab/></w:r>" + Field("PAGE", "1"), "<w:tabs><w:tab w:val=\"right\" w:leader=\"dot\" w:pos=\"9000\"/></w:tabs>"));
+ var footer = source.Footer(P(Field("PAGE", "1") + R(" / ") + Field("NUMPAGES", "2"), "<w:jc w:val=\"center\"/>"));
+ const string Shape = "<wps:wsp><wps:spPr><a:xfrm><a:off x=\"0\" y=\"0\"/><a:ext cx=\"1828800\" cy=\"914400\"/></a:xfrm><a:prstGeom prst=\"rect\"/>" +
+ "<a:solidFill><a:srgbClr val=\"FFF2CC\"/></a:solidFill><a:ln w=\"12700\"><a:solidFill><a:srgbClr val=\"C00000\"/></a:solidFill></a:ln></wps:spPr>" +
+ "<wps:txbx><w:txbxContent><w:p><w:r><w:t>글상자 안의 글</w:t></w:r></w:p></w:txbxContent></wps:txbx><wps:bodyPr anchor=\"ctr\"/></wps:wsp>";
+ var cell = (string content, string tcPr) => $"<w:tc><w:tcPr>{tcPr}</w:tcPr>{P(R(content))}</w:tc>";
+
+ source.Paragraph(P("<w:bookmarkStart w:id=\"0\" w:name=\"intro\"/>" + R("큰 제목") + "<w:bookmarkEnd w:id=\"0\"/>", "<w:pStyle w:val=\"Heading1\"/><w:jc w:val=\"center\"/>"))
+ .Paragraph(P(R("굵은 빨강", "<w:rFonts w:ascii=\"Arial\" w:hAnsi=\"Arial\" w:eastAsia=\"굴림\"/><w:b/><w:color w:val=\"FF0000\"/><w:spacing w:val=\"20\"/><w:sz w:val=\"28\"/>") +
+ R(" 형광펜", "<w:highlight w:val=\"yellow\"/>") + R(" 음영", "<w:shd w:val=\"clear\" w:color=\"auto\" w:fill=\"DDEEFF\"/>") +
+ R(" 위첨자", "<w:vertAlign w:val=\"superscript\"/>") + R(" 취소", "<w:strike/>") + R(" 밑줄", "<w:u w:val=\"single\"/>"),
+ "<w:spacing w:before=\"240\" w:after=\"120\" w:line=\"320\" w:lineRule=\"exact\"/><w:ind w:left=\"720\" w:right=\"360\" w:hanging=\"360\"/><w:jc w:val=\"both\"/>"))
+ .Paragraph(P(R("첫 항목"), "<w:numPr><w:ilvl w:val=\"0\"/><w:numId w:val=\"1\"/></w:numPr>"))
+ .Paragraph(P(R("하위 항목"), "<w:numPr><w:ilvl w:val=\"1\"/><w:numId w:val=\"1\"/></w:numPr>"))
+ .Paragraph(P(R("본문") + "<w:r><w:footnoteReference w:id=\"1\"/></w:r>" +
+ $"<w:hyperlink r:id=\"{url}\">" + R("웹 링크", "<w:rStyle w:val=\"Hyperlink\"/>") + "</w:hyperlink>" +
+ "<w:hyperlink w:anchor=\"intro\">" + R("소개로 이동") + "</w:hyperlink>"))
+ .Paragraph("<w:tbl><w:tblPr><w:tblStyle w:val=\"TableGrid\"/><w:jc w:val=\"center\"/></w:tblPr>" +
+ "<w:tblGrid><w:gridCol w:w=\"2000\"/><w:gridCol w:w=\"3000\"/><w:gridCol w:w=\"2000\"/></w:tblGrid>" +
+ "<w:tr><w:trPr><w:tblHeader/></w:trPr>" + cell("가로 병합", "<w:gridSpan w:val=\"2\"/><w:shd w:val=\"clear\" w:color=\"auto\" w:fill=\"E6E6E6\"/>") +
+ cell("세로 병합", "<w:vMerge w:val=\"restart\"/><w:vAlign w:val=\"center\"/>") + "</w:tr>" +
+ "<w:tr>" + cell("A", "") + cell("B", "") + cell("", "<w:vMerge/>") + "</w:tr>" +
+ "<w:tr>" + cell("C", "<w:tcBorders><w:bottom w:val=\"double\" w:sz=\"12\" w:color=\"FF0000\"/></w:tcBorders>") + cell("D", "") + cell("E", "") + "</w:tr>" +
+ "</w:tbl>")
+ .Paragraph(P(InlinePicture(picture, 457200, 457200) +
+ Anchor(PictureUri, Picture(picture, 914400, 457200), 914400, 457200,
+ "<wp:positionH relativeFrom=\"page\"><wp:posOffset>914400</wp:posOffset></wp:positionH>",
+ "<wp:positionV relativeFrom=\"paragraph\"><wp:posOffset>127000</wp:posOffset></wp:positionV>") +
+ Anchor(ShapeUri, Shape, 1828800, 914400, "<wp:positionH relativeFrom=\"margin\"><wp:align>center</wp:align></wp:positionH>",
+ "<wp:positionV relativeFrom=\"page\"><wp:posOffset>3600000</wp:posOffset></wp:positionV>", "<wp:wrapTopAndBottom/>")))
+ .Paragraph(P(R("첫 구역 끝"), $"<w:sectPr><w:headerReference w:type=\"default\" r:id=\"{header}\"/><w:footerReference w:type=\"default\" r:id=\"{footer}\"/>" +
+ "<w:pgSz w:w=\"16838\" w:h=\"11906\" w:orient=\"landscape\"/><w:pgMar w:top=\"1985\" w:right=\"1134\" w:bottom=\"1418\" w:left=\"1134\" w:header=\"851\" w:footer=\"851\" w:gutter=\"0\"/><w:pgNumType w:start=\"5\"/><w:titlePg/></w:sectPr>"))
+ .Paragraph(P(R("한 단 본문"), $"<w:sectPr>{DefaultPage}</w:sectPr>"))
+ .Paragraph(P(R("두 단 왼쪽")))
+ .Paragraph(P(R("두 단 끝"), $"<w:sectPr><w:type w:val=\"continuous\"/>{DefaultPage}<w:cols w:num=\"2\" w:space=\"720\" w:sep=\"1\"/></w:sectPr>"))
+ .Paragraph(P(R("앞 쪽") + "<w:r><w:br w:type=\"page\"/></w:r>" + R("다음 쪽")));
+ source.SectionProperties = "<w:type w:val=\"continuous\"/>" + DefaultPage;
+ var sourcePath = source.Save(Path.Combine(fx.NewFolder(), "원본.docx"));
+
+ var media = Path.Combine(Path.GetDirectoryName(sourcePath)!, "media");
+ var original = DocxReader.Read(sourcePath, media);
+ var written = Path.Combine(Path.GetDirectoryName(sourcePath)!, "다시 쓴 문서.docx");
+ DocxWriter.Write(original, written);
+ ValidPackage(written);
+ var copy = ReadBack(written);
+
+ // Sections and page setup, columns changing within a page, headers and footers.
+ Assert.Equal(original.Sections.Count, copy.Sections.Count);
+ for (var s = 0; s < original.Sections.Count; s++)
+ {
+ Assert.Equal(original.Sections[s].Page, copy.Sections[s].Page);
+ Assert.Equal(original.Sections[s].HideFirstHeader, copy.Sections[s].HideFirstHeader);
+ Assert.Equal(original.Sections[s].StartPageNumber, copy.Sections[s].StartPageNumber);
+ }
+ var first = copy.Sections[0];
+ Assert.True(first.Page!.Landscape);
+ Assert.Equal(5, first.StartPageNumber);
+ Assert.Equal("머리말", TextOf((HParagraph)first.Headers.Single().Blocks[0]).Trim());
+ Assert.Single(((HParagraph)first.Headers[0].Blocks[0]).Inlines.OfType<HField>(), f => f.Kind == HFieldKind.PageNumber);
+ Assert.Equal([HFieldKind.PageNumber, HFieldKind.TotalPages], ((HParagraph)first.Footers.Single().Blocks[0]).Inlines.OfType<HField>().Select(f => f.Kind));
+ Assert.Equal(new HTabStop(45000, HTabKind.Right, "DOT"), ((HParagraph)first.Headers[0].Blocks[0]).Format.Tabs!.Single());
+ Assert.Equal(2, copy.Sections.Count);
+ var second = copy.Sections[1].Blocks.OfType<HParagraph>().ToList();
+ Assert.Equal(new HColumns(2, 3600, true), second.Single(p => TextOf(p) == "두 단 왼쪽").ColumnsChange);
+ Assert.Equal(HColumns.Single, second.Single(p => TextOf(p) == "앞 쪽").ColumnsChange);
+
+ // Paragraph and character formatting.
+ var originalParagraphs = Paragraphs(original.Sections.SelectMany(s => s.Blocks)).ToList();
+ var paragraphs = Paragraphs(copy.Sections.SelectMany(s => s.Blocks)).ToList();
+ HParagraph Find(List<HParagraph> list, string text) => list.First(p => TextOf(p).Contains(text, StringComparison.Ordinal));
+ foreach (var text in new[] { "큰 제목", "굵은 빨강", "첫 항목", "본문", "다음 쪽" })
+ {
+ var (a, b) = (Find(originalParagraphs, text), Find(paragraphs, text));
+ Assert.Equal(a.Format, b.Format);
+ Assert.Equal(a.HeadingLevel, b.HeadingLevel);
+ Assert.Equal(a.PageBreakBefore, b.PageBreakBefore);
+ }
+ var formatted = Find(paragraphs, "굵은 빨강");
+ Assert.Equal((HAlign.Justify, 3600, -1800), (formatted.Format.Align, formatted.Format.Left, formatted.Format.FirstLine));
+ Assert.Equal(new HLineSpacing(HLineSpacingKind.Fixed, 1600), formatted.Format.LineSpacing);
+ var runs = formatted.Inlines.OfType<HText>().ToList();
+ Assert.Equal(Find(originalParagraphs, "굵은 빨강").Inlines.OfType<HText>().Select(t => t.Format), runs.Select(t => t.Format));
+ Assert.Equal(new HCharFormat(true, false, false, false, false, false, 1400, "Arial", "굴림", "#FF0000", null, 7), runs[0].Format);
+ Assert.Equal("#FFFF00", runs.Single(r => r.Text.Contains("형광펜")).Format.Shade);
+ Assert.Equal("#DDEEFF", runs.Single(r => r.Text.Contains("음영")).Format.Shade);
+ Assert.True(runs.Single(r => r.Text.Contains("위첨자")).Format.Superscript);
+ Assert.True(Find(paragraphs, "다음 쪽").PageBreakBefore);
+
+ // Lists keep their number formats, start and level.
+ var item = Find(paragraphs, "하위 항목").List!;
+ Assert.Equal((1, "HANGUL_SYLLABLE", "^2)"), (item.Level, item.Numbering.Levels[1].Format, item.Numbering.Levels[1].Text));
+ Assert.Equal(3, item.Numbering.Levels[0].Start);
+
+ // Links, bookmarks and notes.
+ var body = Find(paragraphs, "본문");
+ Assert.Equal(["https://example.com/?q=1", "#intro"], body.Inlines.OfType<HLink>().Select(l => l.Target));
+ Assert.Equal("intro", Find(paragraphs, "큰 제목").Inlines.OfType<HBookmark>().Single().Name);
+ Assert.Equal("각주 설명", TextOf((HParagraph)body.Inlines.OfType<HNote>().Single().Blocks[0]).Trim());
+
+ // Tables: merged cells, borders, shading, header row, alignment.
+ var (tableA, tableB) = (original.Sections[0].Blocks.OfType<HTable>().Single(), first.Blocks.OfType<HTable>().Single());
+ Assert.Equal(tableA.ColumnWidths, tableB.ColumnWidths);
+ Assert.Equal(HAlign.Center, tableB.Align);
+ Assert.True(tableB.Rows[0].Header);
+ for (var r = 0; r < tableA.Rows.Count; r++)
+ {
+ Assert.Equal(tableA.Rows[r].Cells.Count, tableB.Rows[r].Cells.Count);
+ for (var c = 0; c < tableA.Rows[r].Cells.Count; c++)
+ {
+ var (x, y) = (tableA.Rows[r].Cells[c], tableB.Rows[r].Cells[c]);
+ Assert.Equal((x.Column, x.RowSpan, x.ColSpan, x.Fill, x.VerticalAlign), (y.Column, y.RowSpan, y.ColSpan, y.Fill, y.VerticalAlign));
+ Assert.Equal(x.Borders?.Bottom.Style, y.Borders?.Bottom.Style);
+ Assert.Equal(x.Borders?.Bottom.Color, y.Borders?.Bottom.Color);
+ }
+ }
+
+ // Pictures (inline and floating) and the text box keep size and position.
+ var objects = first.Blocks.OfType<HParagraph>().SelectMany(p => p.Inlines).ToList();
+ var pictures = objects.OfType<HImage>().ToList();
+ Assert.Equal(2, pictures.Count);
+ Assert.Null(pictures[0].Anchor);
+ Assert.Equal((3600, 3600), (pictures[0].Width, pictures[0].Height));
+ Assert.Equal(new HAnchor("PAPER", "LEFT", 7200, "PARA", "TOP", 1000, "SQUARE", true), pictures[1].Anchor);
+ var box = objects.OfType<HTextBox>().Single();
+ Assert.Equal((14400, 7200, "#FFF2CC", HVerticalAlign.Center), (box.Width, box.Height, box.Fill, box.VerticalAlign));
+ Assert.Equal(("PAGE", "CENTER", "PAPER", 28346, "TOP_AND_BOTTOM"), (box.Anchor!.HorizontalRelativeTo, box.Anchor.HorizontalAlign, box.Anchor.VerticalRelativeTo, box.Anchor.VerticalOffset, box.Anchor.Wrap));
+ Assert.Equal(("#C00000", HBorderStyle.Solid), (box.Line.Color, box.Line.Style));
+ Assert.Equal("글상자 안의 글", TextOf((HParagraph)box.Blocks[0]));
+
+ if (await ConvertibleByLibreOfficeAsync(fx, written) is { } pages)
+ Assert.True(pages >= 3);
+ }
+}
diff --git a/tests/Filee.Engines.Tests/EmlTests.cs b/tests/Filee.Engines.Tests/EmlTests.cs
new file mode 100644
index 00000000..5a4714fd
--- /dev/null
+++ b/tests/Filee.Engines.Tests/EmlTests.cs
@@ -0,0 +1,168 @@
+// E-mail (.eml) → HTML / TXT / ZIP of the attachments with MimeKit: Korean charsets (EUC-KR, ISO-2022-KR) in headers
+// and bodies, quoted-printable and base64, the HTML part with an inline picture ("cid:") and attachments with
+// RFC 2231 file names. Messages are written in the test.
+
+using System.IO.Compression;
+using System.Text;
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using ImageMagick;
+
+namespace Filee.Engines.Tests;
+
+public class EmlTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ static EmlTests() => Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
+
+ private static readonly byte[] Report = Encoding.ASCII.GetBytes("%PDF-1.4 fake report");
+
+ private static string EncodedWord(string text, string charset) =>
+ $"=?{charset}?B?{Convert.ToBase64String(Encoding.GetEncoding(charset).GetBytes(text))}?=";
+
+ private static string Base64Lines(byte[] bytes) =>
+ string.Join("\r\n", Convert.ToBase64String(bytes).Chunk(76).Select(c => new string(c)));
+
+ /// <summary>Quoted-printable of EUC-KR text (every non-ASCII byte as =XX).</summary>
+ private static string QuotedPrintable(string text, string charset)
+ {
+ var sb = new StringBuilder();
+ var column = 0;
+ foreach (var b in Encoding.GetEncoding(charset).GetBytes(text))
+ {
+ var piece = b is >= 33 and <= 126 and not (byte)'=' ? ((char)b).ToString() : $"={b:X2}";
+ if (column + piece.Length > 72)
+ {
+ sb.Append("=\r\n");
+ column = 0;
+ }
+ sb.Append(piece);
+ column += piece.Length;
+ }
+ return sb.ToString();
+ }
+
+ /// <summary>
+ /// multipart/mixed: multipart/related (multipart/alternative text + HTML in EUC-KR, an inline PNG) and two
+ /// attachments, one with an RFC 2231 UTF-8 file name.
+ /// </summary>
+ private async Task<string> MessageAsync()
+ {
+ using var logo = new MagickImage(MagickColors.Teal, 16, 16);
+ var png = logo.ToByteArray(MagickFormat.Png);
+ const string Html = "<html><head><style>p { color: #C00000; }</style></head><body><p>안녕하세요. 자료를 보냅니다.</p>" +
+ "<img src=\"cid:logo@filee\" alt=\"logo\"><script>alert('x')</script></body></html>";
+ var eml = string.Join("\r\n",
+ $"From: {EncodedWord("보낸이", "EUC-KR")} <[email protected]>",
+ "To: [email protected], \"Second\" <[email protected]>",
+ $"Subject: {EncodedWord("회의 자료", "EUC-KR")}",
+ "Date: Thu, 01 Oct 2026 09:30:00 +0900",
+ "MIME-Version: 1.0",
+ "Content-Type: multipart/mixed; boundary=\"mixed\"",
+ "",
+ "--mixed",
+ "Content-Type: multipart/related; boundary=\"related\"",
+ "",
+ "--related",
+ "Content-Type: multipart/alternative; boundary=\"alt\"",
+ "",
+ "--alt",
+ "Content-Type: text/plain; charset=euc-kr",
+ "Content-Transfer-Encoding: base64",
+ "",
+ Base64Lines(Encoding.GetEncoding("EUC-KR").GetBytes("안녕하세요. 자료를 보냅니다.\r\n둘째 줄")),
+ "--alt",
+ "Content-Type: text/html; charset=euc-kr",
+ "Content-Transfer-Encoding: quoted-printable",
+ "",
+ QuotedPrintable(Html, "EUC-KR"),
+ "--alt--",
+ "--related",
+ "Content-Type: image/png",
+ "Content-ID: <logo@filee>",
+ "Content-Transfer-Encoding: base64",
+ "",
+ Base64Lines(png),
+ "--related--",
+ "--mixed",
+ "Content-Type: application/pdf; name=\"report.pdf\"",
+ "Content-Disposition: attachment; filename*=UTF-8''%EB%B3%B4%EA%B3%A0%EC%84%9C.pdf",
+ "Content-Transfer-Encoding: base64",
+ "",
+ Base64Lines(Report),
+ "--mixed",
+ "Content-Type: text/plain; charset=utf-8; name=\"notes.txt\"",
+ "Content-Disposition: attachment; filename=\"notes.txt\"",
+ "",
+ "memo",
+ "--mixed--",
+ "");
+ var path = Path.Combine(fx.NewFolder(), "회의.eml");
+ await File.WriteAllTextAsync(path, eml, Encoding.ASCII, TestContext.Current.CancellationToken);
+ return path;
+ }
+
+ private async Task<string> ConvertAsync(string input, string target)
+ {
+ var job = await fx.ConvertAsync([input], new Preset { TargetFormat = target });
+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+ return job.Outputs.Single();
+ }
+
+ [Fact]
+ public async Task Eml_to_html_shows_headers_and_the_html_body_with_inline_pictures()
+ {
+ var html = await File.ReadAllTextAsync(await ConvertAsync(await MessageAsync(), "html"), TestContext.Current.CancellationToken);
+
+ Assert.Contains("<meta charset=\"utf-8\">", html);
+ Assert.Contains("<title>회의 자료</title>", html);
+ Assert.Contains("<th>From</th><td>보낸이 &lt;[email protected]&gt;</td>", html);
+ Assert.Contains("<th>To</th><td>[email protected], Second &lt;[email protected]&gt;</td>", html);
+ Assert.Contains("<th>Date</th><td>2026-10-01 09:30:00 +09:00</td>", html);
+ Assert.Contains("<th>Attachments</th><td>보고서.pdf, notes.txt</td>", html);
+ Assert.Contains("<p>안녕하세요. 자료를 보냅니다.</p>", html);
+ Assert.Contains("p { color: #C00000; }", html); // the message's own style sheet
+ Assert.Contains("src=\"data:image/png;base64,", html);
+ Assert.DoesNotContain("cid:", html);
+ Assert.DoesNotContain("<script", html);
+ }
+
+ [Fact]
+ public async Task Eml_to_text_and_attachments_to_zip()
+ {
+ var eml = await MessageAsync();
+
+ var text = await File.ReadAllTextAsync(await ConvertAsync(eml, "txt"), TestContext.Current.CancellationToken);
+ Assert.StartsWith("From: 보낸이 <[email protected]>\r\n", text.TrimStart(''));
+ Assert.Contains("Subject: 회의 자료\r\n", text);
+ Assert.EndsWith("\r\n\r\n안녕하세요. 자료를 보냅니다.\r\n둘째 줄\r\n", text);
+
+ using var zip = ZipFile.OpenRead(await ConvertAsync(eml, "zip"));
+ Assert.Equal(["보고서.pdf", "notes.txt"], zip.Entries.Select(e => e.FullName));
+ using var report = new MemoryStream();
+ using (var stream = zip.GetEntry("보고서.pdf")!.Open())
+ stream.CopyTo(report);
+ Assert.Equal(Report, report.ToArray());
+ }
+
+ [Fact]
+ public async Task Iso_2022_kr_and_plain_text_messages()
+ {
+ var subject = EncodedWord("한글 제목", "ISO-2022-KR");
+ var body = Encoding.ASCII.GetString(Encoding.GetEncoding("ISO-2022-KR").GetBytes("본문 <첫 줄>\r\n둘째 줄"));
+ var path = Path.Combine(fx.NewFolder(), "old.eml");
+ await File.WriteAllTextAsync(path,
+ $"From: [email protected]\r\nSubject: {subject}\r\nContent-Type: text/plain; charset=ISO-2022-KR\r\nContent-Transfer-Encoding: 7bit\r\n\r\n{body}\r\n",
+ Encoding.ASCII, TestContext.Current.CancellationToken);
+
+ var html = await File.ReadAllTextAsync(await ConvertAsync(path, "html"), TestContext.Current.CancellationToken);
+ Assert.Contains("<title>한글 제목</title>", html);
+ Assert.Contains("<pre class=\"filee-mail-text\">본문 &lt;첫 줄&gt;\r\n둘째 줄", html);
+ Assert.DoesNotContain("Attachments", html);
+
+ // No attachments: a clear error instead of an empty ZIP.
+ var job = await fx.ConvertAsync([path], new Preset { TargetFormat = "zip" });
+ Assert.Equal(JobState.Failed, job.State);
+ Assert.Contains("no attachments", job.Files.Single().ErrorDetail, StringComparison.OrdinalIgnoreCase);
+ }
+}
diff --git a/tests/Filee.Engines.Tests/Filee.Engines.Tests.csproj b/tests/Filee.Engines.Tests/Filee.Engines.Tests.csproj
index 348333fd..d981e220 100644
--- a/tests/Filee.Engines.Tests/Filee.Engines.Tests.csproj
+++ b/tests/Filee.Engines.Tests/Filee.Engines.Tests.csproj
@@ -13,6 +13,7 @@
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit.v3" />
<PackageReference Include="xunit.runner.visualstudio" />
+ <PackageReference Include="DocumentFormat.OpenXml" />
</ItemGroup>
<ItemGroup>
diff --git a/tests/Filee.Engines.Tests/HwpxAssert.cs b/tests/Filee.Engines.Tests/HwpxAssert.cs
index 28f3af47..e1927fa0 100644
--- a/tests/Filee.Engines.Tests/HwpxAssert.cs
+++ b/tests/Filee.Engines.Tests/HwpxAssert.cs
@@ -144,9 +144,9 @@ internal static class HwpxAssert
}
}
- private static readonly SemaphoreSlim LibreOfficeGate = new(1, 1);
+ internal static readonly SemaphoreSlim LibreOfficeGate = new(1, 1);
- private sealed class FixedPath(string path) : IOutputAllocator
+ internal sealed class FixedPath(string path) : IOutputAllocator
{
public string? Allocate(string extension, string? suffix = null) => path;
}
diff --git a/tests/Filee.Engines.Tests/LibreOfficeFormatTests.cs b/tests/Filee.Engines.Tests/LibreOfficeFormatTests.cs
new file mode 100644
index 00000000..c2c39ba7
--- /dev/null
+++ b/tests/Filee.Engines.Tests/LibreOfficeFormatTests.cs
@@ -0,0 +1,121 @@
+// Formats only LibreOffice reads (Works / WPS, WordPerfect, AbiWord, Apple iWork, StarOffice, Publisher, CorelDRAW,
+// Visio, CGM, ODG): the --convert-to filter of every edge must match the application that opens the source, and
+// sample files (AbiWord, ODG written in the test) convert when LibreOffice is installed.
+
+using System.IO.Compression;
+using System.Text;
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Filee.Engines.Office;
+using ImageMagick;
+using UglyToad.PdfPig;
+
+namespace Filee.Engines.Tests;
+
+public class LibreOfficeFormatTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ private IConverter LibreOffice => fx.Converters.Single(c => c.Id == "libreoffice");
+
+ private void SkipUnlessInstalled() =>
+ Assert.SkipUnless(fx.Catalog.StatusOf(LibreOffice).IsAvailable, "LibreOffice not installed");
+
+ [Theory]
+ [InlineData("wpd", "pdf", null, "pdf:writer_pdf_Export")]
+ [InlineData("pages", "docx", null, "docx:MS Word 2007 XML")]
+ [InlineData("abw", "odt", null, "odt")]
+ [InlineData("wps", "txt", null, "txt:Text (encoded):UTF8")]
+ [InlineData("numbers", "xlsx", null, "xlsx:Calc MS Excel 2007 XML")]
+ [InlineData("sdc", "csv", null, "csv:Text - txt - csv (StarCalc):44,34,76")]
+ [InlineData("et", "pdf", null, "pdf:calc_pdf_Export")]
+ [InlineData("key", "pptx", null, "pptx:Impress MS PowerPoint 2007 XML")]
+ [InlineData("dps", "odp", null, "odp")]
+ [InlineData("sda", "pdf", "sdd", "pdf:impress_pdf_Export")]
+ [InlineData("sda", "pdf", "sda", "pdf:draw_pdf_Export")]
+ [InlineData("cdr", "pdf", null, "pdf:draw_pdf_Export")]
+ [InlineData("vsd", "svg", null, "svg:draw_svg_Export")]
+ [InlineData("pub", "png", null, "png:draw_png_Export")]
+ [InlineData("odg", "odg", null, "odg:draw8")]
+ [InlineData("cgm", "odg", null, "odg:impress8_draw")]
+ [InlineData("cgm", "svg", null, "svg:impress_svg_Export")]
+ public void Filters_follow_the_application_that_opens_the_file(string from, string to, string? extension, string expected) =>
+ Assert.Equal(expected, LibreOfficeConverter.FilterFor(from, to, pdfA: false, extension));
+
+ [Fact]
+ public void Every_edge_has_a_filter_of_its_application()
+ {
+ string[] draw = ["pub", "cdr", "vsd", "odg"];
+ string[] impress = ["pptx", "ppt", "odp", "key", "dps", "sda", "cgm"];
+ string[] calc = ["xlsx", "xls", "ods", "csv", "et", "numbers", "sdc"];
+ foreach (var edge in LibreOffice.Edges)
+ {
+ var filter = LibreOfficeConverter.FilterFor(edge.From, edge.To, pdfA: false);
+ var application = draw.Contains(edge.From) ? "draw" : impress.Contains(edge.From) ? "impress" : calc.Contains(edge.From) ? "calc" : "writer";
+ if (edge.To is "pdf" or "svg" or "png")
+ Assert.Equal($"{edge.To}:{application}_{edge.To}_Export", filter);
+ else if (edge.To is not ("odt" or "ods" or "odp"))
+ Assert.Contains(':', filter);
+ }
+ // Built-in engines stay first: LibreOffice's edges cost more than a normal direct conversion.
+ Assert.All(LibreOffice.Edges, e => Assert.True(e.Cost >= 25));
+ foreach (var from in new[] { "dot", "wps", "wpd", "lwp", "abw", "pages", "sdw", "et", "numbers", "sdc", "key", "dps", "sda", "pub", "cdr", "cgm", "vsd", "odg" })
+ Assert.Contains(LibreOffice.Edges, e => e.From == from && e.To == "pdf");
+ }
+
+ [Fact]
+ public async Task AbiWord_to_pdf_and_docx()
+ {
+ SkipUnlessInstalled();
+ var abw = Path.Combine(fx.NewFolder(), "note.abw");
+ await File.WriteAllTextAsync(abw, """
+ <?xml version="1.0" encoding="UTF-8"?>
+ <!DOCTYPE abiword PUBLIC "-//ABISOURCE//DTD AWML 1.0 Strict//EN" "http://www.abisource.com/awml.dtd">
+ <abiword template="false" xmlns="http://www.abisource.com/awml.dtd" version="3.0.4" fileformat="1.1">
+ <section><p>Hello AbiWord</p><p>Second paragraph</p></section>
+ </abiword>
+ """, TestContext.Current.CancellationToken);
+
+ var pdf = await ConvertAsync(abw, "pdf");
+ using (var document = PdfDocument.Open(pdf))
+ Assert.Contains("Hello AbiWord", string.Concat(document.GetPages().Select(p => p.Text)));
+ var docx = await ConvertAsync(abw, "docx");
+ Assert.Contains("Second paragraph", string.Concat(DocxAssert.Paragraphs(DocxAssert.ReadBack(docx).Sections.SelectMany(s => s.Blocks)).Select(DocxAssert.TextOf)));
+ }
+
+ [Fact]
+ public async Task Drawing_to_svg_png_and_pdf()
+ {
+ SkipUnlessInstalled();
+ var odg = Path.Combine(fx.NewFolder(), "drawing.odg");
+ using (var zip = ZipFile.Open(odg, ZipArchiveMode.Create))
+ {
+ void Write(string name, string text, CompressionLevel level = CompressionLevel.Optimal)
+ {
+ using var stream = zip.CreateEntry(name, level).Open();
+ stream.Write(Encoding.UTF8.GetBytes(text));
+ }
+ Write("mimetype", "application/vnd.oasis.opendocument.graphics", CompressionLevel.NoCompression);
+ Write("META-INF/manifest.xml",
+ "<manifest:manifest xmlns:manifest=\"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0\" manifest:version=\"1.2\">" +
+ "<manifest:file-entry manifest:full-path=\"/\" manifest:version=\"1.2\" manifest:media-type=\"application/vnd.oasis.opendocument.graphics\"/>" +
+ "<manifest:file-entry manifest:full-path=\"content.xml\" manifest:media-type=\"text/xml\"/></manifest:manifest>");
+ Write("content.xml",
+ "<office:document-content xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\" xmlns:draw=\"urn:oasis:names:tc:opendocument:xmlns:drawing:1.0\" " +
+ "xmlns:svg=\"urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0\" xmlns:text=\"urn:oasis:names:tc:opendocument:xmlns:text:1.0\" office:version=\"1.2\">" +
+ "<office:body><office:drawing><draw:page draw:name=\"page1\"><draw:rect svg:x=\"2cm\" svg:y=\"2cm\" svg:width=\"8cm\" svg:height=\"4cm\"><text:p>Filee drawing</text:p></draw:rect>" +
+ "</draw:page></office:drawing></office:body></office:document-content>");
+ }
+
+ Assert.Contains("<svg", await File.ReadAllTextAsync(await ConvertAsync(odg, "svg"), TestContext.Current.CancellationToken));
+ var png = new MagickImageInfo(await ConvertAsync(odg, "png"));
+ Assert.True(png.Width > 100);
+ using var pdf = PdfDocument.Open(await ConvertAsync(odg, "pdf"));
+ Assert.Contains("Filee drawing", pdf.GetPage(1).Text);
+ }
+
+ private async Task<string> ConvertAsync(string input, string target)
+ {
+ var job = await fx.ConvertAsync([input], new Preset { TargetFormat = target });
+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+ return job.Outputs.Single();
+ }
+}
diff --git a/tests/Filee.Engines.Tests/OoxmlVariantTests.cs b/tests/Filee.Engines.Tests/OoxmlVariantTests.cs
new file mode 100644
index 00000000..862b48b5
--- /dev/null
+++ b/tests/Filee.Engines.Tests/OoxmlVariantTests.cs
@@ -0,0 +1,226 @@
+// Office Open XML variants (macro-enabled files, templates, slide shows) without Office: the package is copied with
+// the main part's content type rewritten, and macros are dropped when the target may not hold them. The built-in
+// readers accept the variants directly (DOCM → HWPX, XLSM → CSV, PPSX → DOCX ...).
+
+using System.IO.Compression;
+using System.Xml.Linq;
+using DocumentFormat.OpenXml;
+using DocumentFormat.OpenXml.Packaging;
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Filee.Engines.Office;
+using Filee.Engines.Office.Sheets;
+using static Filee.Engines.Tests.DocxBuilder;
+
+namespace Filee.Engines.Tests;
+
+public class OoxmlVariantTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ private static readonly XNamespace Types = "http://schemas.openxmlformats.org/package/2006/content-types";
+ private static readonly XNamespace Rels = "http://schemas.openxmlformats.org/package/2006/relationships";
+ private const string VbaRelationship = "http://schemas.microsoft.com/office/2006/relationships/vbaProject";
+
+ private async Task<string> ConvertAsync(string input, string target)
+ {
+ var job = await fx.ConvertAsync([input], new Preset { TargetFormat = target });
+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+ return job.Outputs.Single();
+ }
+
+ /// <summary>
+ /// Turns a macro-free package into the macro-enabled variant <paramref name="format"/>: main content type, a VBA
+ /// project (with its data part, as Word keeps it) related from the main part, and for Excel an Excel 4.0 macro sheet.
+ /// </summary>
+ private static string AddMacros(string package, string format, string folder)
+ {
+ var path = Path.ChangeExtension(package, "." + format);
+ File.Copy(package, path, overwrite: true);
+ using var zip = ZipFile.Open(path, ZipArchiveMode.Update);
+ var main = XDocument.Load(zip.GetEntry("_rels/.rels")!.Open()).Root!.Elements(Rels + "Relationship")
+ .Single(r => ((string)r.Attribute("Type")!).EndsWith("/officeDocument", StringComparison.Ordinal)).Attribute("Target")!.Value.TrimStart('/');
+ var mainFolder = main[..main.LastIndexOf('/')];
+ var relsPath = $"{mainFolder}/_rels/{Path.GetFileName(main)}.rels";
+
+ var types = Load(zip, "[Content_Types].xml");
+ types.Root!.Elements(Types + "Override").Single(o => (string)o.Attribute("PartName")! == "/" + main)
+ .SetAttributeValue("ContentType", OoxmlConverter.Variants[format].ContentType);
+ types.Root.AddFirst(new XElement(Types + "Default", new XAttribute("Extension", "bin"), new XAttribute("ContentType", "application/vnd.ms-office.vbaProject")));
+ types.Root.Add(new XElement(Types + "Override", new XAttribute("PartName", $"/{mainFolder}/vbaData.xml"), new XAttribute("ContentType", "application/vnd.ms-word.vbaData+xml")));
+
+ var rels = zip.GetEntry(relsPath) is { } existing ? Load(zip, relsPath) : new XDocument(new XElement(Rels + "Relationships"));
+ rels.Root!.Add(new XElement(Rels + "Relationship", new XAttribute("Id", "rIdVba"), new XAttribute("Type", VbaRelationship), new XAttribute("Target", "vbaProject.bin")));
+ Write(zip, $"{mainFolder}/vbaProject.bin", [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]);
+ Write(zip, $"{mainFolder}/_rels/vbaProject.bin.rels",
+ "<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\"><Relationship Id=\"rId1\" Type=\"http://schemas.microsoft.com/office/2006/relationships/wordVbaData\" Target=\"vbaData.xml\"/></Relationships>"u8.ToArray());
+ Write(zip, $"{mainFolder}/vbaData.xml", "<wne:vbaSuppData xmlns:wne=\"http://schemas.microsoft.com/office/word/2006/wordml\"/>"u8.ToArray());
+
+ if (format == "xlsm")
+ {
+ // An Excel 4.0 macro sheet, listed in the workbook like a sheet.
+ types.Root.Add(new XElement(Types + "Override", new XAttribute("PartName", "/xl/macrosheets/sheet1.xml"), new XAttribute("ContentType", "application/vnd.ms-excel.macrosheet+xml")));
+ rels.Root.Add(new XElement(Rels + "Relationship", new XAttribute("Id", "rIdMacro"), new XAttribute("Type", "http://schemas.microsoft.com/office/2006/relationships/xlMacrosheet"), new XAttribute("Target", "macrosheets/sheet1.xml")));
+ Write(zip, "xl/macrosheets/sheet1.xml", "<xm:macrosheet xmlns:xm=\"http://schemas.microsoft.com/office/excel/2006/main\"/>"u8.ToArray());
+ var workbook = Load(zip, "xl/workbook.xml");
+ XNamespace s = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
+ XNamespace r = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
+ workbook.Root!.Element(s + "sheets")!.Add(new XElement(s + "sheet", new XAttribute("name", "Macro1"), new XAttribute("sheetId", 99), new XAttribute(r + "id", "rIdMacro")));
+ Save(zip, "xl/workbook.xml", workbook);
+ }
+ Save(zip, "[Content_Types].xml", types);
+ Save(zip, relsPath, rels);
+ return path;
+ }
+
+ private static XDocument Load(ZipArchive zip, string name)
+ {
+ using var stream = zip.GetEntry(name)!.Open();
+ return XDocument.Load(stream);
+ }
+
+ private static void Save(ZipArchive zip, string name, XDocument xml)
+ {
+ zip.GetEntry(name)?.Delete();
+ using var stream = zip.CreateEntry(name).Open();
+ xml.Save(stream);
+ }
+
+ private static void Write(ZipArchive zip, string name, byte[] bytes)
+ {
+ using var stream = zip.CreateEntry(name).Open();
+ stream.Write(bytes);
+ }
+
+ /// <summary>No macro part, no content type or relationship pointing to one.</summary>
+ private static void AssertNoMacros(string path)
+ {
+ using var zip = ZipFile.OpenRead(path);
+ Assert.DoesNotContain(zip.Entries, e => e.Name is "vbaProject.bin" or "vbaData.xml" or "vbaProject.bin.rels" || e.FullName.Contains("macrosheets", StringComparison.Ordinal));
+ var types = Load(zip, "[Content_Types].xml").ToString();
+ Assert.DoesNotContain("vbaProject", types);
+ Assert.DoesNotContain("macrosheet", types);
+ foreach (var rels in zip.Entries.Where(e => e.FullName.EndsWith(".rels", StringComparison.Ordinal)))
+ Assert.DoesNotContain(Load(zip, rels.FullName).Root!.Elements(Rels + "Relationship"), r => ((string)r.Attribute("Type")!).StartsWith("http://schemas.microsoft.com/office/2006/relationships/", StringComparison.Ordinal) && ((string)r.Attribute("Type")!).Contains("Macro", StringComparison.OrdinalIgnoreCase) || (string)r.Attribute("Type")! == VbaRelationship);
+ }
+
+ private static string MainContentType(string path)
+ {
+ using var zip = ZipFile.OpenRead(path);
+ var main = XDocument.Load(zip.GetEntry("_rels/.rels")!.Open()).Root!.Elements(Rels + "Relationship")
+ .Single(r => ((string)r.Attribute("Type")!).EndsWith("/officeDocument", StringComparison.Ordinal)).Attribute("Target")!.Value.TrimStart('/');
+ return (string)Load(zip, "[Content_Types].xml").Root!.Elements(Types + "Override").Single(o => (string)o.Attribute("PartName")! == "/" + main).Attribute("ContentType")!;
+ }
+
+ [Fact]
+ public void Variants_are_converted_by_the_ooxml_engine_and_read_directly()
+ {
+ var planner = fx.Catalog.CreatePlanner();
+ foreach (var (from, to) in new[] { ("docm", "docx"), ("dotx", "docx"), ("docx", "dotm"), ("xlsm", "xlsx"), ("xlsx", "xltx"), ("pptm", "pptx"), ("potx", "pptx"), ("ppsx", "pptx"), ("pptx", "ppsx") })
+ Assert.Equal("ooxml", Assert.Single(planner.Plan(from, to)!.Steps).Converter.Id);
+ // Families never mix.
+ Assert.DoesNotContain(fx.Converters.Single(c => c.Id == "ooxml").Edges, e => OoxmlConverter.Variants[e.From].Family != OoxmlConverter.Variants[e.To].Family);
+ foreach (var from in new[] { "docm", "dotx", "dotm", "xlsm", "xltx", "pptm", "potx", "ppsx" })
+ Assert.Equal("hwpx-writer", Assert.Single(planner.Plan(from, "hwpx")!.Steps).Converter.Id);
+ Assert.Equal("spreadsheet", Assert.Single(planner.Plan("xlsm", "csv")!.Steps).Converter.Id);
+ Assert.Equal("spreadsheet", Assert.Single(planner.Plan("xltx", "csv")!.Steps).Converter.Id);
+ }
+
+ [Fact]
+ public async Task Docm_to_docx_drops_the_macros_and_keeps_the_document()
+ {
+ var dir = fx.NewFolder();
+ var docx = new DocxBuilder().Paragraph(P(R("매크로가 있던 문서"))).Save(Path.Combine(dir, "보고.docx"));
+ var docm = AddMacros(docx, "docm", dir);
+ File.Delete(docx);
+
+ var converted = await ConvertAsync(docm, "docx");
+
+ Assert.Equal(".docx", Path.GetExtension(converted));
+ Assert.Equal(OoxmlConverter.Variants["docx"].ContentType, MainContentType(converted));
+ AssertNoMacros(converted);
+ using (var document = WordprocessingDocument.Open(converted, false))
+ Assert.Equal(WordprocessingDocumentType.Document, document.DocumentType);
+ Assert.Equal("매크로가 있던 문서", DocxAssert.TextOf((Hwp.Hwpx.HParagraph)DocxAssert.ReadBack(converted).Sections[0].Blocks[0]));
+
+ // Macro-enabled to macro-enabled keeps them; the readers take the variant directly.
+ var dotm = await ConvertAsync(docm, "dotm");
+ Assert.Equal(OoxmlConverter.Variants["dotm"].ContentType, MainContentType(dotm));
+ using (var zip = ZipFile.OpenRead(dotm))
+ Assert.NotNull(zip.GetEntry("word/vbaProject.bin"));
+ HwpxAssert.ValidPackage(await ConvertAsync(docm, "hwpx"));
+ }
+
+ [Fact]
+ public async Task Templates_and_documents_turn_into_each_other()
+ {
+ var dir = fx.NewFolder();
+ var docx = new DocxBuilder().Paragraph(P(R("서식 파일"))).Save(Path.Combine(dir, "서식.docx"));
+
+ var dotx = await ConvertAsync(docx, "dotx");
+ using (var template = WordprocessingDocument.Open(dotx, false))
+ Assert.Equal(WordprocessingDocumentType.Template, template.DocumentType);
+ File.Delete(docx);
+ var back = await ConvertAsync(dotx, "docx");
+ Assert.Equal(OoxmlConverter.Variants["docx"].ContentType, MainContentType(back));
+ DocxAssert.ValidPackage(back);
+ }
+
+ [Fact]
+ public async Task Xlsm_to_xlsx_removes_vba_and_macro_sheets()
+ {
+ var dir = fx.NewFolder();
+ var builder = new XlsxBuilder();
+ builder.Sheet("매출", XlsxBuilder.Row(1, builder.Text("A1", "지점"), XlsxBuilder.Number("B1", 42)));
+ var xlsx = builder.Save(Path.Combine(dir, "매출.xlsx"));
+ var xlsm = AddMacros(xlsx, "xlsm", dir);
+ File.Delete(xlsx);
+
+ var converted = await ConvertAsync(xlsm, "xlsx");
+
+ AssertNoMacros(converted);
+ using (var workbook = SpreadsheetDocument.Open(converted, false))
+ {
+ Assert.Equal(SpreadsheetDocumentType.Workbook, workbook.DocumentType);
+ Assert.Equal(["매출"], workbook.WorkbookPart!.Workbook!.Sheets!.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Select(s => s.Name!.Value));
+ }
+ Assert.Equal("42", XlsxReader.Read(converted).Sheets.Single().Get(0, 1)!.Text);
+
+ // XLSM → CSV directly.
+ var csv = await ConvertAsync(xlsm, "csv");
+ Assert.Equal("지점,42", (await File.ReadAllTextAsync(csv, TestContext.Current.CancellationToken)).Trim('', '\r', '\n'));
+
+ var xltx = await ConvertAsync(converted, "xltx");
+ using (var template = SpreadsheetDocument.Open(xltx, false))
+ Assert.Equal(SpreadsheetDocumentType.Template, template.DocumentType);
+ }
+
+ [Fact]
+ public async Task Presentation_variants_become_pptx()
+ {
+ var dir = fx.NewFolder();
+ var pptx = new PptxBuilder();
+ pptx.Slide(pptx.Title("슬라이드 쇼"));
+ var source = pptx.Save(Path.Combine(dir, "발표.pptx"));
+ var pptm = AddMacros(source, "pptm", dir);
+ var ppsx = await ConvertAsync(source, "ppsx");
+ File.Delete(source);
+
+ var fromShow = await ConvertAsync(ppsx, "pptx");
+ using (var presentation = PresentationDocument.Open(fromShow, false))
+ Assert.Equal(PresentationDocumentType.Presentation, presentation.DocumentType);
+ using (var show = PresentationDocument.Open(ppsx, false))
+ Assert.Equal(PresentationDocumentType.Slideshow, show.DocumentType);
+
+ File.Delete(fromShow);
+ var fromMacros = await ConvertAsync(pptm, "pptx");
+ AssertNoMacros(fromMacros);
+ using (var presentation = PresentationDocument.Open(fromMacros, false))
+ {
+ Assert.Equal(PresentationDocumentType.Presentation, presentation.DocumentType);
+ var errors = new DocumentFormat.OpenXml.Validation.OpenXmlValidator(FileFormatVersions.Microsoft365).Validate(presentation, TestContext.Current.CancellationToken);
+ Assert.DoesNotContain(errors, e => e.Description.Contains("vba", StringComparison.OrdinalIgnoreCase));
+ }
+
+ var docx = await ConvertAsync(ppsx, "docx");
+ DocxAssert.ValidPackage(docx);
+ }
+}
diff --git a/tests/Filee.Engines.Tests/PandocMarkupTests.cs b/tests/Filee.Engines.Tests/PandocMarkupTests.cs
new file mode 100644
index 00000000..e989e14e
--- /dev/null
+++ b/tests/Filee.Engines.Tests/PandocMarkupTests.cs
@@ -0,0 +1,105 @@
+// reStructuredText and LaTeX through Pandoc (optional engine): to and from Markdown, HTML, DOCX, EPUB, and to HWPX
+// through Pandoc's AST and the built-in HWPX writer. Skipped when Pandoc is not installed.
+
+using System.IO.Compression;
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Filee.Engines.Hwp.Hwpx;
+
+namespace Filee.Engines.Tests;
+
+public class PandocMarkupTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ private const string Rst = """
+ Weekly notes
+ ============
+
+ Decided: **ship it** and *write docs*.
+
+ - first item
+ - second item
+
+ Next steps
+ ==========
+
+ Two sections of the same level, so the first one stays a heading (a lone one would become the title).
+ """;
+
+ private const string Tex = """
+ \documentclass{article}
+ \begin{document}
+ \section{Results}
+ The result is \textbf{good} and \emph{fast}.
+ \end{document}
+ """;
+
+ private void SkipUnlessInstalled() =>
+ Assert.SkipUnless(fx.Catalog.StatusOf(fx.Converters.Single(c => c.Id == "pandoc")).IsAvailable, "Pandoc not installed");
+
+ private async Task<string> WriteAsync(string name, string text)
+ {
+ var path = Path.Combine(fx.NewFolder(), name);
+ await File.WriteAllTextAsync(path, text, TestContext.Current.CancellationToken);
+ return path;
+ }
+
+ private async Task<string> ConvertAsync(string input, string target)
+ {
+ var job = await fx.ConvertAsync([input], new Preset { TargetFormat = target });
+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+ return job.Outputs.Single();
+ }
+
+ [Fact]
+ public void Markup_routes()
+ {
+ var planner = fx.Catalog.CreatePlanner(["pandoc"]);
+ foreach (var (from, to) in new[] { ("rst", "docx"), ("rst", "md"), ("tex", "html"), ("tex", "epub"), ("md", "rst"), ("docx", "tex") })
+ Assert.Equal("pandoc", Assert.Single(planner.Plan(from, to)!.Steps).Converter.Id);
+ Assert.Equal("hwpx-writer", Assert.Single(planner.Plan("rst", "hwpx")!.Steps).Converter.Id);
+ Assert.Equal("hwpx-writer", Assert.Single(planner.Plan("tex", "hwpx")!.Steps).Converter.Id);
+ Assert.DoesNotContain(fx.Converters.Single(c => c.Id == "pandoc").Edges, e => e.To == "pdf");
+ }
+
+ [Fact]
+ public async Task Rst_to_docx_markdown_and_hwpx()
+ {
+ SkipUnlessInstalled();
+ var rst = await WriteAsync("notes.rst", Rst);
+
+ var docx = DocxAssert.ReadBack(await ConvertAsync(rst, "docx"));
+ var paragraphs = DocxAssert.Paragraphs(docx.Sections.SelectMany(s => s.Blocks)).ToList();
+ Assert.Equal(1, paragraphs.Single(p => DocxAssert.TextOf(p) == "Weekly notes").HeadingLevel);
+
+ var md = await File.ReadAllTextAsync(await ConvertAsync(rst, "md"), TestContext.Current.CancellationToken);
+ Assert.Contains("# Weekly notes", md);
+ Assert.Contains("**ship it**", md);
+
+ var hwpx = await ConvertAsync(rst, "hwpx");
+ HwpxAssert.ValidPackage(hwpx);
+ Assert.Contains("first item", HwpxAssert.Xml(hwpx).Value);
+ }
+
+ [Fact]
+ public async Task Latex_to_markdown_epub_and_back()
+ {
+ SkipUnlessInstalled();
+ var tex = await WriteAsync("paper.tex", Tex);
+
+ var md = await File.ReadAllTextAsync(await ConvertAsync(tex, "md"), TestContext.Current.CancellationToken);
+ Assert.Contains("# Results", md);
+ Assert.Contains("**good**", md);
+
+ using (var epub = ZipFile.OpenRead(await ConvertAsync(tex, "epub")))
+ Assert.Equal("application/epub+zip", new StreamReader(epub.GetEntry("mimetype")!.Open()).ReadToEnd());
+
+ var markdown = await WriteAsync("draft.md", "# Title\n\nSome *text*.\n");
+ var latex = await File.ReadAllTextAsync(await ConvertAsync(markdown, "tex"), TestContext.Current.CancellationToken);
+ Assert.Contains("\\begin{document}", latex); // standalone, ready to compile
+ Assert.Contains("\\section{Title}", latex);
+
+ var hwpx = await ConvertAsync(tex, "hwpx");
+ HwpxAssert.ValidPackage(hwpx);
+ Assert.Contains("The result is", HwpxAssert.Xml(hwpx).Value);
+ }
+}
diff --git a/tests/Filee.Engines.Tests/PdfBuilder.cs b/tests/Filee.Engines.Tests/PdfBuilder.cs
new file mode 100644
index 00000000..5089014b
--- /dev/null
+++ b/tests/Filee.Engines.Tests/PdfBuilder.cs
@@ -0,0 +1,133 @@
+// Builds small PDF files for the PDF reader tests with PdfPig's writer: text in the standard 14 fonts (every PDF
+// reader has them, so no font file is needed and the tests run on machines without Windows fonts), wrapped
+// paragraphs, colours, pictures, links and several pages. PDFsharp adds password protection to a finished file.
+
+using ImageMagick;
+using PdfSharp.Pdf.IO;
+using UglyToad.PdfPig.Core;
+using UglyToad.PdfPig.Fonts.Standard14Fonts;
+using UglyToad.PdfPig.Writer;
+
+namespace Filee.Engines.Tests;
+
+/// <summary>A PDF written page by page; <c>y</c> coordinates are points from the top of the page.</summary>
+internal sealed class PdfBuilder
+{
+ private readonly PdfDocumentBuilder _builder = new();
+ private readonly Dictionary<Standard14Font, PdfDocumentBuilder.AddedFont> _fonts = [];
+ private PdfPageBuilder? _page;
+ private double _height;
+
+ private PdfPageBuilder Page => _page ?? throw new InvalidOperationException("Add a page first.");
+
+ /// <summary>Starts a new page (A4 by default).</summary>
+ public PdfBuilder NewPage(double width = 595, double height = 842)
+ {
+ _page = _builder.AddPage(width, height);
+ _height = height;
+ return this;
+ }
+
+ /// <summary>Helvetica in the given style (a standard font: nothing is embedded).</summary>
+ public PdfDocumentBuilder.AddedFont Font(bool bold = false, bool italic = false)
+ {
+ var standard = (bold, italic) switch
+ {
+ (true, true) => Standard14Font.HelveticaBoldOblique,
+ (true, false) => Standard14Font.HelveticaBold,
+ (false, true) => Standard14Font.HelveticaOblique,
+ _ => Standard14Font.Helvetica,
+ };
+ if (!_fonts.TryGetValue(standard, out var font))
+ _fonts[standard] = font = _builder.AddStandard14Font(standard);
+ return font;
+ }
+
+ /// <summary>A TrueType font to embed (for scripts the standard fonts lack, such as Hangul).</summary>
+ public PdfDocumentBuilder.AddedFont TrueType(byte[] font) => _builder.AddTrueTypeFont(font);
+
+ public double Width(string text, double size, PdfDocumentBuilder.AddedFont font)
+ {
+ var letters = Page.MeasureText(text, size, new PdfPoint(0, 0), font);
+ return letters.Count == 0 ? 0 : letters.Max(l => l.EndBaseLine.X) - letters.Min(l => l.StartBaseLine.X);
+ }
+
+ /// <summary>One line of text with its baseline <paramref name="y"/> points below the top of the page.</summary>
+ public PdfBuilder Line(string text, double size, PdfDocumentBuilder.AddedFont font, double x, double y, (byte R, byte G, byte B)? color = null)
+ {
+ if (color is { } c)
+ Page.SetTextAndFillColor(c.R, c.G, c.B);
+ Page.AddText(text, size, new PdfPoint(x, _height - y), font);
+ if (color is not null)
+ Page.ResetColor();
+ return this;
+ }
+
+ /// <summary>Text wrapped at word boundaries into <paramref name="width"/>; returns the baseline below the last line.</summary>
+ public double Paragraph(string text, double size, PdfDocumentBuilder.AddedFont font, double x, double y, double width, double leading, char separator = ' ')
+ {
+ var line = "";
+ foreach (var word in text.Split(separator))
+ {
+ var candidate = line.Length == 0 ? word : line + separator + word;
+ if (line.Length > 0 && Width(candidate, size, font) > width)
+ {
+ Line(line, size, font, x, y);
+ y += leading;
+ line = word;
+ }
+ else
+ {
+ line = candidate;
+ }
+ }
+ if (line.Length > 0)
+ {
+ Line(line, size, font, x, y);
+ y += leading;
+ }
+ return y;
+ }
+
+ /// <summary>A JPEG (kept as a DCT stream) or PNG picture drawn into the rectangle.</summary>
+ public PdfBuilder Picture(string path, double x, double y, double width, double height)
+ {
+ var bytes = File.ReadAllBytes(path);
+ var rect = new PdfRectangle(x, _height - y - height, x + width, _height - y);
+ if (path.EndsWith(".png", StringComparison.OrdinalIgnoreCase))
+ Page.AddPng(bytes, rect);
+ else
+ Page.AddJpeg(bytes, rect);
+ return this;
+ }
+
+ /// <summary>A web link over the rectangle.</summary>
+ public PdfBuilder Link(string url, double x, double y, double width, double height)
+ {
+ Page.AddLink(url, new PdfRectangle(x, _height - y - height, x + width, _height - y));
+ return this;
+ }
+
+ public static string Photo(string folder, string name, MagickFormat format, uint width = 200, uint height = 120)
+ {
+ using var image = new MagickImage("gradient:#FF8800-#0044AA", width, height);
+ var path = Path.Combine(folder, name);
+ image.Write(path, format);
+ return path;
+ }
+
+ public string Save(string path)
+ {
+ File.WriteAllBytes(path, _builder.Build());
+ return path;
+ }
+
+ /// <summary>Encrypts a PDF with a password needed to open it (PDFsharp, no fonts involved).</summary>
+ public static void Protect(string path, string password)
+ {
+ using var document = PdfReader.Open(path, PdfDocumentOpenMode.Modify);
+ document.SecuritySettings.UserPassword = password;
+ document.SecuritySettings.OwnerPassword = password + "-owner";
+ document.Save(path);
+ }
+}
diff --git a/tests/Filee.Engines.Tests/PdfReaderTests.cs b/tests/Filee.Engines.Tests/PdfReaderTests.cs
new file mode 100644
index 00000000..5dc94195
--- /dev/null
+++ b/tests/Filee.Engines.Tests/PdfReaderTests.cs
@@ -0,0 +1,211 @@
+// PDF → DOCX / HWPX / TXT with the built-in PDF reader (PdfPig): paragraphs in reading order (two-column pages
+// too), headings from font sizes, bold / italic / colour, links, pictures (JPEG kept as it is), repeated headers and
+// footers left out, scanned pages as page pictures, and a clear error for password-protected files.
+// The test PDFs use the standard 14 fonts, so no installed font is needed (only the Korean test embeds one, if any).
+
+using System.IO.Compression;
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Filee.Engines.Hwp.Hwpx;
+using Filee.Engines.Pdf;
+using ImageMagick;
+using static Filee.Engines.Tests.DocxAssert;
+
+namespace Filee.Engines.Tests;
+
+public class PdfReaderTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ private const string First =
+ "Filee converts files on your own computer. This paragraph is long enough to wrap over several lines, so the reader " +
+ "has to join the lines again into one paragraph without losing or doubling any of the words in it.";
+ private const string Second =
+ "The second page continues the report with more details. Headers and footers repeat on every page and are left out.";
+
+ private async Task<ConversionJob> RunAsync(string input, string target) =>
+ await fx.ConvertAsync([input], new Preset { TargetFormat = target });
+
+ private async Task<string> ConvertAsync(string input, string target)
+ {
+ var job = await RunAsync(input, target);
+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+ return job.Outputs.Single();
+ }
+
+ /// <summary>Two A4 pages: title, headings, wrapped paragraphs, coloured and italic words, a link, two pictures, and a running header and footer.</summary>
+ private static string Report(string folder)
+ {
+ var pdf = new PdfBuilder();
+ for (var page = 1; page <= 2; page++)
+ {
+ pdf.NewPage();
+ var regular = pdf.Font();
+ var bold = pdf.Font(bold: true);
+ pdf.Line("Filee Quarterly Report", 9, regular, 50, 30);
+ pdf.Line($"Page {page}", 9, regular, 280, 815);
+ if (page == 1)
+ {
+ pdf.Line("Annual Report 2026", 24, bold, 50, 90);
+ pdf.Line("1. Introduction", 16, bold, 50, 135);
+ var y = pdf.Paragraph(First, 11, regular, 50, 165, 495, 14);
+ pdf.Line("Warning", 11, bold, 50, y + 12, (255, 0, 0));
+ pdf.Line(" this line is italic", 11, pdf.Font(italic: true), 50 + pdf.Width("Warning", 11, bold), y + 12);
+ pdf.Line("Visit https://example.com", 11, regular, 50, y + 40);
+ pdf.Link("https://example.com/", 50, y + 30, 150, 14);
+ pdf.Picture(PdfBuilder.Photo(folder, "photo.jpg", MagickFormat.Jpeg), 50, y + 60, 200, 120);
+ pdf.Picture(PdfBuilder.Photo(folder, "chart.png", MagickFormat.Png, 100, 100), 300, y + 60, 100, 100);
+ }
+ else
+ {
+ pdf.Line("2. Details", 16, bold, 50, 90);
+ pdf.Paragraph(Second, 11, regular, 50, 120, 495, 14);
+ }
+ }
+ return pdf.Save(Path.Combine(folder, "report.pdf"));
+ }
+
+ [Fact]
+ public async Task Pdf_to_docx_keeps_paragraphs_headings_formatting_links_and_pictures()
+ {
+ var docx = await ConvertAsync(Report(fx.NewFolder()), "docx");
+
+ ValidPackage(docx);
+ var model = ReadBack(docx);
+ var paragraphs = Paragraphs(model.Sections.SelectMany(s => s.Blocks)).Where(p => TextOf(p).Length > 0).ToList();
+ Assert.Equal(["Annual Report 2026", "1. Introduction", First, "Warning this line is italic", "Visit https://example.com", "2. Details", Second],
+ paragraphs.Select(p => TextOf(p).Trim()));
+ // Heading levels by size: 24 pt → 1, 16 pt → 2; body text is no heading.
+ Assert.Equal([1, 2, 0, 0, 0, 2, 0], paragraphs.Select(p => p.HeadingLevel));
+
+ var warning = paragraphs[3].Inlines.OfType<HText>().ToList();
+ Assert.Equal((true, "#FF0000"), (warning[0].Format.Bold, warning[0].Format.Color));
+ Assert.True(warning[^1].Format.Italic);
+ Assert.Equal("Arial", warning[0].Format.Font); // Helvetica, as Word knows it
+ Assert.Equal((1100, "#000000"), (paragraphs[2].Inlines.OfType<HText>().First().Format.Size, paragraphs[2].Inlines.OfType<HText>().First().Format.Color));
+ Assert.Equal("https://example.com/", paragraphs[4].Inlines.OfType<HLink>().Single().Target);
+
+ // The second page starts on a new page; the running header and footer are gone.
+ Assert.True(paragraphs[5].PageBreakBefore);
+ var allText = string.Concat(Paragraphs(model.Sections.SelectMany(s => s.Blocks)).Select(TextOf));
+ Assert.DoesNotContain("Quarterly", allText);
+ Assert.DoesNotContain("Page 1", allText);
+
+ // A4 page; pictures at their size, the JPEG kept as it was.
+ Assert.Equal((59500, 84200), (model.Sections[0].Page!.Width, model.Sections[0].Page!.Height));
+ var pictures = Paragraphs(model.Sections.SelectMany(s => s.Blocks)).SelectMany(p => p.Inlines).OfType<HImage>().ToList();
+ Assert.Equal([(20000, 12000), (10000, 10000)], pictures.Select(p => (p.Width!.Value, p.Height!.Value)));
+ using (var zip = ZipFile.OpenRead(docx))
+ {
+ Assert.Single(zip.Entries, e => e.FullName.StartsWith("word/media/", StringComparison.Ordinal) && e.FullName.EndsWith(".jpg", StringComparison.Ordinal));
+ Assert.Single(zip.Entries, e => e.FullName.StartsWith("word/media/", StringComparison.Ordinal) && e.FullName.EndsWith(".png", StringComparison.Ordinal));
+ }
+ if (await ConvertibleByLibreOfficeAsync(fx, docx) is { } pages)
+ Assert.Equal(2, pages);
+ }
+
+ [Fact]
+ public async Task Two_column_pages_are_read_column_by_column()
+ {
+ var dir = fx.NewFolder();
+ var pdf = new PdfBuilder().NewPage();
+ var body = pdf.Font();
+ pdf.Line("Two Column Layout", 20, pdf.Font(bold: true), 50, 70);
+ static string Text(string label) => $"{label} paragraph of the column: it has enough words to wrap over a few lines inside its narrow column of text.";
+ var left = pdf.Paragraph(Text("Left first"), 10, body, 50, 110, 230, 13);
+ pdf.Paragraph(Text("Left second"), 10, body, 50, left + 10, 230, 13);
+ var right = pdf.Paragraph(Text("Right first"), 10, body, 315, 110, 230, 13);
+ right = pdf.Paragraph(Text("Right second"), 10, body, 315, right + 10, 230, 13);
+ pdf.Paragraph("A closing paragraph spans both columns again at the end of the page, below everything else.", 10, body, 50, right + 40, 495, 13);
+ var path = pdf.Save(Path.Combine(dir, "columns.pdf"));
+
+ var txt = await ConvertAsync(path, "txt");
+
+ var text = await File.ReadAllTextAsync(txt, TestContext.Current.CancellationToken);
+ var order = new[] { "Two Column Layout", "Left first", "Left second", "Right first", "Right second", "A closing paragraph" }
+ .Select(s => text.IndexOf(s, StringComparison.Ordinal)).ToList();
+ Assert.All(order, index => Assert.True(index >= 0, text));
+ Assert.Equal(order.OrderBy(i => i), order);
+ // One paragraph per line, separated by empty lines.
+ Assert.Contains(Text("Left first") + "\r\n\r\n" + Text("Left second"), text);
+ }
+
+ [Fact]
+ public async Task Scanned_pages_become_page_pictures()
+ {
+ var dir = fx.NewFolder();
+ var pdf = new PdfBuilder().NewPage();
+ pdf.Picture(PdfBuilder.Photo(dir, "scan.jpg", MagickFormat.Jpeg, 595, 842), 0, 0, 595, 842);
+ pdf.NewPage().Line("Text after the scan", 12, pdf.Font(), 50, 80);
+ var path = pdf.Save(Path.Combine(dir, "scan.pdf"));
+
+ var docx = await ConvertAsync(path, "docx");
+
+ ValidPackage(docx);
+ var section = Assert.Single(ReadBack(docx).Sections);
+ var scan = section.Blocks.OfType<HParagraph>().First().Inlines.OfType<HImage>().Single();
+ Assert.Equal((59500, 84200), (scan.Width, scan.Height));
+ Assert.Equal(new HAnchor("PAPER", "LEFT", 0, "PAPER", "TOP", 0, "BEHIND_TEXT", true), scan.Anchor);
+ var text = section.Blocks.OfType<HParagraph>().Single(p => TextOf(p) == "Text after the scan");
+ Assert.True(text.PageBreakBefore);
+
+ // Nothing to extract as text from the scan, but the text page still is.
+ Assert.Equal("Text after the scan\r\n", await File.ReadAllTextAsync(await ConvertAsync(path, "txt"), TestContext.Current.CancellationToken));
+ }
+
+ [Fact]
+ public async Task Pdf_to_hwpx_goes_through_the_document_model()
+ {
+ Assert.Equal("hwpx-writer", Assert.Single(fx.Catalog.CreatePlanner().Plan("pdf", "hwpx")!.Steps).Converter.Id);
+ Assert.Equal("pdf-text", Assert.Single(fx.Catalog.CreatePlanner().Plan("pdf", "txt")!.Steps).Converter.Id);
+
+ var hwpx = await ConvertAsync(Report(fx.NewFolder()), "hwpx");
+
+ HwpxAssert.ValidPackage(hwpx, expectImages: 2);
+ Assert.Contains("Annual Report 2026", HwpxAssert.Xml(hwpx).Value);
+ HwpxAssert.RenderWithRhwp(fx, hwpx, "pdf-report");
+ }
+
+ /// <summary>Hangul needs an embedded font; the test uses Malgun Gothic when the system has it.</summary>
+ [Fact]
+ public async Task Korean_lines_join_into_one_paragraph()
+ {
+ var font = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "malgun.ttf");
+ Assert.SkipUnless(File.Exists(font), "no Hangul font (Malgun Gothic) on this system");
+ const string Korean = "한글 문단도 읽을 수 있어야 합니다. 줄이 바뀌어도 한 문단으로 이어지고 단어 사이의 빈칸도 그대로 남습니다.";
+ var dir = fx.NewFolder();
+ var pdf = new PdfBuilder().NewPage();
+ var hangul = pdf.TrueType(await File.ReadAllBytesAsync(font, TestContext.Current.CancellationToken));
+ pdf.Line("Korean", 16, pdf.Font(bold: true), 50, 80);
+ pdf.Paragraph(Korean, 11, hangul, 50, 110, 200, 16);
+ var path = pdf.Save(Path.Combine(dir, "korean.pdf"));
+
+ var text = await File.ReadAllTextAsync(await ConvertAsync(path, "txt"), TestContext.Current.CancellationToken);
+
+ Assert.Equal("Korean\r\n\r\n" + Korean + "\r\n", text.TrimStart(''));
+ }
+
+ [Fact]
+ public async Task Password_protected_pdf_fails_with_a_clear_message()
+ {
+ var dir = fx.NewFolder();
+ var pdf = new PdfBuilder().NewPage();
+ pdf.Line("Secret", 12, pdf.Font(), 50, 80);
+ var path = pdf.Save(Path.Combine(dir, "locked.pdf"));
+ PdfBuilder.Protect(path, "1234");
+
+ var job = await RunAsync(path, "docx");
+
+ Assert.Equal(JobState.Failed, job.State);
+ Assert.Contains("password", job.Files.Single().ErrorDetail, StringComparison.OrdinalIgnoreCase);
+ }
+
+ [Theory]
+ [InlineData("ABCDEF+TimesNewRomanPS-BoldMT", "Times New Roman")]
+ [InlineData("Arial-BoldMT", "Arial")]
+ [InlineData("Helvetica-Oblique", "Arial")]
+ [InlineData("QWERTY+MalgunGothic,Bold", "Malgun Gothic")]
+ [InlineData("NanumGothic", "NanumGothic")]
+ [InlineData("F1", null)]
+ [InlineData("T3Font_2", null)]
+ public void Font_names_become_families(string postScript, string? family) =>
+ Assert.Equal(family, PdfDocumentReader.FontFamily(postScript));
+}