Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.
C# audio-converteravaloniabatch-conversionconvertercsharpdocument-converterdocx-to-pdfdotnetdrag-and-dropfile-conversionfile-converterheic-converterhwphwpximage-converterlinuxmacospdf-convertervideo-converterwindows
OFD reader: safe package reading, ruled tables, real layout, donut and docs
KnifeLemonf5f79c588feb
diff --git a/README.ko.md b/README.ko.mdindex 9cfc61df..2be360d7 100644--- a/README.ko.md+++ b/README.ko.md@@ -34,7 +34,7 @@<table><tr><td width="33%" valign="top"><b>커서 바로 옆에서</b><br>앱 창을 열 필요가 없어요. 끌고 있는 파일에 맞는 형식만 지금 있는 자리에 나타나요.</td>- <td width="33%" valign="top"><b>248가지 형식, 다른 프로그램 없이</b><br>이미지, PDF, 워드, 엑셀, 파워포인트, HWP, 전자책, 압축 파일, 글꼴, CAD, 3D 모델을 오피스·한컴오피스·LibreOffice 없이 변환해요.</td>+ <td width="33%" valign="top"><b>249가지 형식, 다른 프로그램 없이</b><br>이미지, PDF, 워드, 엑셀, 파워포인트, HWP, 전자책, 압축 파일, 글꼴, CAD, 3D 모델을 오피스·한컴오피스·LibreOffice 없이 변환해요.</td><td width="33%" valign="top"><b>내 컴퓨터 안에서만</b><br>아무것도 업로드하지 않아요. 오프라인으로 동작하고 결과는 원본 옆에 저장해요.</td></tr></table>@@ -89,7 +89,7 @@| **이미지**: JPG, PNG, WEBP, AVIF, TIFF, BMP, GIF, APNG, ICO, ICNS, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM, HEIC, QOI, DDS, PCX, MNG, CUR 등; GIMP XCF, 카메라 RAW(CR2, CR3, NEF, ARW, DNG 등), DICOM, OpenEXR, HDR, JPEG XR(Windows)은 읽기 | 위 형식끼리(HEIC⁵), PDF, SVG(벡터화), 크기 조정, 흑백 || **벡터**: SVG, SVGZ, EMF, WMF, AI · EPS, PS¹ · CDR, VSD, CGM, ODG, FODG² | PDF(벡터), PNG 등 이미지, SVG ↔ SVGZ, SVG → DXF/DWG, PDF → EPS/PS¹, SVG → EMF, WMF, ODG² || **PDF** | DOCX, HWPX, TXT, PNG, JPG, TIFF, CBZ, PPTX(페이지마다 그림 한 장), SVG²; 합치기, 나누기, 페이지 범위, 압축 (더 작은 PDF) |-| **문서**: DOCX, DOCM, DOTX, EML, Outlook MSG · DOC, ODT, FODT, OTT, RTF, WPS, WPD, Pages, ClarisWorks, MacWrite, T602 등² | PDF, DOCX, HWPX, EPUB, TXT, HTML; MSG → EML · ODT, FODT, OTT² |+| **문서**: DOCX, DOCM, DOTX, EML, Outlook MSG; OFD(중국 전자세금계산서·공문서)는 읽기 · DOC, ODT, FODT, OTT, RTF, WPS, WPD, Pages, ClarisWorks, MacWrite, T602 등² | PDF, DOCX, HWPX, EPUB, TXT, HTML; MSG → EML · ODT, FODT, OTT² || **스프레드시트**: XLSX, XLSM, XLS, XLT, ODS, CSV, TSV · OTS, FODS, Numbers, ET² | PDF, XLSX, ODS, CSV, TSV, JSON, HWPX, HTML · XLT, OTS² || **프레젠테이션**: PPTX, PPTM, POTX, POTM, PPSX · PPT, ODP, OTP, FODP, Keynote² | PDF, PNG, JPG, DOCX, HWPX · OTP² || **한글**: HWP, HWPX | PDF, PNG, DOCX, HWPX ↔ HWP, TXT, 마크다운, HTML |diff --git a/README.md b/README.mdindex 769de2e2..a0ed055f 100644--- a/README.md+++ b/README.md@@ -34,7 +34,7 @@<table><tr><td width="33%" valign="top"><b>Right at your cursor</b><br>No app window to open. The formats appear where you already are, only the ones that make sense for the files you drag.</td>- <td width="33%" valign="top"><b>248 formats, no other software</b><br>Images, PDF, Word, Excel, PowerPoint, HWP, e-books, archives, fonts, CAD and 3D models work without Office, Hancom Office or LibreOffice.</td>+ <td width="33%" valign="top"><b>249 formats, no other software</b><br>Images, PDF, Word, Excel, PowerPoint, HWP, e-books, archives, fonts, CAD and 3D models work without Office, Hancom Office or LibreOffice.</td><td width="33%" valign="top"><b>Stays on your computer</b><br>Nothing is uploaded. Filee works offline and saves the result next to the original.</td></tr></table>@@ -89,7 +89,7 @@ Filee shows new releases in its menu and updates itself, keeping your settings a| **Images**: JPG, PNG, WEBP, AVIF, TIFF, BMP, GIF, APNG, ICO, ICNS, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM, HEIC, QOI, DDS, PCX, MNG, CUR, …; GIMP XCF, camera RAW (CR2, CR3, NEF, ARW, DNG, …), DICOM, OpenEXR, HDR, JPEG XR (Windows) read | any of these (HEIC⁵), PDF, SVG (traced), resized, grayscale || **Vector**: SVG, SVGZ, EMF, WMF, AI · EPS, PS¹ · CDR, VSD, CGM, ODG, FODG² | PDF (vector), PNG and other images, SVG ↔ SVGZ, SVG → DXF/DWG, PDF → EPS/PS¹, SVG → EMF, WMF, ODG² || **PDF** | DOCX, HWPX, TXT, PNG, JPG, TIFF, CBZ, PPTX (a picture of each page), SVG²; merge, split, page ranges, compress (smaller PDFs) |-| **Documents**: DOCX, DOCM, DOTX, EML, Outlook MSG · DOC, ODT, FODT, OTT, RTF, WPS, WPD, Pages, ClarisWorks, MacWrite, T602, …² | PDF, DOCX, HWPX, EPUB, TXT, HTML; MSG → EML · ODT, FODT, OTT² |+| **Documents**: DOCX, DOCM, DOTX, EML, Outlook MSG; OFD (Chinese e-invoices, official documents) read · DOC, ODT, FODT, OTT, RTF, WPS, WPD, Pages, ClarisWorks, MacWrite, T602, …² | PDF, DOCX, HWPX, EPUB, TXT, HTML; MSG → EML · ODT, FODT, OTT² || **Spreadsheets**: XLSX, XLSM, XLS, XLT, ODS, CSV, TSV · OTS, FODS, Numbers, ET² | PDF, XLSX, ODS, CSV, TSV, JSON, HWPX, HTML · XLT, OTS² || **Presentations**: PPTX, PPTM, POTX, POTM, PPSX · PPT, ODP, OTP, FODP, Keynote² | PDF, PNG, JPG, DOCX, HWPX · OTP² || **HWP**: HWP, HWPX | PDF, PNG, DOCX, HWPX ↔ HWP, TXT, Markdown, HTML |diff --git a/README.zh-CN.md b/README.zh-CN.mdindex 0b286be2..ec480349 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -34,7 +34,7 @@<table><tr><td width="33%" valign="top"><b>就在光标旁</b><br>无需打开应用窗口。只显示适合当前拖动文件的格式,就在你所在的位置。</td>- <td width="33%" valign="top"><b>248 种格式,无需其他软件</b><br>图片、PDF、Word、Excel、PowerPoint、HWP、电子书、压缩包、字体、CAD 和 3D 模型,无需 Office、韩文办公软件或 LibreOffice。</td>+ <td width="33%" valign="top"><b>249 种格式,无需其他软件</b><br>图片、PDF、Word、Excel、PowerPoint、HWP、电子书、压缩包、字体、CAD 和 3D 模型,无需 Office、韩文办公软件或 LibreOffice。</td><td width="33%" valign="top"><b>只在你的电脑上</b><br>不上传任何文件。Filee 离线工作,结果保存在原文件旁边。</td></tr></table>@@ -88,7 +88,7 @@| **图片**:JPG、PNG、WEBP、AVIF、TIFF、BMP、GIF、APNG、ICO、ICNS、JPEG XL、JPEG 2000、PSD/PSB、TGA、PPM、HEIC、QOI、DDS、PCX、MNG、CUR 等;GIMP XCF、相机 RAW(CR2、CR3、NEF、ARW、DNG 等)、DICOM、OpenEXR、HDR、JPEG XR(Windows)仅读取 | 上述格式互转(HEIC⁵)、PDF、SVG(描摹)、缩放、灰度 || **矢量图**:SVG、SVGZ、EMF、WMF、AI · EPS、PS¹ · CDR、VSD、CGM、ODG、FODG² | PDF(矢量)、PNG 等图片、SVG ↔ SVGZ、SVG → DXF/DWG、PDF → EPS/PS¹、SVG → EMF、WMF、ODG² || **PDF** | DOCX、HWPX、TXT、PNG、JPG、TIFF、CBZ、PPTX(每页一张图片)、SVG²;合并、拆分、页码范围、压缩(更小的 PDF) |-| **文档**:DOCX、DOCM、DOTX、EML、Outlook MSG · DOC、ODT、FODT、OTT、RTF、WPS、WPD、Pages、ClarisWorks、MacWrite、T602 等² | PDF、DOCX、HWPX、EPUB、TXT、HTML、MSG → EML · ODT、FODT、OTT² |+| **文档**:DOCX、DOCM、DOTX、EML、Outlook MSG;OFD(电子发票、公文)仅读取 · DOC、ODT、FODT、OTT、RTF、WPS、WPD、Pages、ClarisWorks、MacWrite、T602 等² | PDF、DOCX、HWPX、EPUB、TXT、HTML、MSG → EML · ODT、FODT、OTT² || **表格**:XLSX、XLSM、XLS、XLT、ODS、CSV、TSV · OTS、FODS、Numbers、ET² | PDF、XLSX、ODS、CSV、TSV、JSON、HWPX、HTML · XLT、OTS² || **演示文稿**:PPTX、PPTM、POTX、POTM、PPSX · PPT、ODP、OTP、FODP、Keynote² | PDF、PNG、JPG、DOCX、HWPX · OTP² || **HWP**:HWP、HWPX | PDF、PNG、DOCX、HWPX ↔ HWP、TXT、Markdown、HTML |diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex bbcdeb0a..6810b897 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -16,8 +16,8 @@ Filee chooses engines automatically. Settings → *Engines* shows their status,| Spreadsheets (ExcelDataReader for XLS) | built in (library) | **XLSX, XLS, ODS, CSV, TSV → XLSX, ODS, CSV, TSV** (one CSV / TSV per sheet) || Office Open XML | built in | **DOCM / DOTX / DOTM ↔ DOCX, XLSM / XLTX ↔ XLSX, PPTM / POTX / POTM / PPSX ↔ PPTX** (macros removed for macro-free types) || Fonts | built in | **TTF, OTF, WOFF, WOFF2, EOT ↔ each other**; CFF (PostScript) outlines become TrueType for TTF and EOT |-| **HWPX writer** | built in | **DOCX (+ DOCM/DOTX/DOTM), XLSX (+ XLSM/XLTX), XLS, ODS, CSV, TSV, PPTX (+ PPTM/POTX/POTM/PPSX), PDF, HTML, MHTML, EPUB, MOBI/AZW3, FB2, HWPX, TXT, Markdown → HWPX** (and with rhwp → PDF and images); ODT, RTF, reStructuredText, LaTeX → HWPX with Pandoc |-| **DOCX writer** | built in | **HWPX (and HWP through rhwp), PDF, HTML, MHTML, EPUB, MOBI/AZW3, FB2, Markdown, TXT, XLSX, XLS, ODS, CSV, PPTX (+ variants) → DOCX** |+| **HWPX writer** | built in | **DOCX (+ DOCM/DOTX/DOTM), XLSX (+ XLSM/XLTX), XLS, ODS, CSV, TSV, PPTX (+ PPTM/POTX/POTM/PPSX), PDF, OFD, HTML, MHTML, EPUB, MOBI/AZW3, FB2, HWPX, TXT, Markdown → HWPX** (and with rhwp → PDF and images); ODT, RTF, reStructuredText, LaTeX → HWPX with Pandoc |+| **DOCX writer** | built in | **HWPX (and HWP through rhwp), PDF, OFD, HTML, MHTML, EPUB, MOBI/AZW3, FB2, Markdown, TXT, XLSX, XLS, ODS, CSV, PPTX (+ variants) → DOCX** || PDF text | built in (PdfPig) | **PDF → TXT, Markdown** (reading order, also two columns; Markdown keeps headings, emphasis, links and the pictures; no OCR) || PDF slides | built in (PDFium, PdfPig) | **PDF → PPTX**: a picture of each page on its own slide (looks like the PDF, not editable), the page's text in the speaker notes || E-mail | built in (MimeKit, MsgReader) | **EML, Outlook MSG → HTML** (headers + body, inline pictures), **TXT**, **ZIP** (the attachments); **MSG → EML**; **MHTML → HTML** (the saved page in one file, pictures inlined; on to PDF, DOCX, HWPX, TXT, Markdown, EPUB from there) |@@ -43,13 +43,13 @@ so Arabic and Hebrew come out unjoined and in the wrong order, and Indic vowel swith dotted circles (#185 Gujarati, #202 Arabic). Its PDF edges are marked `Unshaped`, and rhwp tells(`ITextShapingCheck`) whether a source has such text: `Infrastructure/ComplexScripts.cs` scans the text parts of thefile without reading it into the document model (DOCX `word/document.xml`, headers, footers and notes, PPTX slides,-XLSX shared strings and sheets, HWPX sections, EPUB chapters, or a text file with its HTML / RTF character-references) for the Hebrew, Arabic, Syriac, Thaana, N'Ko, Indic, Sinhala, Thai, Lao, Tibetan, Myanmar, Khmer,-Mongolian and other South / Southeast Asian blocks. For such a file `JobQueue` plans again without unshaped edges: DOCX,-TXT, Markdown, HTML, XLSX, PPTX and HWPX → PDF (and → images through PDF) go through LibreOffice even when Settings →-*Engines* doesn't choose it for documents. Without LibreOffice the file fails with "This script needs LibreOffice to-convert correctly" and the script's name instead of becoming a broken PDF. Latin, Greek, Cyrillic, CJK and Korean-documents keep the built-in route; a binary HWP is not scanned and stays with rhwp.+XLSX shared strings and sheets, HWPX sections, OFD pages and templates, EPUB chapters, or a text file with its HTML /+RTF character references) for the Hebrew, Arabic, Syriac, Thaana, N'Ko, Indic, Sinhala, Thai, Lao, Tibetan, Myanmar,+Khmer, Mongolian and other South / Southeast Asian blocks. For such a file `JobQueue` plans again without unshaped+edges: DOCX, TXT, Markdown, HTML, XLSX, PPTX and HWPX → PDF (and → images through PDF) go through LibreOffice even+when Settings → *Engines* doesn't choose it for documents. Without LibreOffice the file fails with "This script needs+LibreOffice to convert correctly" and the script's name instead of becoming a broken PDF. Latin, Greek, Cyrillic, CJK+and Korean documents keep the built-in route; a binary HWP is not scanned and stays with rhwp.All built-in document readers are registered in one place, `Hwp/Hwpx/DocumentReaders.cs` (format id → reader, andwhich formats need Pandoc). The HWPX writer and the DOCX writer take their input formats from it: adding a reader@@ -503,6 +503,59 @@ writes the text only, read like PDF → TXT (the invisible OCR layer of scans inoption applies to every Markdown writer: e-books (`EbookConverter`), HWP / HWPX (`UnhwpConverter`) and Pandoc (aLua filter drops the pictures, figures keep their captions).+## OFD reader++OFD (GB/T 33190-2016) is China's fixed-layout format: fully digitalized e-invoices (数电票), contracts and official+documents. `Ofd/OfdReader*.cs` reads it into the document model with no external engine, so OFD → DOCX and HWPX are+one step, → PDF two (rhwp), and TXT, Markdown, HTML, EPUB follow from there. OFD is read only (`Writable: false`) and+sits on the office donut (settings schema 27 teaches existing donuts `.ofd`).++- **Package** (`Ofd/OfdPackage.cs`): OFD.xml → the first document (Document.xml) → its pages, template pages and+ resource files (PublicRes, DocumentRes, a page's PageRes, and the unnamed `Res.xml` WPS writes next to them).+ Parts are looked up by name inside the ZIP and never written out under their own names; references are resolved+ against the referring part (or the package root for "/…"), "." and ".." applied, and anything that leaves the+ package, a URL or a drive path finds nothing. XML is read without DTDs; a part may unpack to 64 MB, a picture to+ 32 MB (larger ones are left out), the whole package to 1 GB; at most 100,000 parts, 10,000 pages, 2,000,000+ drawing objects, page blocks nested 32 deep. DeltaX / DeltaY "g n d" repeats never yield more values than the+ text has characters.+- **Encryption**: a package with an `Encryptions.xml` (GM/T 0099) or encryption entries in OFD.xml is refused with a+ clear message; nothing is decrypted. Parts that are not XML (encrypted or damaged) fail the same way. Signatures+ (`Signs/`) are ignored, so the seal images stored inside signed data do not appear.+- **Text**: TextObjects with their Boundary, CTM (scale, also of the font size), Size in millimetres, TextCode X / Y+ (missing ones continue where the previous code ended) and DeltaX advances; DeltaY runs are vertical text. Fonts+ from the resource files, with common Chinese names written in English (宋体 → SimSun, 黑体 → SimHei, 楷体 → KaiTi,+ 仿宋 → FangSong, 微软雅黑 → Microsoft YaHei, …) so Word and LibreOffice find them on any system; bold from+ `Weight` ≥ 600 or the font, italic, colour from the object (FillColor element or attribute; RGB, grey, CMYK,+ decimal or #hex channels), its DrawParam or the layer's DrawParam (tax invoices colour the template that way),+ following `Relative` chains. Invisible objects (`Visible="false"`) are left out.+- **Templates**: the template pages a page names are read first, so an invoice's labels (发票号码:, 名称:) and its+ values come out together. In template content, single characters stacked in one column (购买方信息, 备注) or a+ pair spread over a line (合 计) become one word.+- **Layout** (`OfdReader.Layout.cs`): fragments on one baseline form a line, in reading order top to bottom and+ left to right; a line that ran to the right edge from at least half the measure continues in the next one+ (justified, first-line indent kept, no space between Chinese lines). Wide gaps (1.5 em) become tabs with left+ tab stops where each part starts, so an invoice's item rows keep their columns; a line under such a row whose+ parts start in its columns and hold no amounts is the wrapped end of its cells and follows after a line break in+ the same paragraph. Centred and right-aligned lines, left indents and vertical distances (space before) follow+ the page; page size per page (a new section when it changes), margins from what is drawn.+- **Ruled tables** (`OfdReader.Tables.cs`): the approach of the PDF reader in millimetres. PathObjects+ (AbbreviatedData M/S/L/Q/B/A/C, with Boundary, CTM, line width and stroke colour from the object or its+ DrawParams) give stroked straight rules and thin filled rectangles; joined rules that meet form grids, and a grid+ of at least 2 × 2 units with rectangular merged cells and text in two cells becomes a table with the page's+ column widths and row heights, borders in the drawn colour and shading. Text goes into the cell of its first+ character (widths without DeltaX are estimated) and is laid out like the page, with exact line spacing so the+ rows keep their heights. The frame of an e-invoice becomes one table: buyer and seller blocks, the item list+ (one cell with tabbed rows: the invoice draws no rules between item columns), totals and remarks.+- **Pictures**: ImageObjects (MultiMedia of type Image) with the box from their CTM. PNG, JPEG, GIF and BMP are+ kept as they are (the format comes from the bytes, not the name), TIFF and JPEG 2000 are converted to PNG+ (ImageMagick, at most 100 megapixels), anything else (JBIG2) is left out. A picture alone in its band of the page+ becomes a paragraph; one beside or over text (a QR code next to the title, a seal on a table) floats at its place+ on the paper, in front of the text.++Not converted: annotations (Annots), signatures and their seals, embedded fonts (the font name is kept), composite+objects and other vector drawings, attachments, more than the first document of a package, tables without rules+(their text stays in tabbed rows), clipping. Two text blocks side by side without rules share their lines.+## PDF → PPTX`Pdf/PdfSlidesConverter.cs` turns a PDF into a PowerPoint deck of pictures: every page is rendered (PDFium, as fordiff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.jsonindex 730407ed..f18e9d3a 100644--- a/src/Filee.App/Assets/i18n/en.json+++ b/src/Filee.App/Assets/i18n/en.json@@ -95,8 +95,8 @@"engine.markdown.description": "Markdown → HTML and plain text.","engine.spreadsheet.description": "XLSX, XLS, ODS, CSV and TSV into each other (XLS is read only).\nOne CSV per sheet.","engine.ooxml.description": "Macro-enabled files and templates (DOCM, XLSM, PPTM, DOTX…) ↔ DOCX, XLSX, PPTX.\nMacros are removed.",- "engine.hwpx-writer.description": "Writes HWPX from Word, Excel, PowerPoint, PDF, HTML, e-books and Markdown.\nThe first step of turning documents into PDF without Office.",- "engine.docx-writer.description": "Writes Word documents (DOCX) from PDF, HWP/HWPX, Markdown, HTML, spreadsheets, slides and e-books.",+ "engine.hwpx-writer.description": "Writes HWPX from Word, Excel, PowerPoint, PDF, OFD, HTML, e-books and Markdown.\nThe first step of turning documents into PDF without Office.",+ "engine.docx-writer.description": "Writes Word documents (DOCX) from PDF, OFD, HWP/HWPX, Markdown, HTML, spreadsheets, slides and e-books.","engine.pdf-text.description": "Extracts the text of PDFs in reading order, also from two-column pages (no OCR for scans).","engine.pdf-slides.description": "Turns PDFs into PowerPoint slides: each page becomes a picture on its own slide (looks like the PDF, not editable), with the page text in the speaker notes.","engine.email.description": "E-mails (EML, Outlook MSG) to HTML and text with sender, recipients and date, pictures included; attachments into a ZIP.\nMSG to EML. Saved web pages (MHTML) to one HTML file with their pictures.",diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.jsonindex 033e997a..680814db 100644--- a/src/Filee.App/Assets/i18n/es.json+++ b/src/Filee.App/Assets/i18n/es.json@@ -88,8 +88,8 @@"engine.markdown.description": "Markdown → HTML y texto sin formato.","engine.spreadsheet.description": "XLSX, XLS, ODS, CSV y TSV entre sí (XLS es de solo lectura).\nUn CSV por hoja.","engine.ooxml.description": "Archivos y plantillas con macros (DOCM, XLSM, PPTM, DOTX…) ↔ DOCX, XLSX, PPTX.\nLas macros se eliminan.",- "engine.hwpx-writer.description": "Escribe HWPX desde Word, Excel, PowerPoint, PDF, HTML, libros electrónicos y Markdown.\nEl primer paso para pasar documentos a PDF sin Office.",- "engine.docx-writer.description": "Escribe documentos de Word (DOCX) desde PDF, HWP/HWPX, Markdown, HTML, hojas de cálculo, diapositivas y libros electrónicos.",+ "engine.hwpx-writer.description": "Escribe HWPX desde Word, Excel, PowerPoint, PDF, OFD, HTML, libros electrónicos y Markdown.\nEl primer paso para pasar documentos a PDF sin Office.",+ "engine.docx-writer.description": "Escribe documentos de Word (DOCX) desde PDF, OFD, HWP/HWPX, Markdown, HTML, hojas de cálculo, diapositivas y libros electrónicos.","engine.pdf-text.description": "Extrae el texto de los PDF en orden de lectura, también de páginas en dos columnas (sin OCR para escaneos).","engine.pdf-slides.description": "Convierte PDF en diapositivas de PowerPoint: cada página pasa a ser una imagen en su propia diapositiva (con el aspecto del PDF, no editable), con el texto de la página en las notas del orador.","engine.email.description": "Correos electrónicos (EML, Outlook MSG) a HTML y texto con remitente, destinatarios y fecha, imágenes incluidas; los adjuntos van a un ZIP.\nMSG a EML. Páginas web guardadas (MHTML) a un solo archivo HTML con sus imágenes.",diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.jsonindex 66a74ca9..ea77ae01 100644--- a/src/Filee.App/Assets/i18n/hi.json+++ b/src/Filee.App/Assets/i18n/hi.json@@ -88,8 +88,8 @@"engine.markdown.description": "Markdown → HTML और सादा टेक्स्ट।","engine.spreadsheet.description": "XLSX, XLS, ODS, CSV और TSV एक-दूसरे में (XLS केवल पढ़ा जा सकता है)।\nहर शीट के लिए एक CSV।","engine.ooxml.description": "मैक्रो-सक्षम फ़ाइलें और टेम्पलेट (DOCM, XLSM, PPTM, DOTX…) ↔ DOCX, XLSX, PPTX।\nमैक्रो हटा दिए जाते हैं।",- "engine.hwpx-writer.description": "Word, Excel, PowerPoint, PDF, HTML, ई-बुक और Markdown से HWPX लिखता है।\nOffice के बिना दस्तावेज़ों को PDF में बदलने का पहला चरण।",- "engine.docx-writer.description": "PDF, HWP/HWPX, Markdown, HTML, स्प्रेडशीट, स्लाइड और ई-बुक से Word दस्तावेज़ (DOCX) लिखता है।",+ "engine.hwpx-writer.description": "Word, Excel, PowerPoint, PDF, OFD, HTML, ई-बुक और Markdown से HWPX लिखता है।\nOffice के बिना दस्तावेज़ों को PDF में बदलने का पहला चरण।",+ "engine.docx-writer.description": "PDF, OFD, HWP/HWPX, Markdown, HTML, स्प्रेडशीट, स्लाइड और ई-बुक से Word दस्तावेज़ (DOCX) लिखता है।","engine.pdf-text.description": "PDF का टेक्स्ट पढ़ने के क्रम में निकालता है, दो-कॉलम वाले पेजों से भी (स्कैन के लिए OCR नहीं)।","engine.pdf-slides.description": "PDF को PowerPoint स्लाइड में बदलता है: हर पेज अपनी स्लाइड पर एक तस्वीर बन जाता है (PDF जैसा दिखता है, संपादन योग्य नहीं), और पेज का टेक्स्ट स्पीकर नोट्स में रहता है।","engine.email.description": "ई-मेल (EML, Outlook MSG) को भेजने वाले, प्राप्तकर्ताओं और तारीख के साथ HTML और टेक्स्ट में बदलता है, तस्वीरों सहित; अटैचमेंट ZIP में।\nMSG से EML। सहेजे गए वेब पेज (MHTML) उनकी तस्वीरों सहित एक HTML फ़ाइल में।",diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.jsonindex 3f5d09bb..907fe2a2 100644--- a/src/Filee.App/Assets/i18n/ko.json+++ b/src/Filee.App/Assets/i18n/ko.json@@ -95,8 +95,8 @@"engine.markdown.description": "마크다운 → HTML, 텍스트.","engine.spreadsheet.description": "XLSX, XLS, ODS, CSV, TSV를 서로 바꿔요(XLS는 읽기만).\nCSV는 시트마다 하나씩 만들어요.","engine.ooxml.description": "매크로·서식 파일(DOCM, XLSM, PPTM, DOTX 등) ↔ DOCX, XLSX, PPTX.\n매크로는 지워요.",- "engine.hwpx-writer.description": "워드, 엑셀, 파워포인트, PDF, HTML, 전자책, 마크다운을 HWPX로 써요.\n오피스 없이 문서를 PDF로 바꾸는 첫 단계예요.",- "engine.docx-writer.description": "PDF, HWP/HWPX, 마크다운, HTML, 스프레드시트, 슬라이드, 전자책으로 워드 문서(DOCX)를 만들어요.",+ "engine.hwpx-writer.description": "워드, 엑셀, 파워포인트, PDF, OFD, HTML, 전자책, 마크다운을 HWPX로 써요.\n오피스 없이 문서를 PDF로 바꾸는 첫 단계예요.",+ "engine.docx-writer.description": "PDF, OFD, HWP/HWPX, 마크다운, HTML, 스프레드시트, 슬라이드, 전자책으로 워드 문서(DOCX)를 만들어요.","engine.pdf-text.description": "PDF의 글자를 읽는 순서대로 뽑아내요.\n2단 편집도 순서대로 읽어요(스캔 이미지 글자 인식은 안 해요).","engine.pdf-slides.description": "PDF를 파워포인트 슬라이드로 바꿔요. 페이지마다 그림 한 장으로 슬라이드에 넣어서 PDF와 똑같이 보여요(편집은 안 돼요).\n페이지 글자는 슬라이드 노트에 넣어요.","engine.email.description": "이메일(EML, Outlook MSG)을 보낸 사람·받는 사람·날짜와 본문 그림까지 담아 HTML·텍스트로 바꾸고, 첨부 파일은 ZIP으로 모아요.\nMSG는 EML로도 바꾸고, 저장한 웹 페이지(MHTML)는 그림까지 담긴 HTML 파일 하나로 바꿔요.",diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.jsonindex 655a9180..e1b79530 100644--- a/src/Filee.App/Assets/i18n/pl.json+++ b/src/Filee.App/Assets/i18n/pl.json@@ -95,8 +95,8 @@"engine.markdown.description": "Markdown → HTML i zwykły tekst.","engine.spreadsheet.description": "XLSX, XLS, ODS, CSV i TSV między sobą (XLS tylko do odczytu).\nJeden CSV na arkusz.","engine.ooxml.description": "Pliki z makrami i szablony (DOCM, XLSM, PPTM, DOTX…) ↔ DOCX, XLSX, PPTX.\nMakra są usuwane.",- "engine.hwpx-writer.description": "Zapisuje HWPX z Worda, Excela, PowerPointa, PDF, HTML, e-booków i Markdown.\nPierwszy krok zamiany dokumentów na PDF bez Office.",- "engine.docx-writer.description": "Zapisuje dokumenty Word (DOCX) z PDF, HWP/HWPX, Markdown, HTML, arkuszy, slajdów i e-booków.",+ "engine.hwpx-writer.description": "Zapisuje HWPX z Worda, Excela, PowerPointa, PDF, OFD, HTML, e-booków i Markdown.\nPierwszy krok zamiany dokumentów na PDF bez Office.",+ "engine.docx-writer.description": "Zapisuje dokumenty Word (DOCX) z PDF, OFD, HWP/HWPX, Markdown, HTML, arkuszy, slajdów i e-booków.","engine.pdf-text.description": "Wyodrębnia tekst z PDF w kolejności czytania, także ze stron dwukolumnowych (bez OCR skanów).","engine.pdf-slides.description": "Zamienia PDF na slajdy PowerPoint: każda strona staje się obrazem na osobnym slajdzie (wygląda jak PDF, bez edycji), a tekst strony trafia do notatek prelegenta.","engine.email.description": "E-maile (EML, Outlook MSG) do HTML i tekstu z nadawcą, odbiorcami i datą, razem z obrazami; załączniki do ZIP.\nMSG do EML. Zapisane strony internetowe (MHTML) do jednego pliku HTML razem z obrazami.",diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.jsonindex dcaae0b4..d1f1f4b1 100644--- a/src/Filee.App/Assets/i18n/zh-CN.json+++ b/src/Filee.App/Assets/i18n/zh-CN.json@@ -95,8 +95,8 @@"engine.markdown.description": "Markdown → HTML 和纯文本。","engine.spreadsheet.description": "XLSX、XLS、ODS、CSV、TSV 互相转换(XLS 仅读取)。\n每个工作表生成一个 CSV。","engine.ooxml.description": "启用宏的文件和模板(DOCM、XLSM、PPTM、DOTX 等)↔ DOCX、XLSX、PPTX。\n转换时移除宏。",- "engine.hwpx-writer.description": "把 Word、Excel、PowerPoint、PDF、HTML、电子书和 Markdown 写成 HWPX。\n这是不用 Office 把文档转为 PDF 的第一步。",- "engine.docx-writer.description": "用 PDF、HWP/HWPX、Markdown、HTML、表格、幻灯片和电子书生成 Word 文档(DOCX)。",+ "engine.hwpx-writer.description": "把 Word、Excel、PowerPoint、PDF、OFD、HTML、电子书和 Markdown 写成 HWPX。\n这是不用 Office 把文档转为 PDF 的第一步。",+ "engine.docx-writer.description": "用 PDF、OFD、HWP/HWPX、Markdown、HTML、表格、幻灯片和电子书生成 Word 文档(DOCX)。","engine.pdf-text.description": "按阅读顺序提取 PDF 中的文字,双栏页面也能正确排序(不对扫描件做文字识别)。","engine.pdf-slides.description": "将 PDF 转换为 PowerPoint 幻灯片。每页作为一张图片放在单独的幻灯片上,外观与 PDF 相同(不可编辑),页面文字放入演讲者备注。","engine.email.description": "将电子邮件(EML、Outlook MSG)连同发件人、收件人、日期和图片转为 HTML 和文本,附件打包为 ZIP。\nMSG 也可转为 EML。保存的网页(MHTML)可连同图片转为单个 HTML 文件。",diff --git a/src/Filee.Core/Formats/FormatRegistry.cs b/src/Filee.Core/Formats/FormatRegistry.csindex 53340ce4..921f727f 100644--- a/src/Filee.Core/Formats/FormatRegistry.cs+++ b/src/Filee.Core/Formats/FormatRegistry.cs@@ -72,7 +72,6 @@ public static class FormatRegistrynew("pdf", "PDF", FormatCategory.Pdf, ["pdf"]),// Word processing- new("ofd", "OFD", FormatCategory.Document, ["ofd"], Writable: false),new("docx", "DOCX", FormatCategory.Document, ["docx"]),new("docm", "DOCM", FormatCategory.Document, ["docm"]),new("dotx", "DOTX", FormatCategory.Document, ["dotx"]),@@ -84,6 +83,8 @@ public static class FormatRegistrynew("ott", "OTT", FormatCategory.Document, ["ott"]),new("rtf", "RTF", FormatCategory.Document, ["rtf"]),new("wps", "WPS", FormatCategory.Document, ["wps"], Writable: false),+ // The Chinese fixed-layout standard (GB/T 33190): e-invoices, official documents; read by the built-in OFD reader.+ new("ofd", "OFD", FormatCategory.Document, ["ofd"], Writable: false),new("wpd", "WPD", FormatCategory.Document, ["wpd"], Writable: false),new("lwp", "LWP", FormatCategory.Document, ["lwp"], Writable: false),new("abw", "ABW", FormatCategory.Document, ["abw", "zabw"], Writable: false),diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.csindex 79863577..f787569d 100644--- a/src/Filee.Core/Settings/AppSettings.cs+++ b/src/Filee.Core/Settings/AppSettings.cs@@ -65,7 +65,7 @@ public sealed class DonutSettingspublic sealed class AppSettings{/// <summary>Current schema version. Increase when the format changes and add a migration.</summary>- public const int CurrentSchemaVersion = 24;+ public const int CurrentSchemaVersion = 27;public int SchemaVersion { get; set; } = CurrentSchemaVersion;diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.csindex 17dea6ea..77a88240 100644--- a/src/Filee.Core/Settings/UserDataStore.cs+++ b/src/Filee.Core/Settings/UserDataStore.cs@@ -631,6 +631,10 @@ internal static class SettingsMigrations// of the user already takes them.if (from < 24)changed |= LearnExtensions(profiles, out _, ["potm"]);+ // v27: OFD documents (.ofd; read only: e-invoices, official documents) open from the office donut, unless a+ // donut of the user already takes them.+ if (from < 27)+ changed |= LearnExtensions(profiles, out _, ["ofd"]);return changed;}diff --git a/src/Filee.Engines/Infrastructure/ComplexScripts.cs b/src/Filee.Engines/Infrastructure/ComplexScripts.csindex d86c07ba..56d17b49 100644--- a/src/Filee.Engines/Infrastructure/ComplexScripts.cs+++ b/src/Filee.Engines/Infrastructure/ComplexScripts.cs@@ -233,6 +233,8 @@ internal static partial class ComplexScripts"xlsx" or "xlsm" or "xltx" => Xml("xl/", "sharedStrings") || Xml("xl/worksheets/", "sheet"),"hwpx" => Xml("Contents/", "section"),"odt" or "ods" or "odp" => name.Equals("content.xml", StringComparison.OrdinalIgnoreCase),+ // OFD: the pages and templates (Doc_0/Pages/Page_0/Content.xml, Doc_0/Tpls/Tpl_0/Content.xml).+ "ofd" => name.EndsWith("/Content.xml", StringComparison.OrdinalIgnoreCase),// EPUB, HTMLZ, TXTZ, ...: the chapters._ => !name.StartsWith("META-INF/", StringComparison.OrdinalIgnoreCase)&& (name.EndsWith(".xhtml", StringComparison.OrdinalIgnoreCase) || name.EndsWith(".html", StringComparison.OrdinalIgnoreCase)diff --git a/src/Filee.Engines/Ofd/OfdPackage.cs b/src/Filee.Engines/Ofd/OfdPackage.csnew file mode 100644index 00000000..fcd4b951--- /dev/null+++ b/src/Filee.Engines/Ofd/OfdPackage.cs@@ -0,0 +1,147 @@+// The ZIP container of an OFD file, read defensively: parts are looked up by name inside the package and never+// written out under their own names, references ("../Res/a.png", "/Doc_0/Document.xml") are resolved against the+// package root and cannot leave it, XML is read without DTDs, and every part is read with a size limit (also checked+// while decompressing, so a lying header does not help a zip bomb).++using System.IO.Compression;+using System.Xml;+using System.Xml.Linq;++namespace Filee.Engines.Ofd;++/// <summary>An OFD package opened for reading.</summary>+internal sealed class OfdPackage : IDisposable+{+ /// <summary>More parts than this are refused (real OFD files have a few per page).</summary>+ private const int MaxEntries = 100_000;++ /// <summary>Largest XML part read (a page, a resource list).</summary>+ private const long MaxXmlBytes = 64L * 1024 * 1024;++ /// <summary>Largest picture taken; bigger ones are left out.</summary>+ public const long MaxPictureBytes = 32L * 1024 * 1024;++ /// <summary>Everything read from one package together.</summary>+ private const long MaxTotalBytes = 1024L * 1024 * 1024;++ private static readonly XmlReaderSettings XmlSettings = new()+ {+ DtdProcessing = DtdProcessing.Prohibit,+ XmlResolver = null,+ IgnoreComments = true,+ IgnoreProcessingInstructions = true,+ MaxCharactersInDocument = MaxXmlBytes,+ };++ private readonly ZipArchive _zip;+ private readonly Dictionary<string, ZipArchiveEntry> _entries = new(StringComparer.OrdinalIgnoreCase);+ private long _read;++ public OfdPackage(string path)+ {+ try+ {+ _zip = ZipFile.OpenRead(path);+ }+ catch (InvalidDataException ex)+ {+ throw new InvalidDataException("The file is not an OFD document (it is not a ZIP package). It may be damaged.", ex);+ }+ if (_zip.Entries.Count > MaxEntries)+ {+ _zip.Dispose();+ throw new InvalidDataException($"The OFD package has more than {MaxEntries:N0} parts; Filee does not read it.");+ }+ foreach (var entry in _zip.Entries)+ {+ // Names that climb out of the package ("../x") are unreachable; of two parts with one name the first wins.+ if (!entry.FullName.EndsWith('/') && Resolve("", entry.FullName) is { } name)+ _entries.TryAdd(name, entry);+ }+ }++ public void Dispose() => _zip.Dispose();++ /// <summary>True when the package has a part of that (resolved) name.</summary>+ public bool Has(string? name) => name is not null && _entries.ContainsKey(name);++ /// <summary>Names of all parts, resolved.</summary>+ public IEnumerable<string> Names => _entries.Keys;++ /// <summary>+ /// A reference inside the package as a part name: relative to <paramref name="baseDir"/>, or to the package root+ /// when it starts with "/". "." and ".." are applied; null when the reference is empty, leaves the package or is+ /// a URL or drive path.+ /// </summary>+ public static string? Resolve(string baseDir, string? reference)+ {+ if (string.IsNullOrWhiteSpace(reference))+ return null;+ reference = reference.Trim().Replace('\\', '/');+ if (reference.Contains(':'))+ return null;+ var parts = new List<string>();+ if (!reference.StartsWith('/'))+ parts.AddRange(baseDir.Split('/', StringSplitOptions.RemoveEmptyEntries));+ foreach (var segment in reference.Split('/', StringSplitOptions.RemoveEmptyEntries))+ {+ if (segment == ".")+ continue;+ if (segment == "..")+ {+ if (parts.Count == 0)+ return null;+ parts.RemoveAt(parts.Count - 1);+ continue;+ }+ parts.Add(segment);+ }+ return parts.Count == 0 ? null : string.Join('/', parts);+ }++ /// <summary>The folder of a part name ("" at the root).</summary>+ public static string DirName(string name)+ {+ var slash = name.LastIndexOf('/');+ return slash < 0 ? "" : name[..slash];+ }++ /// <summary>An XML part, or null when the package has no such part. Throws for parts that are not XML.</summary>+ public XDocument? LoadXml(string? name)+ {+ if (name is null || !_entries.ContainsKey(name))+ return null;+ var bytes = Read(name, MaxXmlBytes)+ ?? throw new InvalidDataException($"The OFD part {name} is larger than {MaxXmlBytes / (1024 * 1024)} MB; Filee does not read it.");+ try+ {+ using var reader = XmlReader.Create(new MemoryStream(bytes), XmlSettings);+ return XDocument.Load(reader);+ }+ catch (XmlException ex)+ {+ throw new InvalidDataException($"The OFD part {name} is not valid XML. The file may be encrypted or damaged. {ex.Message}", ex);+ }+ }++ /// <summary>The bytes of a part; null when it is missing or larger than <paramref name="max"/>.</summary>+ public byte[]? Read(string name, long max)+ {+ if (!_entries.TryGetValue(name, out var entry) || entry.Length > max)+ return null;+ using var stream = entry.Open();+ using var copy = new MemoryStream((int)Math.Min(entry.Length, 1024 * 1024));+ var buffer = new byte[81920];+ int count;+ while ((count = stream.Read(buffer)) > 0)+ {+ if (copy.Length + count > max)+ return null;+ _read += count;+ if (_read > MaxTotalBytes)+ throw new InvalidDataException($"The OFD package unpacks to more than {MaxTotalBytes / (1024 * 1024 * 1024)} GB; Filee does not read it.");+ copy.Write(buffer, 0, count);+ }+ return copy.ToArray();+ }+}diff --git a/src/Filee.Engines/Ofd/OfdReader.Layout.cs b/src/Filee.Engines/Ofd/OfdReader.Layout.csnew file mode 100644index 00000000..2024522b--- /dev/null+++ b/src/Filee.Engines/Ofd/OfdReader.Layout.cs@@ -0,0 +1,394 @@+// Layout for OfdReader: the fragments of a page become lines (same baseline, left to right) and lines paragraphs+// (a line that ran to the right edge continues in the next one), in reading order from the top. A line with wide+// gaps (the columns of an invoice's item rows) keeps its parts at their places with tab stops; text under such a row+// in its columns is the wrapped end of its cells and follows in the same paragraph after a line break. Grids drawn with lines become tables first (OfdReader.Tables). Pictures+// alone in their band of the page become paragraphs; pictures beside or over text (QR codes, seals) float where+// they are on the paper. Vertical space between blocks is kept as space before paragraphs, so a page looks like the+// original.++using System.Text.RegularExpressions;+using Filee.Engines.Hwp.Hwpx;++namespace Filee.Engines.Ofd;++internal sealed partial class OfdReader+{+ private const double MmToUnit = 7200.0 / 25.4;++ /// <summary>Margins (mm) are kept within these bounds.</summary>+ private const double MinMargin = 3, MaxMargin = 40;++ private static int Hwp(double mm) => (int)Math.Round(Math.Clamp(mm * MmToUnit, -1e9, 1e9));++ /// <summary>+ /// Fragments on one baseline, left to right; <see cref="Tabs"/> are the ones a wide gap comes before.+ /// <see cref="Wrapped"/> holds the wrapped ends of a tabbed row's cells, each with the column it belongs to.+ /// </summary>+ private sealed class Line(Fragment first)+ {+ public List<Fragment> Fragments { get; } = [first];+ public HashSet<int> Tabs { get; } = [];+ public List<(Fragment Fragment, int Column)> Wrapped { get; } = [];+ public double Baseline { get; } = first.Baseline;+ public double Size => Fragments.Max(f => f.Size);+ public double Left => Fragments.Min(f => f.Left);+ public double Right => Fragments.Max(f => f.Right);+ public double LastBaseline => Fragments.Concat(Wrapped.Select(w => w.Fragment)).Max(f => f.Baseline + f.Run);+ public bool Vertical => Fragments[0].Vertical;+ }++ /// <summary>A paragraph, a table or a picture at its place on the page (mm from the top).</summary>+ private sealed record Placed(double Top, double Bottom, List<Line>? Lines = null, RuledTable? Table = null, HImage? Image = null, double Left = 0);++ // ───────────────────────── Pages ─────────────────────────++ private HDocument Build(List<PageContent> pages)+ {+ var document = new HDocument();+ var margins = pages.GroupBy(p => (p.Width, p.Height)).ToDictionary(g => g.Key, g => Margins(g));+ HSection? section = null;+ foreach (var page in pages)+ {+ var (left, top, right, bottom) = margins[(page.Width, page.Height)];+ 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 = PageBlocks(page, left, page.Width - right, top);+ // A table cannot start a page in every format: a tiny empty paragraph before it carries the page break.+ if (blocks.Count == 0 || blocks[0] is HTable)+ blocks.Insert(0, new HParagraph { MarkFormat = new HCharFormat(Size: 100) });+ if (!newSection && blocks[0] is HParagraph first)+ first.PageBreakBefore = true;+ section!.Blocks.AddRange(blocks);+ }+ if (document.Sections.Count == 0)+ {+ var empty = new HSection();+ empty.Blocks.Add(new HParagraph());+ document.Sections.Add(empty);+ }+ return document;+ }++ /// <summary>+ /// Margins of the pages of one size: the smallest distances from the edges to anything drawn. The bottom one is+ /// halved, so text that comes out a little taller than in the original still fits on its page.+ /// </summary>+ private static (double Left, double Top, double Right, double Bottom) Margins(IEnumerable<PageContent> pages)+ {+ double left = double.MaxValue, top = double.MaxValue, right = double.MaxValue, bottom = double.MaxValue;+ foreach (var page in pages)+ {+ var boxes = page.Fragments.Select(f => (f.Left, f.Top, f.Right, f.Bottom))+ .Concat(page.Rules.Select(r => r.Horizontal ? (r.Start, r.Position, r.End, r.Position) : (r.Position, r.Start, r.Position, r.End)))+ .Concat(page.Pictures.Select(p => (p.Left, p.Top, p.Right, p.Bottom)));+ foreach (var (l, t, r, b) in boxes)+ {+ left = Math.Min(left, l);+ top = Math.Min(top, t);+ right = Math.Min(right, page.Width - r);+ bottom = Math.Min(bottom, page.Height - b);+ }+ }+ static double Clamp(double value) => value == double.MaxValue ? 20 : Math.Clamp(value, MinMargin, MaxMargin);+ return (Clamp(left), Clamp(top), Clamp(right), Clamp(bottom / 2));+ }++ /// <summary>The blocks of one page in reading order; floating pictures go into the first paragraph.</summary>+ private List<HBlock> PageBlocks(PageContent page, double containerLeft, double containerRight, double marginTop)+ {+ var fragments = Deduplicated(page.Fragments);+ var items = new List<Placed>();+ foreach (var table in RuledTables(page, fragments))+ items.Add(new Placed(table.Top, table.Bottom, Table: table));+ foreach (var paragraph in Paragraphs(Lines(fragments), containerLeft, containerRight))+ items.Add(new Placed(TextTop(paragraph), TextBottom(paragraph), Lines: paragraph));++ var floating = new List<HImage>();+ foreach (var picture in page.Pictures.OrderBy(p => p.Top))+ {+ if (Extract(picture.Part) is not { } file)+ continue;+ var image = new HImage(file) { Width = Hwp(picture.Width), Height = Hwp(picture.Height) };+ if (items.Any(i => i.Top < picture.Bottom - 0.5 && i.Bottom > picture.Top + 0.5))+ {+ image.Anchor = new HAnchor("PAPER", "LEFT", Hwp(picture.Left), "PAPER", "TOP", Hwp(picture.Top), "IN_FRONT_OF_TEXT", AllowOverlap: true);+ floating.Add(image);+ }+ else+ {+ items.Add(new Placed(picture.Top, picture.Bottom, Image: image, Left: picture.Left));+ }+ }++ var blocks = new List<HBlock>();+ var above = marginTop;+ foreach (var item in items.OrderBy(i => i.Top))+ {+ var before = Math.Clamp(item.Top - above, 0, 100);+ if (item.Table is { } table)+ {+ blocks.Add(TableBlock(table, containerLeft));+ }+ else if (item.Image is { } image)+ {+ var paragraph = new HParagraph();+ var left = Hwp(item.Left - containerLeft);+ var centered = Math.Abs(left + image.Width!.Value / 2 - Hwp(containerRight - containerLeft) / 2) < Hwp(3);+ paragraph.Format = new HParaFormat(Align: centered ? HAlign.Center : HAlign.Left, Left: centered || left < Hwp(1) ? null : left,+ Before: Hwp(before), After: 0, LineSpacing: new HLineSpacing(HLineSpacingKind.Percent, 100));+ paragraph.Inlines.Add(image);+ blocks.Add(paragraph);+ }+ else+ {+ blocks.Add(TextParagraph(item.Lines!, containerLeft, containerRight, Hwp(before)));+ }+ above = Math.Max(above, item.Bottom);+ }++ if (floating.Count > 0)+ {+ if (blocks.Count == 0 || blocks[0] is not HParagraph)+ blocks.Insert(0, new HParagraph { MarkFormat = new HCharFormat(Size: 100) });+ ((HParagraph)blocks[0]).Inlines.InsertRange(0, floating);+ }+ return blocks;+ }++ /// <summary>The same text drawn twice at one place (fake bold, a label in both the template and the page) once.</summary>+ private static List<Fragment> Deduplicated(List<Fragment> fragments)+ {+ var seen = new HashSet<(string, long, long)>();+ return fragments.Where(f => seen.Add((f.Text, (long)Math.Round(f.X * 3), (long)Math.Round(f.Baseline * 3)))).ToList();+ }++ // ───────────────────────── Lines ─────────────────────────++ /// <summary>Fragments into lines: one baseline (within a fraction of the font size), ordered left to right.</summary>+ private static List<Line> Lines(IEnumerable<Fragment> fragments)+ {+ var lines = new List<Line>();+ foreach (var fragment in fragments.OrderBy(f => f.Baseline).ThenBy(f => f.X))+ {+ var line = fragment.Vertical ? null+ : lines.TakeLast(4).LastOrDefault(l => !l.Vertical && Math.Abs(l.Baseline - fragment.Baseline) <= 0.4 * Math.Min(l.Size, fragment.Size));+ if (line is null)+ lines.Add(new Line(fragment));+ else+ line.Fragments.Add(fragment);+ }+ lines = [.. lines.OrderBy(l => l.Fragments.Min(f => f.Top))];+ foreach (var line in lines)+ {+ line.Fragments.Sort((a, b) => a.X.CompareTo(b.X));+ for (var i = 1; i < line.Fragments.Count; i++)+ {+ var (previous, fragment) = (line.Fragments[i - 1], line.Fragments[i]);+ if (fragment.Left - previous.Right >= Math.Max(1.5 * fragment.Size, 2))+ line.Tabs.Add(i);+ }+ }+ JoinWrappedCells(lines);+ return lines;+ }++ private static readonly Regex Amount = new(@"^[-+¥¥$€]?[\d,.]+%?$", RegexOptions.CultureInvariant);++ /// <summary>+ /// The wrapped ends of cells in a row (转印组 / 件套装 in an invoice's item list): a line right under a tabbed row,+ /// whose parts all start in that row's columns and are no amounts, belongs to the row — a new row always brings its+ /// own amounts. It stays a line of its own in the row's paragraph (joined, the longer text would push the row's+ /// columns apart).+ /// </summary>+ private static void JoinWrappedCells(List<Line> lines)+ {+ for (var i = 1; i < lines.Count; i++)+ {+ var (row, wrapped) = (lines[i - 1], lines[i]);+ var above = row.Wrapped.Count > 0 ? row.Wrapped[^1].Fragment.Baseline : row.Baseline;+ if (row.Tabs.Count < 2 || wrapped.Fragments.Count >= row.Fragments.Count || row.Vertical || wrapped.Vertical+ || !row.Fragments.Any(f => Amount.IsMatch(f.Text)) || wrapped.Fragments.Any(f => Amount.IsMatch(f.Text))+ || wrapped.Baseline - above > 2.2 * wrapped.Size)+ {+ continue;+ }+ var columns = wrapped.Fragments.Select(f => row.Fragments.FindIndex(c => Math.Abs(c.Left - f.Left) < 1.5)).ToList();+ if (columns.Any(c => c < 0 || c > 0 && !row.Tabs.Contains(c)) || columns.Distinct().Count() != columns.Count)+ continue;+ row.Wrapped.AddRange(wrapped.Fragments.Zip(columns));+ lines.RemoveAt(i--);+ }+ }++ // ───────────────────────── Paragraphs ─────────────────────────++ /// <summary>+ /// Lines into paragraphs: a line continues the paragraph above when that one filled the measure (ran to the+ /// right edge from at least half-way), the size and line distance match and it starts no further right than the+ /// paragraph's body (the first line may be indented).+ /// </summary>+ private static List<List<Line>> Paragraphs(List<Line> lines, double containerLeft, double containerRight)+ {+ var paragraphs = new List<List<Line>>();+ foreach (var line in lines)+ {+ var current = paragraphs.LastOrDefault();+ if (current is not null && Continues(current, line, containerLeft, containerRight))+ current.Add(line);+ else+ paragraphs.Add([line]);+ }+ return paragraphs;+ }++ private static bool Continues(List<Line> paragraph, Line line, double containerLeft, double containerRight)+ {+ var last = paragraph[^1];+ var size = last.Size;+ if (last.Tabs.Count > 0 || line.Tabs.Count > 0 || last.Vertical || line.Vertical || Math.Abs(line.Size - size) > 0.15 * size)+ return false;+ var pitch = line.Baseline - last.Baseline;+ if (pitch < 0.9 * size || pitch > 2.5 * size || paragraph.Count > 1 && Math.Abs(pitch - (last.Baseline - paragraph[^2].Baseline)) > 0.25 * size)+ return false;+ var body = paragraph.Count > 1 ? paragraph.Skip(1).Min(l => l.Left) : paragraph[0].Left;+ if (last.Right < containerRight - 2.5 * size || last.Right - Math.Min(body, last.Left) < 0.5 * (containerRight - containerLeft))+ return false;+ return line.Left <= body + 0.6 * size && line.Left >= body - 4 * size;+ }++ /// <summary>Line distance of a paragraph: its baseline pitch (also to wrapped cell ends), or 1.2 times the font size.</summary>+ private static double LineHeight(List<Line> lines)+ {+ var size = lines[0].Size;+ var wrapped = lines[0].Wrapped.Select(w => w.Fragment.Baseline).Distinct().Count();+ var pitch = lines.Count > 1 ? (lines[^1].Baseline - lines[0].Baseline) / (lines.Count - 1)+ : wrapped > 0 ? (lines[0].LastBaseline - lines[0].Baseline) / wrapped+ : size * 1.2;+ return Math.Clamp(pitch, size, size * 3);+ }++ /// <summary>Top of a paragraph's first line box (Word puts the extra line distance above the text).</summary>+ private static double TextTop(List<Line> lines) =>+ lines[0].Vertical ? lines[0].Fragments[0].Top : lines[0].Baseline - (LineHeight(lines) - 0.25 * lines[0].Size);++ private static double TextBottom(List<Line> lines) => lines[^1].LastBaseline + 0.25 * lines[^1].Size;++ /// <param name="exact">Exact line distance (table cells, whose rows must keep their height); else "at least".</param>+ private static HParagraph TextParagraph(List<Line> lines, double containerLeft, double containerRight, int before, bool exact = false)+ {+ var size = lines[0].Size;+ var width = Math.Max(1, containerRight - containerLeft);+ var leftGap = lines[0].Left - containerLeft;+ var rightGap = containerRight - lines.Max(l => l.Right);+ var tabbed = lines.Any(l => l.Tabs.Count > 0);++ HAlign align;+ if (lines.Count == 1 && !tabbed && Math.Abs(leftGap - rightGap) < Math.Max(1.5, width * 0.03) && leftGap > Math.Max(3, width * 0.05))+ align = HAlign.Center;+ else if (lines.Count == 1 && !tabbed && rightGap < 1.5 && leftGap > width * 0.2)+ align = HAlign.Right;+ else if (lines.Count > 1)+ align = HAlign.Justify;+ else+ align = HAlign.Left;++ int? left = null, firstLine = null;+ if (align is HAlign.Left or HAlign.Justify)+ {+ var body = (lines.Count > 1 ? lines.Skip(1).Min(l => l.Left) : lines[0].Left) - containerLeft;+ if (body > 0.5)+ left = Hwp(body);+ var first = lines[0].Left - containerLeft - Math.Max(0, body);+ if (Math.Abs(first) > 0.5)+ firstLine = Hwp(first);+ }++ // A tabbed row: a left tab stop where each part starts on the page.+ var tabs = lines.SelectMany(l => l.Tabs.Select(t => Hwp(l.Fragments[t].Left - containerLeft))).Distinct().Order()+ .Select(position => new HTabStop(position, HTabKind.Left, "NONE")).ToList();++ var paragraph = new HParagraph+ {+ Format = new HParaFormat(+ Align: align,+ Left: left,+ FirstLine: firstLine,+ Tabs: tabs.Count > 0 ? tabs : null,+ Before: before,+ After: 0,+ LineSpacing: new HLineSpacing(exact ? HLineSpacingKind.Fixed : HLineSpacingKind.AtLeast, Hwp(LineHeight(lines)))),+ MarkFormat = new HCharFormat(Size: lines[0].Fragments[0].Format.Size),+ };+ Runs(lines, paragraph.Inlines);+ return paragraph;+ }++ /// <summary>+ /// The text of a paragraph: fragments joined into runs of one format, a space where the page leaves one (and at+ /// line ends, except next to Chinese text), a tab before the parts of a tabbed row; wrapped cell ends after a line+ /// break, tabbed to their columns.+ /// </summary>+ private static void Runs(List<Line> lines, List<HInline> output)+ {+ var pieces = new List<(string Text, HCharFormat Format)>();+ void Space()+ {+ if (pieces.Count > 0 && pieces[^1].Text is not ("\t" or "\n") && !pieces[^1].Text.EndsWith(' '))+ pieces[^1] = (pieces[^1].Text + " ", pieces[^1].Format);+ }+ for (var l = 0; l < lines.Count; l++)+ {+ var line = lines[l];+ for (var i = 0; i < line.Fragments.Count; i++)+ {+ var fragment = line.Fragments[i];+ if (i > 0 && line.Tabs.Contains(i))+ {+ pieces.Add(("\t", fragment.Format));+ }+ else if (i > 0)+ {+ var previous = line.Fragments[i - 1];+ var gap = fragment.Left - previous.Right;+ if (gap > 0.5 * fragment.Size || gap > 0.2 * fragment.Size && !IsWide(previous.Text[^1]) && !IsWide(fragment.Text[0]))+ Space();+ }+ else if (l > 0 && pieces.Count > 0 && !IsWide(pieces[^1].Text[^1]) && !IsWide(fragment.Text[0]))+ {+ Space();+ }+ pieces.Add((fragment.Text, fragment.Format));+ }++ // Wrapped cell ends, a line per baseline: column k's tab stop is the row's n-th tab.+ foreach (var wrappedLine in line.Wrapped.GroupBy(w => w.Fragment.Baseline))+ {+ pieces.Add(("\n", wrappedLine.First().Fragment.Format));+ var stop = 0;+ foreach (var (fragment, column) in wrappedLine.OrderBy(w => w.Column))+ {+ for (var target = line.Tabs.Count(t => t <= column); stop < target; stop++)+ pieces.Add(("\t", fragment.Format));+ pieces.Add((fragment.Text, fragment.Format));+ }+ }+ }++ foreach (var (text, format) in pieces)+ {+ if (text == "\t")+ output.Add(new HTab(format));+ else if (text == "\n")+ output.Add(new HLineBreak(format));+ else if (output.Count > 0 && output[^1] is HText run && run.GetType() == typeof(HText) && run.Format == format)+ output[^1] = new HText(run.Text + text, format);+ else+ output.Add(new HText(text, format));+ }+ }+}diff --git a/src/Filee.Engines/Ofd/OfdReader.Tables.cs b/src/Filee.Engines/Ofd/OfdReader.Tables.csnew file mode 100644index 00000000..35d0b04f--- /dev/null+++ b/src/Filee.Engines/Ofd/OfdReader.Tables.cs@@ -0,0 +1,493 @@+// Ruled tables for OfdReader: grids drawn with lines become real tables — the frame of an e-invoice (buyer and+// seller blocks, the item list, totals, remarks) and the forms of official documents.+//+// The same approach as the PDF reader's (PdfDocumentReader.Tables), in millimetres and with y growing downwards:+// path objects give the rules (stroked straight segments, thin filled rectangles), rules on one line are joined,+// rules that touch form a grid, the grid's lines are the column and row edges, and units without a rule between them+// merge into one cell. Text goes into the cell its first character is in; each cell's text is laid out like the+// page (lines, tabbed rows, paragraphs). Conservative: a grid needs 2 rows and 2 columns, cells must be rectangles+// and at least two hold text; anything else stays text in reading order.++using System.Xml.Linq;+using Filee.Engines.Hwp.Hwpx;++namespace Filee.Engines.Ofd;++internal sealed partial class OfdReader+{+ /// <summary>Thickest line (mm) still taken for a rule; thicker filled rectangles are shading.</summary>+ private const double MaxRuleThickness = 1.5;++ /// <summary>Shortest rule (mm): shorter strokes are glyph parts, ticks and QR code modules.</summary>+ private const double MinRuleLength = 1.5;++ /// <summary>Rules this close (mm) across their direction lie on one line.</summary>+ private const double SameLine = 0.5;++ /// <summary>Gap (mm) along a line that still joins two rules, and the reach of a rule to one it touches.</summary>+ private const double RuleGap = 0.9;++ /// <summary>Grid lines this close (mm) are one edge (double rules, a frame drawn twice).</summary>+ private const double EdgeTolerance = 1.0;++ /// <summary>Pages with more straight segments than this are drawings, not forms; their tables are not looked for.</summary>+ private const int MaxSegments = 5000;++ /// <summary>A straight rule: horizontal (Position is y, Start..End is x) or vertical (Position is x, Start..End is y).</summary>+ private sealed record Rule(bool Horizontal, double Position, double Start, double End, double Thickness, string Color)+ {+ public double Length => End - Start;+ }++ /// <summary>A filled rectangle that may shade a cell.</summary>+ private sealed record Shade(double Left, double Top, double Right, double Bottom, string Color);++ private sealed class RuledCell(int row, int column, int rowSpan, int columnSpan, double left, double top, double right, double bottom)+ {+ public int Row { get; } = row;+ public int Column { get; } = column;+ public int RowSpan { get; } = rowSpan;+ public int ColumnSpan { get; } = columnSpan;+ public double Left { get; } = left;+ public double Top { get; } = top;+ public double Right { get; } = right;+ public double Bottom { get; } = bottom;+ public List<Fragment> Fragments { get; } = [];+ public HBorders Borders { get; set; } = HBorders.Empty;+ public string? Fill { get; set; }+ }++ private sealed class RuledTable(double[] columns, double[] rows, List<RuledCell> cells)+ {+ /// <summary>Column edges left to right (one more than columns).</summary>+ public double[] Columns { get; } = columns;++ /// <summary>Row edges top to bottom (one more than rows).</summary>+ public double[] Rows { get; } = rows;++ public List<RuledCell> Cells { get; } = cells;+ public double Left => Columns[0];+ public double Right => Columns[^1];+ public double Top => Rows[0];+ public double Bottom => Rows[^1];+ }++ // ───────────────────────── Paths ─────────────────────────++ /// <summary>The rules and shading rectangles a path object draws.</summary>+ private static void PathObject(XElement element, Resources res, PageContent page, string? layerDraw)+ {+ if (page.Segments > MaxSegments || Child(element, "AbbreviatedData")?.Value is not { Length: > 0 } data)+ return;+ var box = Box(Attr(element, "Boundary")) ?? default;+ var ctm = Matrix.Parse(Attr(element, "CTM"));+ var own = res.Draw(Attr(element, "DrawParam"));+ var layer = res.Draw(layerDraw);+ var stroke = Attr(element, "Stroke") != "false"+ ? ColorOf(Child(element, "StrokeColor")) ?? own.Stroke ?? layer.Stroke ?? "#000000"+ : null;+ // Without a colour a fill is transparent (the standard's default).+ var fill = Attr(element, "Fill") == "true" ? ColorOf(Child(element, "FillColor")) ?? own.Fill ?? layer.Fill : null;+ var lineWidth = (Number(Attr(element, "LineWidth")) ?? own.LineWidth ?? layer.LineWidth ?? 0.353) * (ctm.ScaleX + ctm.ScaleY) / 2;++ (double X, double Y) Point(double x, double y)+ {+ var (px, py) = ctm.Apply(x, y);+ return (box.X + px, box.Y + py);+ }++ var tokens = data.Split([' ', '\t', '\r', '\n', ','], StringSplitOptions.RemoveEmptyEntries);+ var lines = new List<((double X, double Y) From, (double X, double Y) To)>();+ var curved = false;+ (double X, double Y)? start = null, current = null;+ void Flush()+ {+ AddRules(page, lines, curved, stroke, fill, lineWidth);+ lines.Clear();+ curved = false;+ }+ double At(int i) => i < tokens.Length ? Number(tokens[i]) ?? 0 : 0;++ for (var i = 0; i < tokens.Length && page.Segments <= MaxSegments;)+ {+ switch (tokens[i])+ {+ case "S" or "M":+ Flush();+ start = current = Point(At(i + 1), At(i + 2));+ i += 3;+ break;+ case "L":+ var to = Point(At(i + 1), At(i + 2));+ if (current is { } from)+ lines.Add((from, to));+ start ??= to;+ current = to;+ i += 3;+ break;+ case "Q":+ curved = true;+ current = Point(At(i + 3), At(i + 4));+ i += 5;+ break;+ case "B":+ curved = true;+ current = Point(At(i + 5), At(i + 6));+ i += 7;+ break;+ case "A":+ curved = true;+ current = Point(At(i + 6), At(i + 7));+ i += 8;+ break;+ case "C":+ if (current is { } last && start is { } first)+ lines.Add((last, first));+ current = start;+ i++;+ break;+ default:+ i++;+ break;+ }+ }+ Flush();+ }++ private static void AddRules(PageContent page, List<((double X, double Y) From, (double X, double Y) To)> lines, bool curved,+ string? stroke, string? fill, double lineWidth)+ {+ page.Segments += lines.Count;+ if (lines.Count == 0 || page.Segments > MaxSegments)+ return;++ if (stroke is not null && !IsWhite(stroke))+ {+ var thickness = Math.Max(0.05, lineWidth);+ foreach (var (from, to) in lines)+ {+ if (Math.Abs(from.Y - to.Y) <= 0.2 && Math.Abs(from.X - to.X) >= MinRuleLength)+ page.Rules.Add(new Rule(true, (from.Y + to.Y) / 2, Math.Min(from.X, to.X), Math.Max(from.X, to.X), thickness, stroke));+ else if (Math.Abs(from.X - to.X) <= 0.2 && Math.Abs(from.Y - to.Y) >= MinRuleLength)+ page.Rules.Add(new Rule(false, (from.X + to.X) / 2, Math.Min(from.Y, to.Y), Math.Max(from.Y, to.Y), thickness, stroke));+ }+ }++ // A filled shape of straight, upright edges: a thin one is a rule, a larger one may shade a cell.+ if (fill is null || curved || lines.Count < 3 || IsWhite(fill)+ || !lines.All(l => Math.Abs(l.From.X - l.To.X) <= 0.2 || Math.Abs(l.From.Y - l.To.Y) <= 0.2))+ return;+ var left = lines.Min(l => Math.Min(l.From.X, l.To.X));+ var right = lines.Max(l => Math.Max(l.From.X, l.To.X));+ var top = lines.Min(l => Math.Min(l.From.Y, l.To.Y));+ var bottom = lines.Max(l => Math.Max(l.From.Y, l.To.Y));+ var (width, height) = (right - left, bottom - top);+ if (height <= MaxRuleThickness && width >= MinRuleLength && width > 2 * height)+ page.Rules.Add(new Rule(true, (top + bottom) / 2, left, right, Math.Max(0.05, height), fill));+ else if (width <= MaxRuleThickness && height >= MinRuleLength && height > 2 * width)+ page.Rules.Add(new Rule(false, (left + right) / 2, top, bottom, Math.Max(0.05, width), fill));+ else if (width > MaxRuleThickness && height > MaxRuleThickness)+ page.Shades.Add(new Shade(left, top, right, bottom, fill));+ }++ private static bool IsWhite(string color) =>+ Convert.ToInt32(color[1..3], 16) >= 242 && Convert.ToInt32(color[3..5], 16) >= 242 && Convert.ToInt32(color[5..7], 16) >= 242;++ /// <summary>Rules on one line that overlap or nearly touch become one rule (cells drawn one by one share edges).</summary>+ private static List<Rule> JoinRules(List<Rule> rules)+ {+ var result = new List<Rule>();+ foreach (var direction in rules.GroupBy(r => r.Horizontal))+ {+ var sorted = direction.OrderBy(r => r.Position).ToList();+ for (var i = 0; i < sorted.Count;)+ {+ var j = i + 1;+ while (j < sorted.Count && sorted[j].Position - sorted[j - 1].Position <= SameLine)+ j++;+ Rule? current = null;+ foreach (var rule in sorted[i..j].OrderBy(r => r.Start))+ {+ if (current is not null && rule.Start <= current.End + RuleGap)+ {+ current = current with+ {+ End = Math.Max(current.End, rule.End),+ Thickness = Math.Max(current.Thickness, rule.Thickness),+ Position = rule.Length > current.Length ? rule.Position : current.Position,+ Color = rule.Length > current.Length ? rule.Color : current.Color,+ };+ }+ else+ {+ if (current is not null)+ result.Add(current);+ current = rule;+ }+ }+ result.Add(current!);+ i = j;+ }+ }+ return result;+ }++ // ───────────────────────── Grids ─────────────────────────++ /// <summary>The ruled tables of a page, largest first; the fragments in their cells are taken out of <paramref name="fragments"/>.</summary>+ private static List<RuledTable> RuledTables(PageContent page, List<Fragment> fragments)+ {+ var tables = new List<RuledTable>();+ if (page.Segments > MaxSegments || page.Rules.Count < 4)+ return tables;+ var rules = JoinRules(page.Rules);+ foreach (var group in Grids(rules).Select(g => (Rules: g, Extent: Extent(g))).OrderByDescending(g => Area(g.Extent)))+ {+ if (tables.Any(t => Overlap(t.Left, t.Right, group.Extent.Left, group.Extent.Right) > EdgeTolerance+ && Overlap(t.Top, t.Bottom, group.Extent.Top, group.Extent.Bottom) > EdgeTolerance))+ continue;+ if (Table(group.Rules, group.Extent, fragments, page.Shades) is not { } table)+ continue;+ tables.Add(table);+ var taken = table.Cells.SelectMany(c => c.Fragments).ToHashSet();+ fragments.RemoveAll(taken.Contains);+ }+ return tables;+ }++ /// <summary>Groups of rules that touch each other (a horizontal and a vertical rule crossing or meeting).</summary>+ private static IEnumerable<List<Rule>> Grids(List<Rule> rules)+ {+ var parent = Enumerable.Range(0, rules.Count).ToArray();+ int Find(int i) => parent[i] == i ? i : parent[i] = Find(parent[i]);+ for (var a = 0; a < rules.Count; a++)+ {+ if (!rules[a].Horizontal)+ continue;+ for (var b = 0; b < rules.Count; b++)+ {+ if (!rules[b].Horizontal && Touch(rules[a], rules[b]))+ parent[Find(a)] = Find(b);+ }+ }+ return Enumerable.Range(0, rules.Count).GroupBy(Find).Select(g => g.Select(i => rules[i]).ToList())+ .Where(g => g.Any(r => r.Horizontal) && g.Any(r => !r.Horizontal) && g.Count >= 4);+ }++ private static bool Touch(Rule horizontal, Rule vertical)+ {+ var reach = RuleGap + Math.Max(horizontal.Thickness, vertical.Thickness) / 2;+ return vertical.Position >= horizontal.Start - reach && vertical.Position <= horizontal.End + reach+ && horizontal.Position >= vertical.Start - reach && horizontal.Position <= vertical.End + reach;+ }++ /// <summary>The box of a grid: its outer rules, or further out where most rules of the other direction reach.</summary>+ private static (double Left, double Top, double Right, double Bottom) Extent(List<Rule> group)+ {+ var horizontal = group.Where(r => r.Horizontal).ToList();+ var vertical = group.Where(r => !r.Horizontal).ToList();+ var left = Math.Min(vertical.Min(r => r.Position), Median(horizontal.Select(r => r.Start)));+ var right = Math.Max(vertical.Max(r => r.Position), Median(horizontal.Select(r => r.End)));+ var top = Math.Min(horizontal.Min(r => r.Position), Median(vertical.Select(r => r.Start)));+ var bottom = Math.Max(horizontal.Max(r => r.Position), Median(vertical.Select(r => r.End)));+ return (left, top, right, bottom);+ }++ private static double Median(IEnumerable<double> values)+ {+ var sorted = values.Order().ToList();+ return sorted.Count == 0 ? 0 : sorted[sorted.Count / 2];+ }++ private static double Area((double Left, double Top, double Right, double Bottom) box) => (box.Right - box.Left) * (box.Bottom - box.Top);++ private static double Overlap(double a0, double a1, double b0, double b1) => Math.Min(a1, b1) - Math.Max(a0, b0);++ /// <summary>Positions closer than <see cref="EdgeTolerance"/> merged into one (their mean), sorted.</summary>+ private static List<double> Edges(IEnumerable<double> positions)+ {+ var result = new List<List<double>>();+ foreach (var position in positions.Order())+ {+ if (result.Count > 0 && position - result[^1][^1] <= EdgeTolerance)+ result[^1].Add(position);+ else+ result.Add([position]);+ }+ return result.Select(g => g.Average()).ToList();+ }++ /// <summary>The rule covering most of a segment on the line at <paramref name="position"/>; null when rules cover less than half.</summary>+ private static Rule? Covering(List<Rule> rules, double position, double from, double to)+ {+ var length = to - from;+ if (length <= 0)+ return null;+ var covered = 0.0;+ Rule? best = null;+ var bestOverlap = 0.0;+ foreach (var rule in rules)+ {+ if (Math.Abs(rule.Position - position) > EdgeTolerance + rule.Thickness / 2)+ continue;+ var overlap = Math.Min(to, rule.End) - Math.Max(from, rule.Start);+ if (overlap <= 0)+ continue;+ covered += overlap;+ if (overlap > bestOverlap)+ (best, bestOverlap) = (rule, overlap);+ }+ return covered >= 0.5 * length ? best : null;+ }++ /// <summary>The table a grid of rules draws, with the fragments in its cells; null when it does not look like one.</summary>+ private static RuledTable? Table(List<Rule> group, (double Left, double Top, double Right, double Bottom) extent,+ List<Fragment> fragments, List<Shade> shades)+ {+ var horizontal = group.Where(r => r.Horizontal).ToList();+ var vertical = group.Where(r => !r.Horizontal).ToList();+ var xs = Edges(vertical.Select(r => r.Position).Where(x => x > extent.Left && x < extent.Right).Append(extent.Left).Append(extent.Right));+ var ys = Edges(horizontal.Select(r => r.Position).Where(y => y > extent.Top && y < extent.Bottom).Append(extent.Top).Append(extent.Bottom));++ if ((xs.Count - 1) * (ys.Count - 1) > 2500)+ return null; // a drawing (hatching, a chart's grid), not a form++ // Grid lines that separate no two units anywhere (a rule too short to bound a cell) are dropped.+ bool VerticalEdge(int c, int r) => Covering(vertical, xs[c], ys[r], ys[r + 1]) is not null;+ bool HorizontalEdge(int r, int c) => Covering(horizontal, ys[r], xs[c], xs[c + 1]) is not null;+ while (true)+ {+ var column = Enumerable.Range(1, Math.Max(0, xs.Count - 2)).FirstOrDefault(c => !Enumerable.Range(0, ys.Count - 1).Any(r => VerticalEdge(c, r)));+ if (column > 0)+ {+ xs.RemoveAt(column);+ continue;+ }+ var row = Enumerable.Range(1, Math.Max(0, ys.Count - 2)).FirstOrDefault(r => !Enumerable.Range(0, xs.Count - 1).Any(c => HorizontalEdge(r, c)));+ if (row == 0)+ break;+ ys.RemoveAt(row);+ }+ var (rows, columns) = (ys.Count - 1, xs.Count - 1);+ if (rows < 2 || columns < 2 || rows * columns > 2500)+ return null;++ // Units of the grid joined where no rule separates them; each group must be a rectangle (a cell).+ var owner = new int[rows, columns];+ var parent = Enumerable.Range(0, rows * columns).ToArray();+ int Find(int i) => parent[i] == i ? i : parent[i] = Find(parent[i]);+ for (var r = 0; r < rows; r++)+ {+ for (var c = 0; c < columns; c++)+ {+ if (c + 1 < columns && !VerticalEdge(c + 1, r))+ parent[Find(r * columns + c)] = Find(r * columns + c + 1);+ if (r + 1 < rows && !HorizontalEdge(r + 1, c))+ parent[Find(r * columns + c)] = Find((r + 1) * columns + c);+ }+ }+ var cells = new List<RuledCell>();+ foreach (var unit in Enumerable.Range(0, rows * columns).GroupBy(Find))+ {+ var (top, bottom) = (unit.Min(u => u / columns), unit.Max(u => u / columns));+ var (left, right) = (unit.Min(u => u % columns), unit.Max(u => u % columns));+ if ((bottom - top + 1) * (right - left + 1) != unit.Count())+ return null; // an L-shaped region: not a table cell+ foreach (var u in unit)+ owner[u / columns, u % columns] = cells.Count;+ cells.Add(new RuledCell(top, left, bottom - top + 1, right - left + 1, xs[left], ys[top], xs[right + 1], ys[bottom + 1]));+ }+ if (cells.Count < 4 && (cells.Select(c => c.Row).Distinct().Count() < 2 || cells.Select(c => c.Column).Distinct().Count() < 2))+ return null;++ // Fragments by their first character (a width estimated without DeltaX may reach past the cell). Many rules+ // through the middle of text mean a chart or crossed-out text, not a table.+ var crossed = 0;+ var inside = 0;+ foreach (var fragment in fragments)+ {+ var x = fragment.Left + Math.Min(fragment.Size, fragment.Width) / 2;+ var y = fragment.Vertical ? (fragment.Top + fragment.Bottom) / 2 : fragment.Baseline - 0.35 * fragment.Size;+ if (x <= xs[0] || x >= xs[^1] || y <= ys[0] || y >= ys[^1])+ continue;+ inside++;+ if (horizontal.Any(h => h.Position > fragment.Top + 0.3 * fragment.Size && h.Position < fragment.Baseline - 0.2 * fragment.Size+ && h.Start < fragment.Right - fragment.Size && h.End > fragment.Left + fragment.Size))+ crossed++;+ var column = Math.Clamp(xs.FindLastIndex(e => e <= x), 0, columns - 1);+ var row = Math.Clamp(ys.FindLastIndex(e => e <= y), 0, rows - 1);+ cells[owner[row, column]].Fragments.Add(fragment);+ }+ if (crossed > Math.Max(1, inside / 10) || cells.Count(c => c.Fragments.Count > 0) < 2)+ return null;++ foreach (var cell in cells)+ {+ cell.Borders = new HBorders(+ Border(Covering(vertical, cell.Left, cell.Top, cell.Bottom)),+ Border(Covering(vertical, cell.Right, cell.Top, cell.Bottom)),+ Border(Covering(horizontal, cell.Top, cell.Left, cell.Right)),+ Border(Covering(horizontal, cell.Bottom, cell.Left, cell.Right)));+ cell.Fill = shades.LastOrDefault(s => Math.Max(0, Overlap(s.Left, s.Right, cell.Left, cell.Right)) * Math.Max(0, Overlap(s.Top, s.Bottom, cell.Top, cell.Bottom))+ >= 0.8 * (cell.Right - cell.Left) * (cell.Bottom - cell.Top)+ && s.Right - s.Left < 1.5 * (cell.Right - cell.Left) + 2 && s.Bottom - s.Top < 1.5 * (cell.Bottom - cell.Top) + 2)?.Color;+ }+ return new RuledTable([.. xs], [.. ys], cells);+ }++ private static HBorder Border(Rule? rule) =>+ rule is null ? HBorder.None : new HBorder(HBorderStyle.Solid, Math.Max(0.1, rule.Thickness), rule.Color);++ // ───────────────────────── Building ─────────────────────────++ /// <summary>+ /// The table of a grid: column widths and row heights from the page, each cell's text laid out like the page+ /// (tabbed rows keep their columns), borders and shading per cell.+ /// </summary>+ private static HTable TableBlock(RuledTable grid, double containerLeft)+ {+ const double Padding = 0.5;+ var table = new HTable+ {+ ColumnCount = grid.Columns.Length - 1,+ ColumnWidths = [.. grid.Columns.Zip(grid.Columns.Skip(1), (a, b) => Hwp(b - a))],+ Borders = HBorders.Empty,+ CellMargin = new HInsets(Hwp(Padding), Hwp(Padding), 0, 0),+ };+ if (grid.Left - containerLeft > 0.5)+ table.Indent = Hwp(grid.Left - containerLeft);++ for (var r = 0; r < grid.Rows.Length - 1; r++)+ table.Rows.Add(new HRow { Height = Hwp(grid.Rows[r + 1] - grid.Rows[r]) });+ foreach (var cell in grid.Cells.OrderBy(c => c.Row).ThenBy(c => c.Column))+ {+ var hcell = new HCell+ {+ Column = cell.Column,+ RowSpan = cell.RowSpan,+ ColSpan = cell.ColumnSpan,+ Borders = cell.Borders,+ Fill = cell.Fill,+ };+ if (cell.Fragments.Count > 0)+ {+ var (left, right) = (cell.Left + Padding, cell.Right - Padding);+ var paragraphs = Paragraphs(Lines(cell.Fragments), left, right);+ var above = TextTop(paragraphs[0]);+ foreach (var paragraph in paragraphs)+ {+ var before = hcell.Blocks.Count == 0 ? 0 : Math.Clamp(TextTop(paragraph) - above, 0, 50);+ hcell.Blocks.Add(TextParagraph(paragraph, left, right, Hwp(before), exact: true));+ above = TextBottom(paragraph);+ }+ // Text about as far from the top as from the bottom is centred; text at the bottom stays there.+ var space = (Top: TextTop(paragraphs[0]) - cell.Top, Bottom: cell.Bottom - TextBottom(paragraphs[^1]));+ hcell.VerticalAlign = space.Top > 1 && Math.Abs(space.Top - space.Bottom) <= Math.Max(1, 0.25 * (space.Top + space.Bottom)) ? HVerticalAlign.Center+ : space.Bottom < 0.4 * space.Top && space.Top > 2 ? HVerticalAlign.Bottom+ : HVerticalAlign.Top;+ }+ table.Rows[cell.Row].Cells.Add(hcell);+ }+ return table;+ }+}diff --git a/src/Filee.Engines/Ofd/OfdReader.cs b/src/Filee.Engines/Ofd/OfdReader.csindex 9d001165..4414399b 100644--- a/src/Filee.Engines/Ofd/OfdReader.cs+++ b/src/Filee.Engines/Ofd/OfdReader.cs@@ -1,14 +1,23 @@// OFD (GB/T 33190-2016, the Chinese standard for fixed-layout documents: e-invoices, contracts, official// documents) → HDocument with no external engine, so OFD → DOCX / HWPX / TXT works out of the box.//-// An OFD file is a ZIP package of XML pages. Like a PDF it stores positioned text, so boxes are grouped-// into lines and lines into paragraphs (the same idea as the PDF reader, smaller scale): a line is a-// paragraph unless consecutive lines clearly continue one, and every fragment keeps its own size and-// colour. Pictures (the seals of invoices, often JBIG2 or JPEG-2000) are extracted and kept in reading-// order; ImageMagick transcodes formats Word cannot embed. Vector drawings and tables are not detected-// — their text comes out in reading order, as with scanned PDFs.--using System.IO.Compression;+// An OFD file is a ZIP package of XML: OFD.xml names the document (Document.xml), which lists the pages, the+// template pages they are drawn on and the resource files (fonts, pictures, drawing parameters). Like a PDF a page+// holds positioned text, pictures and vector paths, in millimetres from the top-left corner. Text objects are read+// with their transformation (CTM), character advances (DeltaX, also the "g" shorthand) and vertical runs (DeltaY);+// the layout (OfdReader.Layout) groups them into lines and paragraphs, and grids drawn with lines become tables+// (OfdReader.Tables) — the frame of an e-invoice. Pictures are unpacked and kept in reading order, or float at their+// place when text sits beside or under them (QR codes, seals).+//+// Three writer variants seen in the wild are handled: the standard's own structure, WPS (page size only in+// Document.xml, a Res.xml next to the pages, bold as Weight=700) and tax invoices (template pages with the labels,+// DocumentRes, the colour in a layer's DrawParam, item names wrapped onto a second line).+//+// Not converted: signatures (seals stored in Signs/ as signed data), annotations, embedded fonts (the font name is+// kept), composite objects, JBIG2 pictures. Encrypted documents (GM/T 0099 Encryptions.xml) are refused; nothing+// is decrypted. The package is read defensively (OfdPackage).++using System.Globalization;using System.Xml.Linq;using Filee.Engines.Hwp.Hwpx;using ImageMagick;@@ -16,537 +25,679 @@ using ImageMagick;namespace Filee.Engines.Ofd;/// <summary>Reads an OFD file into the document model (DOCX / HWPX writers, plain text).</summary>-internal static class OfdReader+internal sealed partial class OfdReader{- /// <summary>Millimetres → HWPUNIT (1/7200 inch).</summary>- private const double MmToUnit = 7200.0 / 25.4;+ /// <summary>Documents with more pages are refused.</summary>+ private const int MaxPages = 10_000;++ /// <summary>Text, picture and path objects of a whole document; more are refused.</summary>+ private const int MaxObjects = 2_000_000;++ /// <summary>Text runs on one page (a dense page drawn character by character has a few thousand); more are refused.</summary>+ private const int MaxFragmentsPerPage = 50_000;- /// <summary>Millimetres → font size in 1/100 pt.</summary>- private const double MmToCentiPt = 100.0 * 72.0 / 25.4;+ /// <summary>Pictures unpacked per document; further ones are left out.</summary>+ private const int MaxPictures = 2_000;- /// <summary>Smallest margin the page allows, so text never touches the paper edge (1 mm).</summary>- private const double MinMarginMm = 1.0;+ /// <summary>Largest picture decoded (pixels), against images that unpack to gigabytes.</summary>+ private const long MaxPicturePixels = 100_000_000;- /// <summary>Image extensions the writers embed as they are; anything else is transcoded to PNG.</summary>- private static readonly HashSet<string> DirectImages = ["png", "jpg", "jpeg", "gif", "bmp", "webp"];+ /// <summary>Nesting of layers and page blocks followed.</summary>+ private const int MaxDepth = 32;- /// <summary>Set by <see cref="Read"/>: the package pictures are unpacked from.</summary>- private static string? _zipPath;+ /// <summary>Default font size (mm) when a text object names none.</summary>+ private const double DefaultSize = 3.5;++ private readonly OfdPackage _package;+ private readonly string _mediaFolder;+ private readonly Dictionary<string, string?> _extracted = new(StringComparer.OrdinalIgnoreCase);+ private readonly Dictionary<string, (XElement Root, Resources Res)?> _templates = new();+ private int _objects;++ private OfdReader(OfdPackage package, string mediaFolder)+ {+ _package = package;+ _mediaFolder = mediaFolder;+ }public static HDocument Read(string path, string mediaFolder){- _zipPath = path;- using var zip = ZipFile.OpenRead(path);- var entries = zip.Entries.ToDictionary(e => Norm(e.FullName), e => e, StringComparer.OrdinalIgnoreCase);-- var root = LoadXml(entries, "OFD.xml") ?? throw new InvalidDataException("This OFD file has no OFD.xml.");- var docRoot = root.Descendants().First(d => d.Name.LocalName == "DocBody")- .Descendants().First(d => d.Name.LocalName == "DocRoot").Value.Trim();- var docDir = DirName(docRoot);- var document = LoadXml(entries, docRoot) ?? throw new InvalidDataException("This OFD file has no document root.");-- // Default page size from Document.xml/CommonData/PageArea (WPS writes it here, pages have no box of- // their own); a page's own PhysicalBox, when present, overrides it.- double defaultW = 210, defaultH = 297;- var commonData = document.Descendants().FirstOrDefault(d => d.Name.LocalName == "CommonData");- if (PageBox(commonData?.Descendants().FirstOrDefault(d => d.Name.LocalName == "PhysicalBox")?.Value) is { } box)+ using var package = new OfdPackage(path);+ return new OfdReader(package, mediaFolder).Read();+ }++ private HDocument Read()+ {+ var ofd = _package.LoadXml("OFD.xml")?.Root;+ if (ofd is null || ofd.Name.LocalName != "OFD")+ throw new InvalidDataException("The file is not an OFD document (it has no OFD.xml).");+ RefuseEncrypted(ofd);++ // A package may hold several documents; the first is read.+ var docPath = OfdPackage.Resolve("", Child(Child(ofd, "DocBody"), "DocRoot")?.Value)+ ?? throw new InvalidDataException("The OFD file names no document (DocRoot).");+ var document = _package.LoadXml(docPath)?.Root ?? throw new InvalidDataException($"The OFD package has no {docPath}.");+ var docDir = OfdPackage.DirName(docPath);+ var common = Child(document, "CommonData");+ var defaultArea = PageArea(Child(common, "PageArea")) ?? (210, 297);++ // Fonts, pictures and drawing parameters of the whole document; WPS keeps them in a Res.xml it does not name.+ var docRes = new Resources(null);+ foreach (var res in Children(common, "PublicRes").Concat(Children(common, "DocumentRes")))+ LoadRes(docRes, OfdPackage.Resolve(docDir, res.Value), docDir);+ LoadRes(docRes, OfdPackage.Resolve(docDir, "Res.xml"), docDir);++ var templates = new Dictionary<string, string>();+ foreach (var template in Children(common, "TemplatePage")){- defaultW = box.W;- defaultH = box.H;+ if (Attr(template, "ID") is { } id && PagePath(docDir, Attr(template, "BaseLoc")) is { } path)+ templates.TryAdd(id, path);}- // Fonts and pictures the document itself owns: Res.xml plus the PublicRes and DocumentRes files- // CommonData names (tax invoices keep their pictures in DocumentRes); pages fall back to these.- var docRes = LoadRes(entries, docDir, "Res.xml");- foreach (var name in new[] { "PublicRes", "DocumentRes" })- if (commonData?.Descendants().FirstOrDefault(d => d.Name.LocalName == name)?.Value.Trim() is { Length: > 0 } file)- docRes = MergeRes(LoadRes(entries, docDir, file), docRes);-- // Template pages (tax invoices): the fixed layout every page is drawn on top of.- var templates = new Dictionary<string, (string Path, XElement Root)>();- foreach (var tpl in document.Descendants().Where(d => d.Name.LocalName == "TemplatePage"))+ var pages = new List<PageContent>();+ foreach (var page in Children(Child(document, "Pages"), "Page")){- if (Attr(tpl, "ID") is not { } id || Attr(tpl, "BaseLoc") is not { Length: > 0 } loc)- continue;- var templatePath = loc.EndsWith(".xml", StringComparison.OrdinalIgnoreCase)- ? Join(docDir, loc)- : Join(docDir, loc, "Content.xml");- if (LoadXml(entries, templatePath)?.Root is { } templateRoot)- templates[id] = (templatePath, templateRoot);+ if (pages.Count == MaxPages)+ throw new InvalidDataException($"The OFD document has more than {MaxPages:N0} pages; Filee does not read it.");+ var path = PagePath(docDir, Attr(page, "BaseLoc"));+ if (_package.LoadXml(path)?.Root is { } content)+ pages.Add(ReadPage(content, path!, docDir, docRes, templates, defaultArea));}+ return Build(pages);+ }- var section = new HSection();- double pageW = defaultW, pageH = defaultH;- var firstPage = true;- var allItems = new List<Item>();- foreach (var page in document.Descendants().Where(d => d.Name.LocalName == "Page"))+ /// <summary>+ /// Encrypted OFD (GM/T 0099: an Encryptions.xml entry file, encrypted parts) is refused, never decrypted.+ /// </summary>+ private void RefuseEncrypted(XElement ofd)+ {+ if (_package.Names.Any(n => n.Equals("Encryptions.xml", StringComparison.OrdinalIgnoreCase)+ || n.EndsWith("/Encryptions.xml", StringComparison.OrdinalIgnoreCase))+ || ofd.Descendants().Any(e => e.Name.LocalName is "Encryptions" or "Encryption" or "EncryptInfo")){- // BaseLoc is a folder (the standard) or the content file itself (WPS writes Pages/Page_0/Content.xml).- var loc = Attr(page, "BaseLoc") ?? "";- var pagePath = loc.EndsWith(".xml", StringComparison.OrdinalIgnoreCase)- ? Join(docDir, loc)- : Join(docDir, loc, Attr(page, "PageFile") ?? "Content.xml");- var content = LoadXml(entries, pagePath);- if (content?.Root is null)- continue;+ throw new InvalidDataException("The OFD document is encrypted. Filee does not convert encrypted (DRM-protected) documents.");+ }+ }- // Templates the page is drawn on: their labels (发票号码:, 购买方信息) are read together with- // the page's own values, so the invoice comes out complete.- var usedTemplates = new List<(string Dir, XElement Root)>();- foreach (var use in content.Root.Descendants().Where(d => d.Name.LocalName == "Template"))- if (Attr(use, "TemplateID") is { } tid && templates.TryGetValue(tid, out var tpl))- usedTemplates.Add((DirName(tpl.Path), tpl.Root));+ /// <summary>A page or template location: the content file itself, or (some writers) its folder.</summary>+ private static string? PagePath(string docDir, string? baseLoc) =>+ OfdPackage.Resolve(docDir, baseLoc) is not { } path ? null+ : path.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) ? path+ : path + "/Content.xml";- pageW = defaultW;- pageH = defaultH;- if (PageBox(content.Root.Descendants().FirstOrDefault(d => d.Name.LocalName == "PhysicalBox")?.Value) is { } pageBox)- {- pageW = pageBox.W;- pageH = pageBox.H;- }- else if (usedTemplates.Select(t => PageBox(t.Root.Descendants().FirstOrDefault(d => d.Name.LocalName == "PhysicalBox")?.Value))- .FirstOrDefault(b => b is not null) is { } templateBox)- {- pageW = templateBox.W;- pageH = templateBox.H;- }+ // ───────────────────────── Pages ─────────────────────────- var pageDir = DirName(pagePath);- var res = MergeRes(LoadRes(entries, pageDir, "Res.xml"), docRes);- var items = new List<Item>();- foreach (var (tplDir, tplRoot) in usedTemplates)- {- var templateRes = MergeRes(LoadRes(entries, tplDir, "Res.xml"), docRes);- items.AddRange(MergeVerticalLabels(Collect(tplRoot, tplDir, templateRes, entries)));- }- items.AddRange(Collect(content.Root, pageDir, res, entries));- allItems.AddRange(items);+ /// <summary>What a page draws, in millimetres from its top-left corner.</summary>+ private sealed class PageContent+ {+ public double Width { get; set; }+ public double Height { get; set; }+ public List<Fragment> Fragments { get; } = [];+ public List<Picture> Pictures { get; } = [];+ public List<Rule> Rules { get; } = [];+ public List<Shade> Shades { get; } = [];++ /// <summary>Straight path segments seen; a page with very many is a drawing, not a form.</summary>+ public int Segments { get; set; }+ }- var firstBlockOfPage = true;- foreach (var block in Layout(items, mediaFolder))- {- if (!firstPage && firstBlockOfPage && block is HParagraph p)- p.PageBreakBefore = true;- firstBlockOfPage = false;- section.Blocks.Add(block);- }- firstPage = false;- }+ /// <summary>A run of text on one baseline (or one vertical column of characters).</summary>+ private sealed class Fragment(string text, HCharFormat format, double size, bool template)+ {+ public string Text { get; set; } = text;+ public HCharFormat Format { get; } = format;++ /// <summary>Font size in millimetres.</summary>+ public double Size { get; } = size;- if (section.Blocks.Count == 0)- section.Blocks.Add(new HParagraph());- section.Page = PageSetup(allItems, pageW, pageH);+ /// <summary>Drawn by a template page (labels of a form), not by the page itself.</summary>+ public bool Template { get; } = template;++ public double X { get; set; }+ public double Baseline { get; set; }+ public double Width { get; set; }- var doc = new HDocument();- doc.Sections.Add(section);- return doc;+ /// <summary>Vertical text: distance from the first character's baseline to the last one's.</summary>+ public double Run { get; set; }++ public bool Vertical => Run > 0;+ public double Left => X;+ public double Right => X + Width;+ public double Top => Baseline - 0.88 * Size;+ public double Bottom => Baseline + Run + 0.12 * Size;}- // ───────────────────────── Page items ─────────────────────────+ /// <summary>A picture: the package part and its box.</summary>+ private sealed record Picture(string Part, double Left, double Top, double Width, double Height)+ {+ public double Right => Left + Width;+ public double Bottom => Top + Height;+ }- /// <summary>A text fragment or a picture with its box, in millimetres from the page's top-left.</summary>- private abstract class Item+ private PageContent ReadPage(XElement content, string path, string docDir, Resources docRes,+ Dictionary<string, string> templates, (double W, double H) defaultArea){- public double X { get; set; }- public double Y { get; set; }- public double W { get; set; }- public double H { get; set; }+ var page = new PageContent();+ var area = PageArea(Child(content, "Area"));++ // Template pages first (the form behind the values): their labels read together with the page's text.+ foreach (var id in Children(content, "Template").Select(t => Attr(t, "TemplateID")).OfType<string>().Distinct().Take(8))+ {+ if (!templates.TryGetValue(id, out var templatePath) || Template(templatePath, docDir, docRes) is not { } template)+ continue;+ area ??= PageArea(Child(template.Root, "Area"));+ var first = page.Fragments.Count;+ Collect(Child(template.Root, "Content"), template.Res, page, null, true, 0);+ if (page.Fragments.Count - first <= 5000)+ MergeTemplateLabels(page.Fragments, first);+ }++ Collect(Child(content, "Content"), PageResources(content, path, docDir, docRes), page, null, false, 0);+ (page.Width, page.Height) = area ?? defaultArea;+ return page;}- private sealed class Fragment(string text, double sizeMm, string? color, string? font, bool bold) : Item+ private (XElement Root, Resources Res)? Template(string path, string docDir, Resources docRes){- public string Text { get; } = text;- public double SizeMm { get; } = sizeMm;- public string? Color { get; } = color;- public string? Font { get; } = font;- public bool Bold { get; } = bold;+ if (!_templates.TryGetValue(path, out var template))+ {+ template = _package.LoadXml(path)?.Root is { } root ? (root, PageResources(root, path, docDir, docRes)) : null;+ _templates[path] = template;+ }+ return template;}- private sealed class Picture(string entry) : Item+ /// <summary>The resource files a page names (PageRes), and a Res.xml next to it; the document's behind them.</summary>+ private Resources PageResources(XElement content, string path, string docDir, Resources docRes){- public string Entry { get; } = entry;+ var pageDir = OfdPackage.DirName(path);+ var res = new Resources(docRes);+ foreach (var pageRes in Children(content, "PageRes"))+ LoadRes(res, OfdPackage.Resolve(pageDir, pageRes.Value) is { } name && _package.Has(name) ? name : OfdPackage.Resolve(docDir, pageRes.Value), docDir);+ LoadRes(res, OfdPackage.Resolve(pageDir, "Res.xml"), docDir);+ return res;}- /// <summary>Collects the text fragments and pictures of one page's content tree.</summary>- private static List<Item> Collect(XElement page, string pageDir, Dictionary<string, string> res,- IReadOnlyDictionary<string, ZipArchiveEntry> entries)+ /// <summary>Page area "x y width height" (PhysicalBox, else ApplicationBox) in millimetres.</summary>+ private static (double W, double H)? PageArea(XElement? area){- var items = new List<Item>();- foreach (var el in page.Descendants())+ foreach (var name in new[] { "PhysicalBox", "ApplicationBox" }){- if (el.Name.LocalName == "TextObject")+ if (Box(Child(area, name)?.Value) is { Width: >= 1 and <= 5000, Height: >= 1 and <= 5000 } box)+ return (box.Width, box.Height);+ }+ return null;+ }++ /// <summary>The drawing objects of a content tree (layers, page blocks), with the layer's drawing parameters.</summary>+ private void Collect(XElement? container, Resources res, PageContent page, string? layerDraw, bool template, int depth)+ {+ if (container is null || depth > MaxDepth)+ return;+ foreach (var element in container.Elements())+ {+ if (Attr(element, "Visible") == "false")+ continue;+ switch (element.Name.LocalName){- var box = BoxWH(Attr(el, "Boundary"));- double size = Attr(el, "Size") is { } s && double.TryParse(s, out var mm) && mm > 0 ? mm : 3.5;- string? color = Color(Attr(el, "FillColor")) ?? Color(FillValue(el)) ?? Color(LayerColor(el, res));- string? font = Attr(el, "Font") is { } id ? res.GetValueOrDefault("font:" + id) : null;- bool bold = Attr(el, "Weight") is { } weight && weight == "700";- var originX = box?.X ?? 0;- var originY = box?.Y ?? 0;- foreach (var code in el.Descendants().Where(d => d.Name.LocalName == "TextCode"))- {- var text = (code.Value ?? "").Replace("\r\n", "\n");- double x = Parse(Attr(code, "X"));- double y = Parse(Attr(code, "Y")); // of the baseline, from the object's box- var at = 0;- foreach (var line in text.Split('\n'))- {- var trimmed = line.Trim();- if (trimmed.Length > 0)- {- // Column-wide boxes (the 数量 cell holding one digit) must not swallow the gap to- // the next column: the text's own width, when smaller, wins. DeltaX advances are- // exact; the last character is as wide as the advance before it (half the size for- // digits), not the full size.- var own = DeltaX(code) is { } advances- ? advances.Sum() + (advances.Length > 0 ? advances[^1] : size)- : EstimateWidth(trimmed, size);- var w = at == 0 && box is { W: > 0 } b ? Math.Min(b.W, own) : own;- items.Add(new Fragment(trimmed, size, color, font, bold)- .At(originX + x, originY + y - size * 0.86 + at * size * 1.3,- w, Math.Max(box?.H ?? 0, size * 1.25)));- }- at++;- }- }- }- else if (el.Name.LocalName == "ImageObject")- {- if (Attr(el, "ResourceID") is not { } id || !res.TryGetValue("media:" + id, out var entry))- continue;- if (BoxWH(Attr(el, "Boundary")) is { } image)- items.Add(new Picture(entry).At(image.X, image.Y, image.W, image.H));+ case "Layer":+ Collect(element, res, page, Attr(element, "DrawParam") ?? layerDraw, template, depth + 1);+ break;+ case "PageBlock":+ Collect(element, res, page, layerDraw, template, depth + 1);+ break;+ case "TextObject":+ Count();+ TextObject(element, res, page, layerDraw, template);+ break;+ case "ImageObject":+ Count();+ ImageObject(element, res, page);+ break;+ case "PathObject":+ Count();+ PathObject(element, res, page, layerDraw);+ break;}}- return items;}- /// <summary>Position setter: records give positional equality, so boxes are set after construction.</summary>- private static T At<T>(this T item, double x, double y, double w, double h) where T : Item+ private void Count(){- item.X = x; item.Y = y; item.W = w; item.H = h;- return item;+ if (++_objects > MaxObjects)+ throw new InvalidDataException($"The OFD document has more than {MaxObjects:N0} drawing objects; Filee does not read it.");}- // ───────────────────────── Layout ─────────────────────────+ // ───────────────────────── Text ─────────────────────────- /// <summary>Boxes → paragraphs in reading order; fragments that line up share one line.</summary>- private static List<HBlock> Layout(List<Item> items, string mediaFolder)+ private static void TextObject(XElement element, Resources res, PageContent page, string? layerDraw, bool template){- var blocks = new List<(double Y, HBlock Block)>();-- // Fragments into lines: same band of the page, ordered left to right.- var lines = new List<List<Fragment>>();- foreach (var fragment in items.Where(i => i is Fragment).Cast<Fragment>()- .OrderBy(f => f.Y + f.H / 2).ThenBy(f => f.X))+ var box = Box(Attr(element, "Boundary")) ?? default;+ var ctm = Matrix.Parse(Attr(element, "CTM"));+ var size = Number(Attr(element, "Size")) is { } s and > 0 and < 1000 ? s : DefaultSize;+ var font = Attr(element, "Font") is { } fontId ? res.Font(fontId) : null;+ var bold = Number(Attr(element, "Weight")) >= 600 || font?.Bold == true;+ var italic = Attr(element, "Italic") == "true" || font?.Italic == true;++ // Colour: the object's own (an attribute in some writers, the standard's FillColor element), its drawing+ // parameter, the layer's. Text drawn as outline only takes the stroke colour.+ var own = res.Draw(Attr(element, "DrawParam"));+ var layer = res.Draw(layerDraw);+ var color = Color(Attr(element, "FillColor")) ?? ColorOf(Child(element, "FillColor")) ?? own.Fill ?? layer.Fill;+ if (Attr(element, "Fill") == "false" && Attr(element, "Stroke") == "true")+ color = ColorOf(Child(element, "StrokeColor")) ?? own.Stroke ?? layer.Stroke ?? color;++ var scaleX = ctm.ScaleX;+ var fontSize = Math.Clamp(size * ctm.ScaleY, 0.1, 1000);+ var family = FontFamily(font?.Name);+ var format = new HCharFormat(+ Bold: bold ? true : null,+ Italic: italic ? true : null,+ Size: (int)(Math.Round(fontSize * 72 / 25.4 * 2) * 50),+ Font: family,+ EastAsianFont: family,+ Color: color);++ // A TextCode without X or Y goes on where the one before it ended.+ double penX = 0, penY = 0;+ foreach (var code in Children(element, "TextCode")){- var line = lines.LastOrDefault();- if (line is not null && Math.Abs((fragment.Y + fragment.H / 2) - LineMid(line)) < 0.6 * Math.Max(fragment.H, 1))- line.Add(fragment);- else- lines.Add([fragment]);+ var text = string.Concat(code.Value.Select(c => char.IsControl(c) ? ' ' : c));+ var x = Number(Attr(code, "X")) ?? penX;+ var y = Number(Attr(code, "Y")) ?? penY;+ if (text.Length == 0)+ continue;+ var dx = Deltas(Attr(code, "DeltaX"), text.Length - 1);+ var dy = Deltas(Attr(code, "DeltaY"), text.Length - 1);+ var vertical = dy is not null && dy.Any(d => d != 0) && (dx is null || dx.All(d => d == 0));++ // Offsets of each character from the first, along the line (or down the column).+ var offsets = new double[text.Length + 1];+ for (var i = 0; i < text.Length; i++)+ {+ var step = vertical ? dy!.ElementAtOrDefault(i) : dx is not null && i < dx.Length ? dx[i] : Advance(text[i], size);+ offsets[i + 1] = offsets[i] + (vertical && i >= dy!.Length ? size : step);+ }+ (penX, penY) = vertical ? (x, y + offsets[^1]) : (x + offsets[^1], y);++ var start = 0;+ while (start < text.Length && char.IsWhiteSpace(text[start]))+ start++;+ var end = text.Length - 1;+ while (end >= start && char.IsWhiteSpace(text[end]))+ end--;+ if (end < start)+ continue;++ var (originX, originY) = vertical ? (x, y + offsets[start]) : (x + offsets[start], y);+ var (pageX, pageY) = ctm.Apply(originX, originY);+ var fragment = new Fragment(text[start..(end + 1)], format, fontSize, template)+ {+ X = box.X + pageX,+ Baseline = box.Y + pageY,+ Width = (vertical ? size : offsets[end] - offsets[start] + Advance(text[end], size)) * scaleX,+ Run = vertical ? (offsets[end] - offsets[start]) * ctm.ScaleY : 0,+ };+ if (page.Fragments.Count == MaxFragmentsPerPage)+ throw new InvalidDataException($"An OFD page has more than {MaxFragmentsPerPage:N0} pieces of text; Filee does not read it.");+ page.Fragments.Add(fragment);}+ }- // A wrapped item name continues its row (转印组 / 件): a lone CJK fragment under a line that ends in a- // number, starting at the same left edge, joins that line — a new row always brings its own columns, so- // it has several fragments and never matches.- for (var i = 1; i < lines.Count; i++)+ /// <summary>+ /// DeltaX / DeltaY: the distances between the characters, with "g n d" standing for n times d. At most+ /// <paramref name="count"/> values are taken (a huge repeat count cannot allocate more than the text needs).+ /// </summary>+ private static double[]? Deltas(string? value, int count)+ {+ if (value is null || count <= 0)+ return null;+ var result = new List<double>();+ var tokens = value.Split([' ', '\t', '\r', '\n'], StringSplitOptions.RemoveEmptyEntries);+ for (var i = 0; i < tokens.Length && result.Count < count; i++){- var previous = lines[i - 1];- var current = lines[i];- if (current.Count == 1 && previous.Count > 1- && Math.Abs(current[0].X - previous.Min(f => f.X)) < 2- && current[0].Y - previous.Max(f => f.Y) is > 0 and < 8- && current[0].Text.All(c => c >= 0x2E80)- && previous.MaxBy(f => f.X) is { Text.Length: > 0 } last && char.IsAsciiDigit(last.Text[^1]))+ if (tokens[i] == "g" && i + 2 < tokens.Length+ && int.TryParse(tokens[i + 1], NumberStyles.Integer, CultureInfo.InvariantCulture, out var repeat)+ && Number(tokens[i + 2]) is { } repeated)+ {+ for (var k = 0; k < repeat && result.Count < count; k++)+ result.Add(repeated);+ i += 2;+ }+ else if (Number(tokens[i]) is { } delta){- previous.Add(current[0]);- lines.RemoveAt(i);- i--;+ result.Add(delta);}}+ return result.Count > 0 ? [.. result] : null;+ }++ /// <summary>Advance of a character without DeltaX: full width for CJK, half for the rest (as Chinese fonts draw Latin).</summary>+ private static double Advance(char c, double size) => IsWide(c) ? size : size * 0.5;- foreach (var group in lines)+ private static bool IsWide(char c) => c >= 0x2E80 && c is < '。' or > 'ᅵ';++ /// <summary>+ /// Single characters of a template stacked in one column (购买方信息, 备注 — the block titles of an invoice) or spread+ /// over one line (合 计) become one fragment, so they read as a word. Template content only: the page's own single+ /// characters are values in table cells that must stay apart.+ /// </summary>+ private static void MergeTemplateLabels(List<Fragment> fragments, int first)+ {+ var singles = fragments.Skip(first).Where(f => f.Text.Length == 1 && IsWide(f.Text[0]) && !f.Vertical).ToList();+ var merged = new HashSet<Fragment>();++ // Stacked: same X, one under the other, at most three lines apart.+ foreach (var column in singles.GroupBy(f => Math.Round(f.X * 2) / 2)){- var paragraph = new HParagraph();- var line = group.OrderBy(f => f.X).ToList();- for (var i = 0; i < line.Count; i++)+ var stack = new List<Fragment>();+ foreach (var fragment in column.OrderBy(f => f.Baseline).Append(null)){- if (i > 0)+ if (fragment is not null && stack.Count is > 0 and < 8 && Math.Abs(fragment.Size - stack[0].Size) < 0.1+ && fragment.Baseline - stack[^1].Baseline > 0 && fragment.Baseline - stack[^1].Baseline < 3 * fragment.Size){- var gap = line[i].X - (line[i - 1].X + line[i - 1].W);- if (gap > 0.5 * line[i].SizeMm)- paragraph.Inlines.Add(new HText(" ", Format(line[i])));+ stack.Add(fragment);+ continue;}- paragraph.Inlines.Add(new HText(line[i].Text, Format(line[i])));+ if (stack.Count >= 2)+ {+ stack[0].Text = string.Concat(stack.Select(f => f.Text));+ stack[0].Run = stack[^1].Baseline - stack[0].Baseline;+ merged.UnionWith(stack.Skip(1));+ }+ stack = fragment is null ? [] : [fragment];}- blocks.Add((line.Average(f => f.Y), paragraph));}- // Pictures: one centred paragraph each (the seal of an invoice), in reading order.- foreach (var picture in items.Where(i => i is Picture).Cast<Picture>().OrderBy(p => p.Y + p.H / 2))+ // Spread: a pair of single characters on one baseline with nothing between them.+ var row = singles.Where(f => !merged.Contains(f) && !f.Vertical).OrderBy(f => f.Baseline).ThenBy(f => f.X).ToList();+ for (var i = 1; i < row.Count; i++){- if (Extract(picture, mediaFolder) is not { } file)- continue;- var paragraph = new HParagraph { Format = new(Align: HAlign.Center) };- paragraph.Inlines.Add(new HImage(file)+ var (left, right) = (row[i - 1], row[i]);+ var gap = right.Left - left.Right;+ if (left.Text.Length != 1 || Math.Abs(left.Baseline - right.Baseline) > 0.3 || Math.Abs(left.Size - right.Size) > 0.1+ || gap < -0.1 || gap > 8 * right.Size+ || fragments.Skip(first).Any(f => f != left && f != right && Math.Abs(f.Baseline - left.Baseline) < 0.5 * f.Size+ && f.Left >= left.Right - 0.1 && f.Right <= right.Left + 0.1)){- Width = (int)Math.Round(picture.W * MmToUnit),- Height = (int)Math.Round(picture.H * MmToUnit),- });- blocks.Add((picture.Y, paragraph));+ continue;+ }+ left.Text += right.Text;+ left.Width = right.Right - left.Left;+ merged.Add(right);+ row[i] = left;}-- return blocks.OrderBy(b => b.Y).Select(b => b.Block).ToList();+ fragments.RemoveAll(merged.Contains);}- /// <summary>One-character labels stacked at the same X (购买方信息, 备注 — the vertical block titles of an- /// invoice) become one fragment so they read as a word. Template content only: the page's own single- /// characters are table cells that must stay apart (rows sit closer than label characters).</summary>- private static List<Item> MergeVerticalLabels(List<Item> items)+ /// <summary>English family names of common Chinese fonts, which Word and LibreOffice know on any system.</summary>+ private static readonly Dictionary<string, string> ChineseFonts = new(StringComparer.OrdinalIgnoreCase){- var vertical = items.Where(i => i is Fragment { Text.Length: 1 } f && f.Text[0] >= 0x2E80).Cast<Fragment>()- .OrderBy(f => f.X).ThenBy(f => f.Y).ToList();- if (vertical.Count < 2)- return items;-- var groups = new List<List<Fragment>>();- foreach (var fragment in vertical)- {- var group = groups.LastOrDefault(g => Math.Abs(g[0].X - fragment.X) < 0.75 && fragment.Y - g[^1].Y is > 0 and < 7.5);- if (group is not null && group.Count < 8)- group.Add(fragment);- else- groups.Add([fragment]);- }+ ["宋体"] = "SimSun",+ ["新宋体"] = "NSimSun",+ ["黑体"] = "SimHei",+ ["楷体"] = "KaiTi",+ ["楷体_GB2312"] = "KaiTi_GB2312",+ ["仿宋"] = "FangSong",+ ["仿宋_GB2312"] = "FangSong_GB2312",+ ["微软雅黑"] = "Microsoft YaHei",+ ["等线"] = "DengXian",+ ["隶书"] = "LiSu",+ ["幼圆"] = "YouYuan",+ ["华文宋体"] = "STSong",+ ["华文中宋"] = "STZhongsong",+ ["华文楷体"] = "STKaiti",+ ["华文仿宋"] = "STFangsong",+ ["华文细黑"] = "STXihei",+ ["方正小标宋简体"] = "FZXiaoBiaoSong-B05S",+ };- var replaced = new HashSet<Fragment>();- var result = new List<Item>(items.Count);- foreach (var group in groups.Where(g => g.Count >= 2))- {- var first = group[0];- replaced.UnionWith(group);- result.Add(new Fragment(string.Concat(group.Select(g => g.Text)), first.SizeMm, first.Color, first.Font, first.Bold)- .At(first.X, first.Y, first.W, group[^1].Y + group[^1].H - first.Y));- }- result.AddRange(items.Where(i => i is not Fragment f || !replaced.Contains(f)));- return result;+ /// <summary>The family to write: subset prefixes ("ABCDEF+") and style suffixes (",Bold") off, Chinese names in English.</summary>+ private static string? FontFamily(string? name)+ {+ if (string.IsNullOrWhiteSpace(name))+ return null;+ name = name.Trim();+ if (name.Length > 7 && name[6] == '+' && name[..6].All(char.IsAsciiLetterUpper))+ name = name[7..];+ name = name.Split(',')[0].Trim();+ return name.Length == 0 ? null : ChineseFonts.GetValueOrDefault(name, name);}- private static double LineMid(List<Fragment> line) => line.Average(f => f.Y + f.H / 2);+ // ───────────────────────── Pictures ─────────────────────────- private static HCharFormat Format(Fragment f) => new()+ private static void ImageObject(XElement element, Resources res, PageContent page){- Size = (int)Math.Round(f.SizeMm * MmToCentiPt),- Color = f.Color,- Font = f.Font,- EastAsianFont = f.Font,- Bold = f.Bold ? true : null,- };+ if (Attr(element, "ResourceID") is not { } id || res.Media(id) is not { } part)+ return;+ if (Box(Attr(element, "Boundary")) is not { } box)+ return;+ // The picture fills the unit square, which the CTM scales to its size within the boundary.+ var ctm = Matrix.Parse(Attr(element, "CTM"));+ var (left, top, width, height) = ctm != Matrix.Identity ? ctm.Bounds(box.X, box.Y) : box;+ if (width >= 0.5 && height >= 0.5 && width < 10_000 && height < 10_000)+ page.Pictures.Add(new Picture(part, left, top, width, height));+ }- /// <summary>Unpacks a picture; exotic formats (JBIG2, JPEG-2000) are transcoded to PNG, unreadable ones skipped.</summary>- private static string? Extract(Picture picture, string mediaFolder)+ /// <summary>A picture unpacked into the media folder (once per part), as a format the writers embed; null when+ /// it cannot be decoded (JBIG2, damaged) or is too large.</summary>+ private string? Extract(string part){- var name = "ofd-" + Guid.NewGuid().ToString("N")[..8];- var ext = Extension(picture.Entry);- Directory.CreateDirectory(mediaFolder);+ if (_extracted.TryGetValue(part, out var known))+ return known;+ string? file = null;+ if (_extracted.Count < MaxPictures && _package.Read(part, OfdPackage.MaxPictureBytes) is { } bytes)+ file = Save(bytes);+ _extracted[part] = file;+ return file;+ }++ private string? Save(byte[] bytes)+ {+ // The part name is never used for the file: the format comes from the bytes.+ var kind = bytes switch+ {+ [0x89, 0x50, 0x4E, 0x47, ..] => "png",+ [0xFF, 0xD8, 0xFF, ..] => "jpg",+ [0x47, 0x49, 0x46, 0x38, ..] => "gif",+ [0x42, 0x4D, ..] => "bmp",+ [0x49, 0x49, 0x2A, 0x00, ..] or [0x4D, 0x4D, 0x00, 0x2A, ..] => "tiff",+ [0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20, ..] => "jp2",+ [0xFF, 0x4F, 0xFF, 0x51, ..] => "j2k",+ _ => null,+ };+ if (kind is null)+ return null;+ Directory.CreateDirectory(_mediaFolder);+ var name = Path.Combine(_mediaFolder, $"ofd-{Guid.NewGuid():N}");+ if (kind is "png" or "jpg" or "gif" or "bmp")+ {+ File.WriteAllBytes($"{name}.{kind}", bytes);+ return $"{name}.{kind}";+ }try{- if (DirectImages.Contains(ext))+ var settings = new MagickReadSettings{- var file = Path.Combine(mediaFolder, $"{name}.{ext}");- File.WriteAllBytes(file, ReadEntry(picture.Entry));- return file;- }- using var image = new MagickImage(ReadEntry(picture.Entry));- var png = Path.Combine(mediaFolder, $"{name}.png");- image.Write(png);- return png;+ Format = kind switch { "tiff" => MagickFormat.Tiff, "jp2" => MagickFormat.Jp2, _ => MagickFormat.J2k },+ };+ var info = new MagickImageInfo(bytes, settings);+ if ((long)info.Width * info.Height > MaxPicturePixels)+ return null;+ using var image = new MagickImage(bytes, settings);+ image.Write($"{name}.png", MagickFormat.Png);+ return $"{name}.png";}- catch+ catch (MagickException){- return null; // a seal Filee cannot decode is left out; the text of the invoice still converts+ return null; // a picture Filee cannot decode is left out; the text still converts}}// ───────────────────────── Resources ─────────────────────────- /// <summary>Res file lookup: "media:id" → zip entry, "font:id" → font family name, "draw:id" → the colour- /// a DrawParam fills with. The Res element's own BaseLoc ("Res") says where its media files live.</summary>- private static Dictionary<string, string> LoadRes(IReadOnlyDictionary<string, ZipArchiveEntry> entries, string dir, string fileName)+ private sealed record FontInfo(string? Name, bool Bold, bool Italic);++ private sealed record DrawParam(string? Relative, string? Fill, string? Stroke, double? LineWidth);++ /// <summary>Resources by ID; a page's own come first, then the document's (<see cref="Parent"/>).</summary>+ private sealed class Resources(Resources? parent){- var res = new Dictionary<string, string>();- var xml = LoadXml(entries, Join(dir, fileName));- if (xml?.Root is null)- return res;- var mediaDir = Attr(xml.Root, "BaseLoc") is { Length: > 0 } baseLoc ? Join(dir, baseLoc) : dir;- var drawParams = new List<(string Id, string? Relative, string? Color)>();- foreach (var el in xml.Root.Descendants())+ public Resources? Parent { get; } = parent;+ public Dictionary<string, FontInfo> Fonts { get; } = [];+ public Dictionary<string, string> MediaParts { get; } = [];+ public Dictionary<string, DrawParam> DrawParams { get; } = [];++ public FontInfo? Font(string id) => Fonts.GetValueOrDefault(id) ?? Parent?.Font(id);++ public string? Media(string id) => MediaParts.GetValueOrDefault(id) ?? Parent?.Media(id);++ /// <summary>Fill and stroke colour and line width of a drawing parameter, completed from the ones it is relative to.</summary>+ public (string? Fill, string? Stroke, double? LineWidth) Draw(string? id){- if (el.Name.LocalName == "MultiMedia" && Attr(el, "ID") is { } id)- res["media:" + id] = ResolveEntry(entries, mediaDir, MediaFile(el));- else if (el.Name.LocalName == "Font" && Attr(el, "ID") is { } fid)- res["font:" + fid] = Attr(el, "FontName") ?? Attr(el, "FamilyName") ?? "";- else if (el.Name.LocalName == "DrawParam" && Attr(el, "ID") is { } did)- drawParams.Add((did, Attr(el, "Relative"), Attr(el, "FillColor") ?? FillValue(el) ?? StrokeValue(el)));- }- // A DrawParam without its own FillColor inherits from the one it is Relative to.- for (var pass = 0; pass < 4 && drawParams.Any(p => !res.ContainsKey("draw:" + p.Id)); pass++)- foreach (var (id, relative, colour) in drawParams.Where(p => !res.ContainsKey("draw:" + p.Id)))+ string? fill = null, stroke = null;+ double? width = null;+ for (var hops = 0; id is not null && hops < 8 && Find(id) is { } param; hops++){- if (colour is { Length: > 0 })- res["draw:" + id] = colour;- else if (relative is { } rel && res.TryGetValue("draw:" + rel, out var inherited))- res["draw:" + id] = inherited;+ fill ??= param.Fill;+ stroke ??= param.Stroke;+ width ??= param.LineWidth;+ id = param.Relative;}- return res;- }-- private static Dictionary<string, string> MergeRes(Dictionary<string, string> page, Dictionary<string, string> doc)- {- foreach (var pair in doc.Where(p => !page.ContainsKey(p.Key)))- page[pair.Key] = pair.Value;- return page;- }+ return (fill, stroke, width);+ }- /// <summary>MediaFile is relative to the page (or document) the Res file belongs to; a few writers differ.</summary>- private static string ResolveEntry(IReadOnlyDictionary<string, ZipArchiveEntry> entries, string dir, string mediaFile)- {- foreach (var candidate in new[] { Join(dir, mediaFile), Join(dir, "Res", mediaFile), mediaFile })- if (entries.ContainsKey(candidate))- return candidate;- return Join(dir, mediaFile);+ private DrawParam? Find(string id) => DrawParams.GetValueOrDefault(id) ?? Parent?.Find(id);}- // ───────────────────────── Page setup ─────────────────────────-- private static HPage PageSetup(List<Item> items, double pageW, double pageH)+ /// <summary>Reads a resource file into <paramref name="into"/> (IDs already there are kept).</summary>+ private void LoadRes(Resources into, string? name, string docDir){- double left = MinMarginMm, top = MinMarginMm, right = MinMarginMm, bottom = MinMarginMm;- if (items.Count > 0)+ if (_package.LoadXml(name)?.Root is not { } root)+ return;+ var resDir = OfdPackage.DirName(name!);+ // Media files are relative to the folder the Res element names (BaseLoc); writers differ, so the file's own+ // folder, its Res subfolder, the document and the package root are tried too.+ var baseDir = OfdPackage.Resolve(resDir, Attr(root, "BaseLoc")) ?? resDir;+ foreach (var element in root.Descendants()){- left = Math.Max(MinMarginMm, items.Min(i => i.X));- top = Math.Max(MinMarginMm, items.Min(i => i.Y));- right = Math.Max(MinMarginMm, pageW - items.Max(i => i.X + i.W));- bottom = Math.Max(MinMarginMm, pageH - items.Max(i => i.Y + i.H));+ if (Attr(element, "ID") is not { } id)+ continue;+ switch (element.Name.LocalName)+ {+ case "Font":+ into.Fonts.TryAdd(id, new FontInfo(Attr(element, "FontName") ?? Attr(element, "FamilyName"),+ Attr(element, "Bold") == "true", Attr(element, "Italic") == "true"));+ break;+ case "MultiMedia" when Attr(element, "Type") is null || Attr(element, "Type")!.Equals("Image", StringComparison.OrdinalIgnoreCase):+ var file = Attr(element, "MediaFile") ?? Child(element, "MediaFile")?.Value;+ var part = new[] { baseDir, resDir, resDir.Length == 0 ? "Res" : resDir + "/Res", docDir, "" }+ .Select(dir => OfdPackage.Resolve(dir, file)).FirstOrDefault(_package.Has);+ if (part is not null)+ into.MediaParts.TryAdd(id, part);+ break;+ case "DrawParam":+ into.DrawParams.TryAdd(id, new DrawParam(Attr(element, "Relative"),+ Color(Attr(element, "FillColor")) ?? ColorOf(Child(element, "FillColor")),+ Color(Attr(element, "StrokeColor")) ?? ColorOf(Child(element, "StrokeColor")),+ Number(Attr(element, "LineWidth"))));+ break;+ }}- return new HPage((int)(pageW * MmToUnit), (int)(pageH * MmToUnit),- (int)(left * MmToUnit), (int)(right * MmToUnit), (int)(top * MmToUnit), (int)(bottom * MmToUnit), 0, 0, 0);}// ───────────────────────── Small helpers ─────────────────────────- private static XDocument? LoadXml(IReadOnlyDictionary<string, ZipArchiveEntry> entries, string path)+ /// <summary>A transformation "a b c d e f": (x, y) → (a·x + c·y + e, b·x + d·y + f).</summary>+ private readonly record struct Matrix(double A, double B, double C, double D, double E, double F){- if (!entries.TryGetValue(path, out var entry) || entry.Length == 0)- return null;- using var stream = entry.Open();- return XDocument.Load(stream, LoadOptions.None);- }+ public static readonly Matrix Identity = new(1, 0, 0, 1, 0, 0);- private static byte[] ReadEntry(string path)- {- using var zip = ZipFile.OpenRead(_zipPath!);- var entry = zip.Entries.FirstOrDefault(e => Norm(e.FullName) == path)- ?? throw new InvalidDataException($"The OFD package is missing {path}.");- using var stream = entry.Open();- using var copy = new MemoryStream();- stream.CopyTo(copy);- return copy.ToArray();- }-- private static string? Attr(XElement el, string name) =>- el.Attribute(name)?.Value ?? el.Attributes().FirstOrDefault(a => a.Name.LocalName == name)?.Value;-- /// <summary>WPS writes colour as a FillColor child element with a decimal "R G B" Value attribute.</summary>- private static string? FillValue(XElement el) =>- el.Elements().FirstOrDefault(e => e.Name.LocalName == "FillColor")?.Attribute("Value")?.Value;+ public static Matrix Parse(string? value)+ {+ var numbers = Numbers(value);+ if (numbers is not [var a, var b, var c, var d, var e, var f] || Math.Abs(a * d - b * c) < 1e-9)+ return Identity;+ return new Matrix(a, b, c, d, e, f);+ }- /// <summary>StrokeColor the same way (a DrawParam may only define one).</summary>- private static string? StrokeValue(XElement el) =>- el.Elements().FirstOrDefault(e => e.Name.LocalName == "StrokeColor")?.Attribute("Value")?.Value;+ public (double X, double Y) Apply(double x, double y) => (A * x + C * y + E, B * x + D * y + F);- /// <summary>MediaFile is an attribute (WPS) or a child element (tax invoices).</summary>- private static string MediaFile(XElement el) =>- Attr(el, "MediaFile") ?? el.Elements().FirstOrDefault(e => e.Name.LocalName == "MediaFile")?.Value.Trim() ?? "";+ public double ScaleX => Math.Sqrt(A * A + B * B);+ public double ScaleY => Math.Sqrt(C * C + D * D);- /// <summary>A Layer's DrawParam colours its text (tax invoices: red labels and amounts).</summary>- private static string? LayerColor(XElement el, Dictionary<string, string> res)- {- var layer = el.Ancestors().FirstOrDefault(a => a.Name.LocalName == "Layer");- return layer is not null && Attr(layer, "DrawParam") is { } id ? res.GetValueOrDefault("draw:" + id) : null;+ /// <summary>Box of the unit square after the transformation, moved by (<paramref name="x"/>, <paramref name="y"/>).</summary>+ public (double Left, double Top, double Width, double Height) Bounds(double x, double y)+ {+ var corners = new[] { Apply(0, 0), Apply(1, 0), Apply(0, 1), Apply(1, 1) };+ var (left, top) = (corners.Min(p => p.X), corners.Min(p => p.Y));+ return (x + left, y + top, corners.Max(p => p.X) - left, corners.Max(p => p.Y) - top);+ }}- /// <summary>TextCode DeltaX: per-character advances in millimetres, when the writer spelled them out.</summary>- private static double[]? DeltaX(XElement code)- {- if (Attr(code, "DeltaX") is not { } value)- return null;- var advances = new List<double>();- foreach (var part in value.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))- if (double.TryParse(part, out var advance))- advances.Add(advance);- return advances.Count > 0 ? advances.ToArray() : null;- }+ /// <summary>A box "x y width height" in millimetres; null when missing or not four numbers.</summary>+ private static (double X, double Y, double Width, double Height)? Box(string? value) =>+ Numbers(value) is [var x, var y, var w, var h] && w >= 0 && h >= 0 ? (x, y, w, h) : null;- /// <summary>Width of a text run without DeltaX: full width for CJK, half for digits (the advance tax- /// invoices use), slightly more for other Latin.</summary>- private static double EstimateWidth(string text, double size) =>- text.Sum(c =>- {- if (c >= 0x2E80)- return size;- if (char.IsAsciiDigit(c) || c == '.')- return size * 0.5;- return size * 0.55;- });-- /// <summary>Boundary "x y w h" in millimetres (TextObject, ImageObject); null when missing.</summary>- private static (double X, double Y, double W, double H)? BoxWH(string? value)+ private static double[]? Numbers(string? value){- var parts = value?.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);- if (parts is not [var x, var y, var w, var h])+ if (value is null)return null;- return Parse(w) > 0 && Parse(h) > 0 ? (Parse(x), Parse(y), Parse(w), Parse(h)) : null;- }-- /// <summary>PhysicalBox "xmin ymin xmax ymax" in millimetres (page area); null when missing.</summary>- private static (double W, double H)? PageBox(string? value)- {- var parts = value?.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);- if (parts is not [var x0, var y0, var x1, var y1])+ var parts = value.Split([' ', '\t', '\r', '\n', ','], StringSplitOptions.RemoveEmptyEntries);+ if (parts.Length > 16)return null;- var w = Math.Max(1, Parse(x1) - Parse(x0));- var h = Math.Max(1, Parse(y1) - Parse(y0));- return w is <= 0 or > 2000 || h is <= 0 or > 2000 ? null : (w, h);+ var numbers = new double[parts.Length];+ for (var i = 0; i < parts.Length; i++)+ {+ if (Number(parts[i]) is not { } number)+ return null;+ numbers[i] = number;+ }+ return numbers;}- private static string? Color(string? value) => value switch- {- null or "" => null,- ['#', .. var hex] when hex.Length >= 6 => "#" + hex[^6..], // #RRGGBB or #AARRGGBB- _ when value.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) is [var r, var g, var br]- && int.TryParse(r, out var red) && int.TryParse(g, out var green) && int.TryParse(br, out var blue)- => $"#{red:X2}{green:X2}{blue:X2}", // decimal "R G B" (WPS FillColor Value)- _ => null,- };-- private static double Parse(string? value) => double.TryParse(value, out var number) ? number : 0;-- private static string Extension(string entry) => Path.GetExtension(entry).TrimStart('.').ToLowerInvariant();+ /// <summary>A number written the XML way (invariant culture); null when it is none, not finite or absurdly large.</summary>+ private static double? Number(string? value) =>+ double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var number) && Math.Abs(number) <= 1e6 ? number : null;- /// <summary>Zip entry names use forward slashes; writers differ in case and in leading slashes.</summary>- private static string Norm(string path) => path.TrimStart('/', '\\').Replace('\\', '/').TrimEnd('/');+ /// <summary>A colour element's Value ("R G B", grey, CMYK, channels in decimal or "#hex").</summary>+ private static string? ColorOf(XElement? element) => Color(Attr(element, "Value"));- private static string DirName(string path)+ private static string? Color(string? value){- var i = path.LastIndexOf('/');- return i < 0 ? "" : path[..i];+ if (string.IsNullOrWhiteSpace(value))+ return null;+ var parts = value.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);+ if (parts is [var single] && single.StartsWith('#') && single.Length >= 7+ && int.TryParse(single[^6..], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var rgb))+ return $"#{rgb:X6}"; // #RRGGBB or #AARRGGBB+ var channels = new int[parts.Length];+ for (var i = 0; i < parts.Length; i++)+ {+ var ok = parts[i].StartsWith('#')+ ? int.TryParse(parts[i][1..], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out channels[i])+ : int.TryParse(parts[i], NumberStyles.Integer, CultureInfo.InvariantCulture, out channels[i]);+ if (!ok)+ return null;+ channels[i] = Math.Clamp(channels[i], 0, 255);+ }+ return channels switch+ {+ [var gray] => $"#{gray:X2}{gray:X2}{gray:X2}",+ [var r, var g, var b] => $"#{r:X2}{g:X2}{b:X2}",+ [var c, var m, var y, var k] => $"#{Cmyk(c, k):X2}{Cmyk(m, k):X2}{Cmyk(y, k):X2}",+ _ => null,+ };++ static int Cmyk(int channel, int black) => (int)Math.Round((255 - channel) * (255 - black) / 255.0);}- private static string Join(string dir, string file) =>- string.IsNullOrEmpty(dir) ? Norm(file) : Norm(dir) + "/" + Norm(file);+ private static string? Attr(XElement? element, string name) =>+ element?.Attribute(name)?.Value ?? element?.Attributes().FirstOrDefault(a => a.Name.LocalName == name)?.Value;++ private static XElement? Child(XElement? element, string name) =>+ element?.Elements().FirstOrDefault(e => e.Name.LocalName == name);- private static string Join(string dir, string folder, string file) =>- string.IsNullOrEmpty(folder) ? Join(dir, file) : Join(dir, Norm(folder) + "/" + Norm(file));+ private static IEnumerable<XElement> Children(XElement? element, string name) =>+ element?.Elements().Where(e => e.Name.LocalName == name) ?? [];}diff --git a/tests/Filee.Core.Tests/UserDataStoreTests.cs b/tests/Filee.Core.Tests/UserDataStoreTests.csindex 5129bac7..cb06ea7d 100644--- a/tests/Filee.Core.Tests/UserDataStoreTests.cs+++ b/tests/Filee.Core.Tests/UserDataStoreTests.cs@@ -756,6 +756,29 @@ public class UserDataStoreTestsAssert.DoesNotContain("potm", profiles.Single(p => p.Id == "presentations").Extensions);}+ [Fact]+ public void Version_26_libraries_learn_ofd_on_the_office_donut_and_nothing_else()+ {+ // As written with schema 26: no OFD, and the user took RTF off the office donut.+ var presets = BuiltInData.CreatePresets();+ var profiles = BuiltInData.CreateProfiles();+ var office = profiles.Single(p => p.Id == "office");+ office.Extensions.RemoveAll(e => e is "ofd" or "rtf");++ Assert.True(SettingsMigrations.ApplyToLibrary(26, presets, profiles));++ Assert.Contains("ofd", office.Extensions);+ Assert.DoesNotContain("rtf", office.Extensions);+ Assert.False(SettingsMigrations.ApplyToLibrary(26, presets, profiles)); // once only++ // A donut of the user that already opens .ofd files keeps them.+ profiles = BuiltInData.CreateProfiles();+ profiles.Single(p => p.Id == "office").Extensions.Remove("ofd");+ profiles.Insert(0, new ToolbarProfile { Id = "invoices", Name = "Invoices", Extensions = ["ofd"] });+ Assert.False(SettingsMigrations.ApplyToLibrary(26, presets, profiles));+ Assert.DoesNotContain("ofd", profiles.Single(p => p.Id == "office").Extensions);+ }+[Fact]public void Version_15_libraries_get_the_tracing_presets_on_the_images_donut_after_pdf(){diff --git a/tests/Filee.Engines.Tests/ComplexScriptTests.cs b/tests/Filee.Engines.Tests/ComplexScriptTests.csindex 76d50695..3bf58966 100644--- a/tests/Filee.Engines.Tests/ComplexScriptTests.cs+++ b/tests/Filee.Engines.Tests/ComplexScriptTests.cs@@ -5,6 +5,7 @@// right-to-left words and lines from the right and marks such paragraphs right to left.// The PDFs are written glyph by glyph (GlyphPdfBuilder) the way the shaping engines leave them.+using System.IO.Compression;using System.Text;using System.Xml.Linq;using Filee.Core.Conversion;@@ -59,6 +60,20 @@ public class ComplexScriptTests(EngineFixture fx) : IClassFixture<EngineFixture>"<p>=E0=AA=B8=E0=AB=8C=E0=AA=B0=E0=AA=BE</p>\r\n--b--\r\n";Assert.Equal("Gujarati", ComplexScripts.FindInFile(Text("page.mhtml", Mhtml), "mhtml"));Assert.Null(ComplexScripts.FindInFile(Text("plain.mhtml", Mhtml.Replace("=E0=AA=B8=E0=AB=8C=E0=AA=B0=E0=AA=BE", "Hello")), "mhtml"));++ // OFD: the text of the pages (an official document in Uyghur), not the resource names.+ string Ofd(string name, string text)+ {+ var path = Path.Combine(folder, name);+ using var zip = ZipFile.Open(path, ZipArchiveMode.Create);+ using (var writer = new StreamWriter(zip.CreateEntry("Doc_0/Pages/Page_0/Content.xml").Open()))+ writer.Write($"<ofd:Page xmlns:ofd=\"http://www.ofdspec.org/2016\"><ofd:TextCode X=\"0\" Y=\"4\">{text}</ofd:TextCode></ofd:Page>");+ using (var writer = new StreamWriter(zip.CreateEntry("Doc_0/PublicRes.xml").Open()))+ writer.Write("<Res><Font ID=\"1\" FontName=\"UKIJ Tuz مرحبا\"/></Res>");+ return path;+ }+ Assert.Equal("Arabic", ComplexScripts.FindInFile(Ofd("uyghur.ofd", "ئۇيغۇرچە ھۆججەت"), "ofd"));+ Assert.Null(ComplexScripts.FindInFile(Ofd("chinese.ofd", "电子发票(普通发票)"), "ofd"));}[Fact]diff --git a/tests/Filee.Engines.Tests/OfdTests.cs b/tests/Filee.Engines.Tests/OfdTests.csindex 53abfa6b..80330bcd 100644--- a/tests/Filee.Engines.Tests/OfdTests.cs+++ b/tests/Filee.Engines.Tests/OfdTests.cs@@ -1,165 +1,407 @@-// OFD (GB/T 33190, the Chinese fixed-layout standard: e-invoices, official documents) → DOCX / TXT with the-// built-in reader. The sample packages are written in the test: the standard's own structure (invoice with a-// seal) and the WPS variant (page size in Document.xml, colour as a decimal FillColor child element).+// OFD (GB/T 33190, the Chinese fixed-layout standard: e-invoices, official documents) → DOCX / TXT with the+// built-in reader. The packages are written in the test: an e-invoice in the tax-invoice structure (template page+// with the frame and labels, values on the page, QR code and seal pictures), a WPS document (page size only in+// Document.xml, decimal colours, wrapped body text over two pages), and hostile packages.using System.IO.Compression;using System.Text;-using System.Text.RegularExpressions;using System.Xml.Linq;using Filee.Core.Conversion;using Filee.Core.Presets;+using Filee.Engines.Hwp.Hwpx;+using Filee.Engines.Ofd;+using ImageMagick;namespace Filee.Engines.Tests;public class OfdTests(EngineFixture fx) : IClassFixture<EngineFixture>{- /// <summary>A one-page invoice-shaped OFD in the standard's structure, with a seal picture.</summary>- private static string MakeStandardOfd(string folder)+ private const string Ns = "xmlns:ofd=\"http://www.ofdspec.org/2016\"";++ // ───────────────────────── E-invoice ─────────────────────────++ /// <summary>+ /// A fully digitalized e-invoice (数电票) as tax-invoice writers lay it out: the template draws the frame (a grid+ /// in the layer's red-brown) and the labels, some stacked one character per line (购买方信息) or spread (合 计);+ /// the page draws the values — numbers with DeltaX in the "g" shorthand, the buyer's name scaled by a CTM, an item+ /// name wrapped onto a second line — and a QR code. Signatures are present and ignored.+ /// </summary>+ private static string MakeInvoice(string folder){+ var png = File.ReadAllBytes(EngineFixture.MakeImage(folder, "qr.png", MagickFormat.Png, 80, 80));var path = Path.Combine(folder, "invoice.ofd");using var zip = ZipFile.Open(path, ZipArchiveMode.Create);- Text(zip, "OFD.xml",- """- <?xml version="1.0" encoding="utf-8"?>- <ofd:OFD xmlns:ofd="http://www.ofdspec.org" Version="1.0"><ofd:DocBody>- <ofd:DocRoot>Doc_0/Document.xml</ofd:DocRoot></ofd:DocBody></ofd:OFD>+ Text(zip, "OFD.xml", $"""+ <?xml version="1.0" encoding="UTF-8"?>+ <ofd:OFD {Ns} Version="1.1" DocType="OFD"><ofd:DocBody>+ <ofd:DocInfo><ofd:DocID>4bd9a0e0</ofd:DocID><ofd:CustomDatas><ofd:CustomData Name="发票号码">25442000000123456789</ofd:CustomData></ofd:CustomDatas></ofd:DocInfo>+ <ofd:DocRoot>Doc_0/Document.xml</ofd:DocRoot><ofd:Signatures>Doc_0/Signs/Signatures.xml</ofd:Signatures>+ </ofd:DocBody></ofd:OFD>""");- Text(zip, "Doc_0/Document.xml",- """- <?xml version="1.0" encoding="utf-8"?>- <ofd:Document xmlns:ofd="http://www.ofdspec.org"><ofd:Pages>- <ofd:Page ID="1" BaseLoc="Pages/Page_0/"/></ofd:Pages></ofd:Document>+ Text(zip, "Doc_0/Document.xml", $"""+ <?xml version="1.0" encoding="UTF-8"?>+ <ofd:Document {Ns}><ofd:CommonData><ofd:MaxUnitID>200</ofd:MaxUnitID>+ <ofd:PageArea><ofd:PhysicalBox>0 0 210 140</ofd:PhysicalBox></ofd:PageArea>+ <ofd:PublicRes>PublicRes.xml</ofd:PublicRes><ofd:DocumentRes>DocumentRes.xml</ofd:DocumentRes>+ <ofd:TemplatePage ID="2" BaseLoc="Tpls/Tpl_0/Content.xml"/></ofd:CommonData>+ <ofd:Pages><ofd:Page ID="1" BaseLoc="Pages/Page_0/Content.xml"/></ofd:Pages></ofd:Document>""");- Text(zip, "Doc_0/Pages/Page_0/Content.xml",- """- <?xml version="1.0" encoding="utf-8"?>- <ofd:Page xmlns:ofd="http://www.ofdspec.org"><ofd:Content><ofd:Layer>- <ofd:TextObject ID="1" Font="1" Size="7" Boundary="62 12 116 9" FillColor="#C00000">- <ofd:TextCode X="0" Y="7.5">四川增值税电子普通发票</ofd:TextCode></ofd:TextObject>- <ofd:TextObject ID="2" Font="1" Size="3.5" Boundary="18 38 12 5">- <ofd:TextCode X="0" Y="3.8">购买方</ofd:TextCode></ofd:TextObject>- <ofd:TextObject ID="3" Font="1" Size="3.5" Boundary="30 38 80 5">- <ofd:TextCode X="0" Y="3.8">名称:成都双流科技有限公司</ofd:TextCode></ofd:TextObject>- <ofd:ImageObject ID="4" ResourceID="10" Boundary="160 55 40 40"/>- </ofd:Layer></ofd:Content></ofd:Page>+ Text(zip, "Doc_0/PublicRes.xml", $"""+ <?xml version="1.0" encoding="UTF-8"?>+ <ofd:Res {Ns} BaseLoc="Res"><ofd:Fonts>+ <ofd:Font ID="3" FontName="宋体" FamilyName="宋体"/><ofd:Font ID="4" FontName="楷体" FamilyName="楷体"/>+ <ofd:Font ID="5" FontName="Courier New" FamilyName="Courier New"/></ofd:Fonts>+ <ofd:DrawParams><ofd:DrawParam ID="6" LineWidth="0.25"><ofd:FillColor Value="128 0 0"/><ofd:StrokeColor Value="128 0 0"/></ofd:DrawParam></ofd:DrawParams>+ </ofd:Res>""");- Text(zip, "Doc_0/Pages/Page_0/Res.xml",- """- <?xml version="1.0" encoding="utf-8"?>- <ofd:Res xmlns:ofd="http://www.ofdspec.org"><ofd:Fonts>- <ofd:Font ID="1" FontName="宋体"/></ofd:Fonts><ofd:MultiMedias>- <ofd:MultiMedia ID="10" Type="Image" MediaFile="seal.png"/></ofd:MultiMedias></ofd:Res>+ Text(zip, "Doc_0/DocumentRes.xml", $"""+ <?xml version="1.0" encoding="UTF-8"?>+ <ofd:Res {Ns} BaseLoc="Res"><ofd:MultiMedias>+ <ofd:MultiMedia ID="7" Type="Image" Format="PNG"><ofd:MediaFile>image_7.png</ofd:MediaFile></ofd:MultiMedia>+ </ofd:MultiMedias></ofd:Res>""");- // A 4×4 red PNG: the seal of the invoice.- var png = new byte[]+ Entry(zip, "Doc_0/Res/image_7.png", png);++ var template = new StringBuilder();+ void Label(string text, double x, double y, double size = 3){- 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52,- 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x04, 0x08, 0x02, 0x00, 0x00, 0x00, 0x26, 0x93, 0x11,- 0xE3, 0x00, 0x00, 0x00, 0x18, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x62, 0x18, 0xEE, 0xE3, 0xE3,- 0xE3, 0x83, 0x83, 0x38, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x19, 0x26, 0x03, 0xD3, 0x00, 0x7B, 0x00,- 0x51, 0x84, 0x19, 0x47, 0x8E, 0xB8, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42,- 0x60, 0x82,- };- Entry(zip, "Doc_0/Pages/Page_0/Res/seal.png", png);+ template.Append($"""<ofd:TextObject ID="1" Boundary="{x} {y - size} 60 {size + 1}" Font="3" Size="{size}"><ofd:TextCode X="0" Y="{size}">{text}</ofd:TextCode></ofd:TextObject>""");+ }+ void Rule(double x0, double y0, double x1, double y1) =>+ template.Append($"""<ofd:PathObject ID="1" Boundary="{x0} {y0} {Math.Max(1, x1 - x0)} {Math.Max(1, y1 - y0)}"><ofd:AbbreviatedData>M 0 0 L {x1 - x0} {y1 - y0}</ofd:AbbreviatedData></ofd:PathObject>""");+ Label("电子发票(普通发票)", 75, 12, 6);+ Label("发票号码:", 140, 18);+ Label("开票日期:", 140, 24);+ // The frame: an outer rectangle and the rules of the blocks (no rules between the item columns).+ template.Append("""<ofd:PathObject ID="1" Boundary="5 28 200 97"><ofd:AbbreviatedData>M 0 0 L 200 0 L 200 97 L 0 97 C</ofd:AbbreviatedData></ofd:PathObject>""");+ Rule(5, 50, 205, 50);+ Rule(5, 100, 205, 100);+ Rule(5, 108, 205, 108);+ Rule(12, 28, 12, 50);+ Rule(105, 28, 105, 50);+ Rule(112, 28, 112, 50);+ Rule(45, 100, 45, 108);+ Rule(12, 108, 12, 125);+ foreach (var (c, i) in "购买方信息".Select((c, i) => (c, i)))+ Label(c.ToString(), 7, 32 + 4 * i);+ foreach (var (c, i) in "销售方信息".Select((c, i) => (c, i)))+ Label(c.ToString(), 107, 32 + 4 * i);+ Label("名称:", 14, 36);+ Label("统一社会信用代码/纳税人识别号:", 14, 44);+ Label("名称:", 114, 36);+ Label("统一社会信用代码/纳税人识别号:", 114, 44);+ Label("项目名称", 15, 55);+ Label("规格型号", 50, 55);+ Label("单位", 75, 55);+ Label("数量", 95, 55);+ Label("单价", 115, 55);+ Label("金额", 140, 55);+ Label("税率/征收率", 160, 55);+ Label("税额", 185, 55);+ Label("合", 20, 96);+ Label("计", 35, 96);+ Label("价税合计(大写)", 7, 105);+ Label("(小写)", 140, 105);+ Label("备", 7, 114);+ Label("注", 7, 120);+ Label("开票人:", 8, 131);+ Text(zip, "Doc_0/Tpls/Tpl_0/Content.xml", $"""+ <?xml version="1.0" encoding="UTF-8"?>+ <ofd:Page {Ns}><ofd:Content><ofd:Layer ID="1" DrawParam="6">{template}</ofd:Layer></ofd:Content></ofd:Page>+ """);++ var page = new StringBuilder();+ void Value(string text, double x, double y, int font = 4, double size = 3.5, string extra = "") =>+ page.Append($"""<ofd:TextObject ID="1" Boundary="{x} {y - size} 80 {size + 1}" Font="{font}" Size="{size}"><ofd:FillColor Value="0 0 0"/><ofd:TextCode X="0" Y="{size}"{extra}>{text}</ofd:TextCode></ofd:TextObject>""");+ page.Append("""<ofd:ImageObject ID="1" ResourceID="7" Boundary="8 6 20 20" CTM="20 0 0 20 0 0"/>""");+ Value("25442000000123456789", 155.5, 18, 5, extra: " DeltaX=\"g 19 2.1\"");+ Value("2025年03月18日", 155.5, 24);+ // Size 7 halved by the CTM: 3.5 mm on the page, the baseline at y = 36.+ page.Append("""<ofd:TextObject ID="1" Boundary="24 32.5 60 5" Font="4" Size="7" CTM="0.5 0 0 0.5 0 0"><ofd:TextCode X="0" Y="7">成都双流科技有限公司</ofd:TextCode></ofd:TextObject>""");+ Value("91510100MA6CXXXX1A", 61, 44, 5);+ Value("深圳市南山区示例贸易有限公司", 124, 36);+ Value("91440300MA5FXXXX2B", 161, 44, 5);+ Value("*印刷品*转印组", 15, 61);+ Value("A4", 50, 61);+ Value("件", 76, 61);+ Value("2", 97, 61);+ Value("50.00", 115, 61);+ Value("100.00", 140, 61);+ Value("13%", 163, 61);+ Value("13.00", 185, 61);+ Value("件套装", 15, 65.5);+ Value("*信息技术服务*软件维护费", 15, 71);+ Value("次", 76, 71);+ Value("1", 97, 71);+ Value("200.00", 115, 71);+ Value("200.00", 140, 71);+ Value("6%", 163, 71);+ Value("12.00", 185, 71);+ Value("¥300.00", 140, 96);+ Value("¥25.00", 185, 96);+ Value("叁佰贰拾伍圆整", 50, 105);+ Value("¥325.00", 155, 105);+ Value("购方开户银行:中国银行成都分行", 14, 114);+ Value("张三", 20.5, 131);+ Text(zip, "Doc_0/Pages/Page_0/Content.xml", $"""+ <?xml version="1.0" encoding="UTF-8"?>+ <ofd:Page {Ns}><ofd:Template TemplateID="2" ZOrder="Background"/>+ <ofd:Content><ofd:Layer ID="1">{page}</ofd:Layer></ofd:Content></ofd:Page>+ """);+ Text(zip, "Doc_0/Signs/Signatures.xml", $"""<?xml version="1.0" encoding="UTF-8"?><ofd:Signatures {Ns}><ofd:Signature ID="1" BaseLoc="Sign_0/Signature.xml"/></ofd:Signatures>""");+ Entry(zip, "Doc_0/Signs/Sign_0/SignedValue.dat", [0x30, 0x82, 0x01, 0x00, 0xDE, 0xAD]);return path;}- /// <summary>A two-page document in the WPS variant: the page size lives in Document.xml, BaseLoc names the- /// content file itself and the colour is a decimal FillColor child element.</summary>- private static string MakeWpsOfd(string folder)+ [Fact]+ public void Invoice_frame_becomes_a_table_with_the_labels_and_values_in_their_cells()+ {+ var folder = fx.NewFolder();+ var document = OfdReader.Read(MakeInvoice(folder), Path.Combine(folder, "media"));+ var section = document.Sections.Single();+ Assert.Equal(Hwp(210), section.Page!.Width);+ Assert.Equal(Hwp(140), section.Page.Height);++ var table = section.Blocks.OfType<HTable>().Single();+ Assert.Equal(4, table.Rows.Count);+ string CellText(HCell cell) => string.Join("\n", cell.Blocks.OfType<HParagraph>().Select(ParagraphText));+ var cells = table.Rows.SelectMany(r => r.Cells).Select(CellText).ToList();++ // Buyer and seller blocks side by side, each with its stacked block title; label and value read as one.+ Assert.Equal(["购买方信息", "名称:成都双流科技有限公司\n统一社会信用代码/纳税人识别号:91510100MA6CXXXX1A",+ "销售方信息", "名称:深圳市南山区示例贸易有限公司\n统一社会信用代码/纳税人识别号:91440300MA5FXXXX2B"],+ table.Rows[0].Cells.Select(CellText));++ // The item list: one cell, a tabbed row per item (a wrapped name continues on a second line of its row's+ // paragraph), the spread 合 计 one word.+ var items = CellText(table.Rows[1].Cells.Single()).Split('\n');+ Assert.Equal("项目名称\t规格型号\t单位\t数量\t单价\t金额\t税率/征收率\t税额", items[0]);+ Assert.Equal("*印刷品*转印组\tA4\t件\t2\t50.00\t100.00\t13%\t13.00", items[1]);+ Assert.Equal("件套装", items[2]);+ Assert.Equal("*信息技术服务*软件维护费\t次\t1\t200.00\t200.00\t6%\t12.00", items[3]);+ Assert.Equal("合计\t¥300.00\t¥25.00", items[4]);+ Assert.Equal(4, table.Rows[1].Cells.Single().Blocks.Count);+ var itemRow = table.Rows[1].Cells.Single().Blocks.OfType<HParagraph>().ElementAt(1);+ Assert.Equal(Hwp(50 - 5.5), itemRow.Format.Tabs![0].Position); // the column where A4 starts, from the cell's text edge++ Assert.Contains("价税合计(大写)", cells);+ Assert.Contains("叁佰贰拾伍圆整\t(小写) ¥325.00", cells);+ Assert.Contains("备注", cells);+ Assert.Contains("购方开户银行:中国银行成都分行", cells);++ // The frame keeps the template's red-brown rules; labels keep its colour, values are black.+ Assert.Equal("#800000", table.Rows[0].Cells[0].Borders!.Value.Left.Color);+ var labels = table.Rows[0].Cells[1].Blocks.OfType<HParagraph>().First().Inlines.OfType<HText>().ToList();+ Assert.Equal("#800000", labels[0].Format.Color);+ Assert.Null(labels[1].Format.Color);+ Assert.Equal("KaiTi", labels[1].Format.EastAsianFont);+ Assert.Equal(1000, labels[1].Format.Size); // 3.5 mm: 7 mm halved by the CTM++ // Above the frame: the title centred, then number and date in reading order; the QR code floats beside them.+ var above = section.Blocks.TakeWhile(b => b is not HTable).OfType<HParagraph>().ToList();+ var lines = above.Select(ParagraphText).Where(t => t.Length > 0).ToList();+ Assert.Equal(["电子发票(普通发票)", "发票号码:25442000000123456789", "开票日期:2025年03月18日"], lines);+ Assert.Equal(HAlign.Center, above.Single(p => ParagraphText(p).StartsWith('电')).Format.Align);+ var qr = above[0].Inlines.OfType<HImage>().Single();+ Assert.Equal(new HAnchor("PAPER", "LEFT", Hwp(8), "PAPER", "TOP", Hwp(6), "IN_FRONT_OF_TEXT", true), qr.Anchor);+ Assert.Equal(Hwp(20), qr.Width);++ // Below the frame.+ Assert.Equal("开票人:张三", ParagraphText((HParagraph)section.Blocks[^1]));+ }++ [Fact]+ public async Task Invoice_becomes_docx_and_txt_in_reading_order()+ {+ var job = await fx.ConvertAsync([MakeInvoice(fx.NewFolder())], new Preset { TargetFormat = "docx" });+ Assert.Equal(JobState.Completed, job.State);+ using (var zip = ZipFile.OpenRead(job.Outputs.Single()))+ {+ var xml = XDocument.Load(zip.GetEntry("word/document.xml")!.Open());+ Assert.Single(xml.Descendants(), d => d.Name.LocalName == "tbl");+ Assert.Contains("SimSun", xml.ToString());+ Assert.Contains(zip.Entries, e => e.FullName.StartsWith("word/media/", StringComparison.Ordinal));+ }++ job = await fx.ConvertAsync([MakeInvoice(fx.NewFolder())], new Preset { TargetFormat = "txt" });+ Assert.Equal(JobState.Completed, job.State);+ var text = await File.ReadAllTextAsync(job.Outputs.Single(), TestContext.Current.CancellationToken);+ string[] order = ["电子发票(普通发票)", "发票号码:25442000000123456789", "购买方信息", "名称:成都双流科技有限公司", "销售方信息",+ "*印刷品*转印组", "件套装", "*信息技术服务*软件维护费", "合计", "价税合计(大写)", "¥325.00", "备注", "开票人:张三"];+ var positions = order.Select(s => text.IndexOf(s, StringComparison.Ordinal)).ToList();+ Assert.DoesNotContain(-1, positions);+ Assert.Equal(positions.Order(), positions);+ }++ // ───────────────────────── WPS document ─────────────────────────++ /// <summary>+ /// A two-page document as WPS writes it: the page size only in Document.xml, BaseLoc naming the content file,+ /// a Res.xml next to Document.xml that nothing names, decimal colours, bold as Weight=700, one TextObject per line.+ /// </summary>+ private const string Body = "为进一步提升医院管理水平和医疗服务质量,按照国家卫生健康委员会关于推进智慧医院建设的有关要求,结合本院实际情况,制定本方案。明确建设目标。";++ private static string MakeWps(string folder){var path = Path.Combine(folder, "letter.ofd");using var zip = ZipFile.Open(path, ZipArchiveMode.Create);- Text(zip, "OFD.xml",- """- <?xml version="1.0" encoding="utf-8"?>- <ofd:OFD xmlns:ofd="http://www.ofdspec.org/2016" Version="1.1"><ofd:DocBody>- <ofd:DocRoot>Doc_0/Document.xml</ofd:DocRoot></ofd:DocBody></ofd:OFD>- """);- Text(zip, "Doc_0/Document.xml",- """- <?xml version="1.0" encoding="utf-8"?>- <ofd:Document xmlns:ofd="http://www.ofdspec.org/2016"><ofd:CommonData>- <ofd:PageArea><ofd:PhysicalBox>0 0 210 297</ofd:PhysicalBox></ofd:PageArea>- </ofd:CommonData><ofd:Pages>- <ofd:Page ID="1" BaseLoc="Pages/Page_0/Content.xml"/>- <ofd:Page ID="2" BaseLoc="Pages/Page_1/Content.xml"/></ofd:Pages></ofd:Document>- """);- Text(zip, "Doc_0/Pages/Page_0/Content.xml",- """- <?xml version="1.0" encoding="utf-8"?>- <ofd:Page xmlns:ofd="http://www.ofdspec.org/2016"><ofd:Content><ofd:Layer>- <ofd:TextObject ID="1" Font="3" Size="4" Boundary="20 30 170 5" Weight="700"><ofd:FillColor Value="5 7 59"/>- <ofd:TextCode X="0" Y="4.3">医院信息化建设方案</ofd:TextCode></ofd:TextObject>- <ofd:TextObject ID="2" Font="3" Size="3.5" Boundary="20 40 170 5">- <ofd:TextCode X="0" Y="3.8" DeltaX="3.5 3.5 3.5">第一章 总体规划</ofd:TextCode></ofd:TextObject>- </ofd:Layer></ofd:Content></ofd:Page>- """);- Text(zip, "Doc_0/Pages/Page_1/Content.xml",- """- <?xml version="1.0" encoding="utf-8"?>- <ofd:Page xmlns:ofd="http://www.ofdspec.org/2016"><ofd:Content><ofd:Layer>- <ofd:TextObject ID="1" Font="3" Size="3.5" Boundary="20 30 170 5">- <ofd:TextCode X="0" Y="3.8">第二章 实施步骤</ofd:TextCode></ofd:TextObject>- </ofd:Layer></ofd:Content></ofd:Page>- """);- Text(zip, "Doc_0/Res.xml",- """+ Text(zip, "OFD.xml", $"""<?xml version="1.0" encoding="utf-8"?><ofd:OFD {Ns} Version="1.1"><ofd:DocBody><ofd:DocRoot>/Doc_0/Document.xml</ofd:DocRoot></ofd:DocBody></ofd:OFD>""");+ Text(zip, "Doc_0/Document.xml", $"""<?xml version="1.0" encoding="utf-8"?>- <ofd:Res xmlns:ofd="http://www.ofdspec.org/2016"><ofd:Fonts>- <ofd:Font ID="3" FontName="仿宋"/></ofd:Fonts></ofd:Res>+ <ofd:Document {Ns}><ofd:CommonData><ofd:PageArea><ofd:PhysicalBox>0 0 210 297</ofd:PhysicalBox></ofd:PageArea></ofd:CommonData>+ <ofd:Pages><ofd:Page ID="1" BaseLoc="Pages/Page_0/Content.xml"/><ofd:Page ID="2" BaseLoc="Pages/Page_1/Content.xml"/></ofd:Pages></ofd:Document>""");+ Text(zip, "Doc_0/Res.xml", $"""<?xml version="1.0" encoding="utf-8"?><ofd:Res {Ns}><ofd:Fonts><ofd:Font ID="3" FontName="仿宋_GB2312"/><ofd:Font ID="4" FontName="黑体"/></ofd:Fonts></ofd:Res>""");++ string Line(string text, double x, double y, int font = 3, double size = 5.6, string extra = "") =>+ $"""<ofd:TextObject ID="1" Font="{font}" Size="{size}" Boundary="{x} {y - size} 160 {size * 1.3}"{extra}><ofd:FillColor Value="5 7 59"/><ofd:TextCode X="0" Y="{size}">{text}</ofd:TextCode></ofd:TextObject>""";+ var first = new StringBuilder();+ first.Append(Line("医院信息化建设方案", 67.15, 40, 4, 8.5, " Weight=\"700\""));+ // A paragraph of three lines on a 156.8 mm measure (28 characters): the first indented by two characters.+ first.Append(Line(Body[..26], 38.2, 60));+ first.Append(Line(Body[26..54], 27, 70));+ first.Append(Line(Body[54..], 27, 80));+ first.Append(Line("第一章 总体规划", 27, 100, 4));+ Text(zip, "Doc_0/Pages/Page_0/Content.xml", $"""<?xml version="1.0" encoding="utf-8"?><ofd:Page {Ns}><ofd:Content><ofd:Layer ID="1">{first}</ofd:Layer></ofd:Content></ofd:Page>""");+ Text(zip, "Doc_0/Pages/Page_1/Content.xml", $"""<?xml version="1.0" encoding="utf-8"?><ofd:Page {Ns}><ofd:Content><ofd:Layer ID="1">{Line("第二章 实施步骤", 27, 40, 4)}</ofd:Layer></ofd:Content></ofd:Page>""");return path;}[Fact]- public async Task Standard_ofd_becomes_docx_and_txt()+ public void Wps_document_keeps_paragraphs_pages_bold_and_colour(){- var job = await fx.ConvertAsync([MakeStandardOfd(fx.NewFolder())], new Preset { TargetFormat = "docx" });- Assert.Equal(JobState.Completed, job.State);- var docx = job.Outputs.Single();+ var folder = fx.NewFolder();+ var document = OfdReader.Read(MakeWps(folder), Path.Combine(folder, "media"));+ var blocks = document.Sections.Single().Blocks.OfType<HParagraph>().ToList();+ Assert.Equal(["医院信息化建设方案", Body, "第一章 总体规划", "第二章 实施步骤"], blocks.Select(ParagraphText));++ var title = blocks[0];+ Assert.Equal(HAlign.Center, title.Format.Align);+ var titleRun = title.Inlines.OfType<HText>().Single().Format;+ Assert.True(titleRun.Bold);+ Assert.Equal("#05073B", titleRun.Color);+ Assert.Equal("SimHei", titleRun.EastAsianFont);++ // The body paragraph: justified, a first-line indent of two characters.+ var body = blocks[1];+ Assert.Equal(HAlign.Justify, body.Format.Align);+ Assert.Equal(Hwp(11.2), body.Format.FirstLine);+ Assert.Equal("FangSong_GB2312", body.Inlines.OfType<HText>().First().Format.Font);++ Assert.False(blocks[2].PageBreakBefore);+ Assert.True(blocks[3].PageBreakBefore);+ }++ // ───────────────────────── Hostile and refused packages ─────────────────────────- // The text arrives (title red, buyer block on one line) and the seal picture is embedded.- using (var zip = ZipFile.OpenRead(docx))+ [Fact]+ public void References_cannot_leave_the_package_and_huge_counts_are_capped()+ {+ var folder = fx.NewFolder();+ var path = Path.Combine(folder, "hostile.ofd");+ using (var zip = ZipFile.Open(path, ZipArchiveMode.Create)){- var document = XDocument.Load(zip.Entries.Single(e => e.FullName == "word/document.xml").Open());- var text = string.Concat(document.Descendants().Where(d => d.Name.LocalName == "t").Select(d => d.Value));- Assert.Contains("四川增值税电子普通发票", text);- Assert.Contains("名称:成都双流科技有限公司", text);- Assert.Contains("C00000", document.ToString()); // the title keeps its colour- Assert.Contains(zip.Entries, e => e.FullName.StartsWith("word/media/"));+ Text(zip, "OFD.xml", $"""<?xml version="1.0"?><ofd:OFD {Ns}><ofd:DocBody><ofd:DocRoot>Doc_0/../Doc_0/./Document.xml</ofd:DocRoot></ofd:DocBody></ofd:OFD>""");+ Text(zip, "Doc_0/Document.xml", $"""+ <?xml version="1.0"?>+ <ofd:Document {Ns}><ofd:CommonData><ofd:PublicRes>../../../outside/Res.xml</ofd:PublicRes><ofd:DocumentRes>/Doc_0/Res.xml</ofd:DocumentRes></ofd:CommonData>+ <ofd:Pages><ofd:Page ID="1" BaseLoc="C:/Windows/win.ini"/><ofd:Page ID="2" BaseLoc="/Doc_0/Pages/Page_0/Content.xml"/></ofd:Pages></ofd:Document>+ """);+ // Pictures that climb out of the package, or name a file on the disk, are not found; a name in the package is.+ Text(zip, "Doc_0/Res.xml", $"""+ <?xml version="1.0"?>+ <ofd:Res {Ns}><ofd:MultiMedias>+ <ofd:MultiMedia ID="1" Type="Image"><ofd:MediaFile>../../../../evil.png</ofd:MediaFile></ofd:MultiMedia>+ <ofd:MultiMedia ID="2" Type="Image"><ofd:MediaFile>file:///C:/Windows/win.ini</ofd:MediaFile></ofd:MultiMedia>+ <ofd:MultiMedia ID="3" Type="Image"><ofd:MediaFile>/Doc_0/Res/../Res/ok.png</ofd:MediaFile></ofd:MultiMedia>+ </ofd:MultiMedias></ofd:Res>+ """);+ Entry(zip, "../evil.png", File.ReadAllBytes(EngineFixture.MakeImage(folder, "evil.png", MagickFormat.Png, 40, 40)));+ Entry(zip, "Doc_0/Res/ok.png", File.ReadAllBytes(EngineFixture.MakeImage(folder, "ok.png", MagickFormat.Png, 40, 40)));+ // A repeat count of two billion, a text object nested deeper than the reader follows.+ var nested = string.Concat(Enumerable.Repeat("<ofd:PageBlock>", 200)) + $"""<ofd:TextObject ID="9" Boundary="20 200 50 5" Size="4"><ofd:TextCode X="0" Y="4">太深</ofd:TextCode></ofd:TextObject>"""+ + string.Concat(Enumerable.Repeat("</ofd:PageBlock>", 200));+ Text(zip, "Doc_0/Pages/Page_0/Content.xml", $"""+ <?xml version="1.0"?>+ <ofd:Page {Ns}><ofd:Content><ofd:Layer ID="1">+ <ofd:TextObject ID="4" Boundary="20 20 100 5" Size="4"><ofd:TextCode X="0" Y="4" DeltaX="g 2000000000 4">安全</ofd:TextCode></ofd:TextObject>+ <ofd:ImageObject ID="5" ResourceID="1" Boundary="20 40 10 10"/><ofd:ImageObject ID="6" ResourceID="2" Boundary="20 60 10 10"/>+ <ofd:ImageObject ID="7" ResourceID="3" Boundary="20 80 10 10"/>{nested}</ofd:Layer></ofd:Content></ofd:Page>+ """);+ // The same name twice: the first part wins, nothing throws.+ Text(zip, "doc_0/pages/page_0/content.xml", "not xml");}- job = await fx.ConvertAsync([MakeStandardOfd(fx.NewFolder())], new Preset { TargetFormat = "txt" });- Assert.Equal(JobState.Completed, job.State);- var lines = (await File.ReadAllTextAsync(job.Outputs.Single(), TestContext.Current.CancellationToken)).Replace("\r\n", "\n").Split('\n');- Assert.Contains("四川增值税电子普通发票", lines);+ var media = Path.Combine(folder, "media");+ var document = OfdReader.Read(path, media);+ var paragraphs = document.Sections.Single().Blocks.OfType<HParagraph>().ToList();+ Assert.Equal("安全", ParagraphText(paragraphs[0]));+ Assert.Single(paragraphs.SelectMany(p => p.Inlines).OfType<HImage>());+ Assert.DoesNotContain(paragraphs, p => ParagraphText(p).Contains("太深"));+ Assert.Single(Directory.GetFiles(media));+ Assert.All(Directory.GetFiles(media), f => Assert.StartsWith(Path.GetFullPath(media), Path.GetFullPath(f)));}[Fact]- public async Task Wps_ofd_keeps_pages_bold_and_colour()+ public void Dtds_are_refused(){- var job = await fx.ConvertAsync([MakeWpsOfd(fx.NewFolder())], new Preset { TargetFormat = "docx" });- Assert.Equal(JobState.Completed, job.State);+ var folder = fx.NewFolder();+ var path = Path.Combine(folder, "xxe.ofd");+ using (var zip = ZipFile.Open(path, ZipArchiveMode.Create))+ {+ Text(zip, "OFD.xml", $"""+ <?xml version="1.0"?>+ <!DOCTYPE ofd:OFD [<!ENTITY a "aaaaaaaaaa"><!ENTITY b "&a;&a;&a;&a;&a;&a;&a;&a;&a;&a;"><!ENTITY x SYSTEM "file:///C:/Windows/win.ini">]>+ <ofd:OFD {Ns}><ofd:DocBody><ofd:DocRoot>&b;&x;</ofd:DocRoot></ofd:DocBody></ofd:OFD>+ """);+ }+ var error = Assert.Throws<InvalidDataException>(() => OfdReader.Read(path, Path.Combine(folder, "media")));+ Assert.Contains("not valid XML", error.Message);+ }++ [Fact]+ public async Task Encrypted_and_broken_packages_fail_with_a_clear_message()+ {+ var folder = fx.NewFolder();+ var encrypted = Path.Combine(folder, "encrypted.ofd");+ using (var zip = ZipFile.Open(encrypted, ZipArchiveMode.Create))+ {+ Text(zip, "OFD.xml", $"""<?xml version="1.0"?><ofd:OFD {Ns}><ofd:DocBody><ofd:DocRoot>Doc_0/Document.xml</ofd:DocRoot></ofd:DocBody></ofd:OFD>""");+ Text(zip, "Encryptions.xml", """<?xml version="1.0"?><Encryptions><Encryption ID="1"/></Encryptions>""");+ Entry(zip, "Doc_0/Document.xml", [0x8F, 0x13, 0x77, 0x02, 0xC4]);+ }+ var job = await fx.ConvertAsync([encrypted], new Preset { TargetFormat = "docx" });+ Assert.Equal(JobState.Failed, job.State);+ Assert.Contains("encrypted", job.Files.Single().ErrorDetail, StringComparison.OrdinalIgnoreCase);- using var zip = ZipFile.OpenRead(job.Outputs.Single());- var document = XDocument.Load(zip.Entries.Single(e => e.FullName == "word/document.xml").Open());- var xml = document.ToString();- Assert.Contains("医院信息化建设方案", xml);- Assert.Contains("05073B", xml); // decimal "5 7 59" → #05073B- Assert.Contains("仿宋", xml);- Assert.Equal(1, Regex.Count(xml, "pageBreakBefore")); // the second page starts on a new page+ var notZip = Path.Combine(folder, "plain.ofd");+ await File.WriteAllTextAsync(notZip, "<OFD/>", TestContext.Current.CancellationToken);+ Assert.Contains("not an OFD document", Assert.Throws<InvalidDataException>(() => OfdReader.Read(notZip, folder)).Message);++ var empty = Path.Combine(folder, "empty.ofd");+ using (var zip = ZipFile.Open(empty, ZipArchiveMode.Create))+ Text(zip, "readme.txt", "no OFD.xml here");+ Assert.Contains("no OFD.xml", Assert.Throws<InvalidDataException>(() => OfdReader.Read(empty, folder)).Message);}- // ───────────────────────── Package helpers ─────────────────────────+ // ───────────────────────── Helpers ─────────────────────────++ private static int Hwp(double mm) => (int)Math.Round(mm * 7200 / 25.4);++ private static string ParagraphText(HParagraph paragraph) =>+ string.Concat(paragraph.Inlines.Select(i => i switch+ {+ HText text => text.Text,+ HTab => "\t",+ HLineBreak => "\n",+ _ => "",+ }));- private static void Text(ZipArchive zip, string name, string content) =>- Entry(zip, name, Encoding.UTF8.GetBytes(content));+ private static void Text(ZipArchive zip, string name, string content) => Entry(zip, name, Encoding.UTF8.GetBytes(content));private static void Entry(ZipArchive zip, string name, byte[] bytes){- var entry = zip.CreateEntry(name);- using var stream = entry.Open();- stream.Write(bytes, 0, bytes.Length);+ using var stream = zip.CreateEntry(name).Open();+ stream.Write(bytes);}}