diff --git a/CHANGELOG.md b/CHANGELOG.md index d778ebd..a38f091 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ ## [Unreleased] +### 修复 + +- **Issue #214 跨格式文本与字段偏移**:TXT 保留单换行、缩进和普通下划线字段名;PDF 只在实测坐标支持时补空格,并按重复双栏分离阅读顺序;DOCX 往返保留页面尺寸/页边距、段落对齐/缩进/制表位、表格列宽和 `gridSpan` / `vMerge`。PDF、HTML、DOCX writer 对尚未支持的版面特性发出降级 warning,QualityReport 增加 `layoutFidelity`。新增英文表单布局回归测试。 + ## [2.4.0] - 2026-07-17 ### 稳定性 diff --git a/docs/development/DEVELOPMENT_TASKS.md b/docs/development/DEVELOPMENT_TASKS.md index 624bc3a..8a3a3b7 100644 --- a/docs/development/DEVELOPMENT_TASKS.md +++ b/docs/development/DEVELOPMENT_TASKS.md @@ -1,6 +1,6 @@ # Trans2Former Development Tasks -最后更新:2026-06-13 +最后更新:2026-09-24 维护规则: @@ -89,6 +89,8 @@ > 仅保留最近 4 周内的记录;更早的归档到 [docs/archive/DEVELOPMENT_HISTORY.md](docs/archive/DEVELOPMENT_HISTORY.md),逐次发布的细节走 [CHANGELOG.md](CHANGELOG.md)。 +- **2026-09-24 (Issue #214 英文文本与表单布局回归)**:TXT 读写保留段内单换行、行首缩进和字段下划线,并将 Markdown 下划线语法识别限制为非单词边界;PDF 仅按真实水平坐标补英文片段空格,检测连续三行以上的双栏内容并按左栏后右栏输出;DOCX 保留页面几何、段落格式/自定义制表位、表格列宽和 `gridSpan` / `vMerge`,DOCX→PDF/HTML 投影保留可表达的页边距、对齐、缩进和列宽;QualityReport 增加 `layoutFidelity`,不可表达的布局发出 lossy warning。增加 `scripts/layout-offset-regression-test.js`,覆盖 TXT、英文 PDF 单栏/双栏、DOCX 表单 DOCX/PDF/HTML 往返。当前无用户脱敏原件,版面回归使用程序生成的合成文档;多节、多栏跨页、旧式 `hMerge`、浮动对象及完整字体主题仍会警告降级。 + - **2026-05-30 (OCR 识别质量展示到检验报告 UI + modelReview 保留修复)**:把已计算但一直不可见的 OCR 识别质量呈现给用户。**修复潜伏 bug**:`format-registry.js` `_runRepairCycle` 用 Repair Engine 的 `modelReview`(`engine:"rule-based"`)覆盖了上游 OCR stage 写的 `modelReview`,导致 `ocr`/`ocrQuality` 子对象被丢弃、UI 取不到——改为合并保留 `priorReview.ocr` / `priorReview.ocrQuality`。`public/index.html` 检验报告面板加「OCR 识别质量」行(`#verificationOcrRecognitionRow`,默认 hidden,仅本次跑了 OCR 才显示)。`public/app.js` `renderVerificationReport` 读 `quality.modelReview.ocr` + `.ocrQuality` 渲染:引擎 / 行数 / 置信度 / 质量 grade / 低置信行 / 纠偏角 / 方向校正数 / 已去噪;grade 驱动 ok·skip·drift 配色。`scripts/browser-smoke-test.js` 断言 `#verificationOcrRecognition` 存在。`scripts/ocr-baseline-test.js` 加回归断言(`convertContentAsync` 默认 repair 路径下 `result.quality.modelReview.ocr` 必须存活)。`npm test` 28 个脚本全量通过。 - **2026-05-30 (OCR 版面结构识别增强)**:落实「对文件内部文本格式识别的增强」——把 OCR 识别的多行(带 bbox)按版面归并成标题 + 段落,而非平铺成一个大段。新增 `public/core/ocr/ocr-structure.js`:`deriveOcrStructure(lines, opts)`(按阅读顺序 y→x 排序;中位行高 → 相对字号判定标题,行高 ≥ 中位 ×1.35 为 heading、按比例给 level 1-3;行间垂直间距 > 中位 ×0.7 分段;同段相邻行 CJK 直连 / 拉丁加空格;无 bbox 几何回退单段保持旧行为)+ `blocksFromOcrResult(result)`(按页拼接,空则回退 fullText)。`png-ocr.js` `enhanceWithOCR` 把 `paragraphsFromOCR`(旧:整页 16 行拼成 1 段)换成 `blocksFromOcrResult`(结构化标题+段落),删旧函数 + 未用 import。**真机验证**:产品标签 16 行 → 4 个结构块(「纯臻营养护发素」识别为 heading,正文按间距归并为段落)。`browser-transformer` export `deriveOcrStructure`/`blocksFromOcrResult`。新增 `scripts/ocr-structure-test.js`(7 组:字号判标题、间距分段、CJK/拉丁拼接、阅读顺序排序、无几何回退、blocksFromOcrResult 翻页、空白行忽略)接入 `npm test`(第 28 个)。`npm test` 28 个脚本全量通过。 - **2026-05-30 (OCR 倾斜文档自动纠偏 · 去倾斜)**:解决倾斜/旋转文档(拍照/扫描带角度)识别崩塌的问题。新增纯函数 `rotateImageDataByAngle(im, deg)`(任意角最近邻旋转 + 画布扩展 + 白底)+ `estimateSkewAngle(probData, mapW, mapH)`(对 det 概率图二值化下采样后,用错切投影直方图方差找让文本行最对齐水平的角度,返回去倾斜旋转角)。`runPaddlePipeline` 抽出 `detect(image)` helper + 接 `options.deskew=true(默认)|false`:从首次 det 估倾斜角,`|est| >= minSkew`(默认 3°) 则把图旋正后**重检一次**再识别——正立图估计≈0 不重检、零开销;识别(rec)始终只跑一次。**真机验证**:倾斜 +10° 文档原本 **8 行/avgConf 0.535**(检测崩一半),自动纠偏后恢复 **16 行/0.970**(skewApplied=10);-8° 同样恢复;正立图 skewApplied=0、保持 0.974 不受影响。`quality` 摘要增 `skewApplied`。`browser-transformer` export `rotateImageDataByAngle`/`estimateSkewAngle`。`scripts/paddle-ocr-pipeline-test.js` 加任意旋转 + 倾斜估计(合成斜行 prob 图检出 ~角度、平行行≈0)断言(共 16 组)。`npm test` 27 个脚本全量通过。 diff --git a/docs/document-model.schema.json b/docs/document-model.schema.json index 7e0748e..d47b1d3 100644 --- a/docs/document-model.schema.json +++ b/docs/document-model.schema.json @@ -29,7 +29,8 @@ "sourceSpan": { "$ref": "#/$defs/sourceSpan" }, "warnings": { "$ref": "#/$defs/warnings" }, "level": { "type": "integer", "minimum": 1, "maximum": 6 }, - "text": { "type": "string" } + "text": { "type": "string" }, + "paragraphFormat": { "$ref": "#/$defs/paragraphFormat" } } }, { @@ -41,7 +42,8 @@ "id": { "type": "string" }, "sourceSpan": { "$ref": "#/$defs/sourceSpan" }, "warnings": { "$ref": "#/$defs/warnings" }, - "text": { "type": "string" } + "text": { "type": "string" }, + "paragraphFormat": { "$ref": "#/$defs/paragraphFormat" } } }, { @@ -112,6 +114,24 @@ "enum": ["", "left", "center", "right"] } }, + "columnWidths": { + "type": "array", + "items": { "type": "integer", "minimum": 1 } + }, + "cellSpans": { + "type": "array", + "items": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "columnSpan": { "type": "integer", "minimum": 1 }, + "verticalMerge": { "enum": ["restart", "continue"] } + } + } + } + }, "chunk": { "type": "object" } } }, @@ -214,6 +234,33 @@ } }, "$defs": { + "paragraphFormat": { + "type": "object", + "additionalProperties": false, + "properties": { + "alignment": { "enum": ["left", "center", "right", "justify"] }, + "indentLeft": { "type": "integer" }, + "indentRight": { "type": "integer" }, + "firstLineIndent": { "type": "integer" }, + "hangingIndent": { "type": "integer" }, + "spacingBefore": { "type": "integer", "minimum": 0 }, + "spacingAfter": { "type": "integer", "minimum": 0 }, + "lineSpacing": { "type": "integer", "minimum": 0 }, + "tabStops": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": ["position"], + "properties": { + "position": { "type": "integer", "minimum": 1 }, + "alignment": { "enum": ["clear", "left", "center", "right", "decimal", "bar", "num"] }, + "leader": { "enum": ["none", "dot", "hyphen", "underscore", "heavy", "middleDot"] } + } + } + } + } + }, "sourceSpan": { "type": "object", "additionalProperties": false, diff --git a/docs/formats/BASIC_FORMAT_QUALITY.md b/docs/formats/BASIC_FORMAT_QUALITY.md index 6dd8419..78aafa9 100644 --- a/docs/formats/BASIC_FORMAT_QUALITY.md +++ b/docs/formats/BASIC_FORMAT_QUALITY.md @@ -2,7 +2,7 @@ 版本:v0.1.0 状态:P0 生效 -最后更新:2026-04-30 +最后更新:2026-09-24 本文记录免下载基础格式的 before/after 样例、保真范围和可解释降级路径。基础格式包括 Markdown、HTML、TXT、JSON、CSV、XML、PNG input 和 PDF output;文档到 PNG/JPEG 的视觉输出在真实渲染器完成前不进入输出矩阵。 @@ -93,9 +93,10 @@ After: After: - 连续文本段落进入 `paragraph`。 -- 纯文本不推断复杂样式。 +- 段落内单换行、行首空格和普通下划线字段名保留。 +- 质量报告将 `layoutFidelity` 与 `textFidelity`、`structureFidelity` 分开;不承载页面布局的输入标为 `not-applicable`。 -降级说明:TXT 没有结构元数据,输出质量取决于原始换行和段落边界。 +降级说明:TXT 没有字体、分页、坐标等页面布局元数据;连续空行按段落边界规范化。 ## JSON diff --git a/docs/formats/DOCX_INPUT_MVP.md b/docs/formats/DOCX_INPUT_MVP.md index 2c8e3f8..9171f47 100644 --- a/docs/formats/DOCX_INPUT_MVP.md +++ b/docs/formats/DOCX_INPUT_MVP.md @@ -2,7 +2,7 @@ 版本:v0.2.0 状态:P3 生效 -最后更新:2026-04-30 +最后更新:2026-09-24 DOCX input MVP 的目标是把 Word 文档本地解析为 `DocumentModel`,优先输出 Markdown / HTML / JSON。 @@ -11,19 +11,20 @@ DOCX input MVP 的目标是把 Word 文档本地解析为 `DocumentModel`,优 - 标题:识别 `w:pStyle` 中的 `Heading1` 到 `Heading6`。 - 段落:合并 `w:t` 文本。 - 链接:解析 `word/_rels/document.xml.rels` 中的 external hyperlink,并追加到可读文本。 -- 表格:第一行作为 headers,其余行作为 rows。 +- 表格:第一行作为 headers,其余行作为 rows;保留 `tblGrid` 列宽、`gridSpan` 跨列和 `vMerge` 纵向合并信息。 +- 段落布局:保留对齐、左右/首行/悬挂缩进、段前段后间距、行距和自定义制表位;文档页面尺寸、方向和页边距供 DOCX writer 回写。 - 图片引用:解析 `a:blip r:embed`,读取 `word/media/*`,进入 `assets` 并生成 asset block。 - 列表:识别 `w:numPr`,映射为 `DocumentModel` list,保留层级 metadata。 - 页眉页脚:读取 header/footer relationship 中的可读文本。 - 脚注和批注:读取 `word/footnotes.xml`、`word/comments.xml` 并以可解释段落保留。 -- 合并单元格:当前扁平化为 table,并输出 `DOCX_TABLE_MERGE_APPROXIMATED` warning。 +- 旧式 `hMerge`、嵌套表格仍会降级并产生 warning;`gridSpan` / `vMerge` 由 table 的 `cellSpans` 表示。 - 图片 alt text:优先读取 `wp:docPr descr/title`。 -- Metadata:记录 OOXML entry 数量、relationship 数量、document part 和文件名。 +- Metadata:记录 OOXML entry 数量、relationship 数量、document part、文件名和最后一个 section 的页面几何。 ## 当前限制 - P3 支持 stored / deflate ZIP entries,但暂不支持 ZIP64 和 data descriptor。 -- 不还原复杂 Word 样式、分页、修订、文本框、公式和浮动布局。 +- 不还原完整 Word 样式、修订、文本框、公式、浮动布局和多节页面设置;跨格式输出不会完整复刻字体主题、边框、单元格内边距或精确分页。 - 图片尺寸、精确编号样式和复杂表格布局属于 P4 高保真增强。 ## 安全边界 @@ -41,4 +42,5 @@ DOCX input MVP 的目标是把 Word 文档本地解析为 `DocumentModel`,优 - DOCX -> Markdown - DOCX -> HTML - DOCX -> JSON -- DOCX 列表、页眉页脚、脚注、批注、合并单元格 warning 和图片 alt text +- DOCX 列表、页眉页脚、脚注、批注、合并单元格和图片 alt text +- 英文表单的段落制表位/对齐、页面几何、表格列宽与合并关系往返 diff --git a/docs/formats/PDF_TEXT_EXTRACTION_MVP.md b/docs/formats/PDF_TEXT_EXTRACTION_MVP.md index ab7d685..34962a6 100644 --- a/docs/formats/PDF_TEXT_EXTRACTION_MVP.md +++ b/docs/formats/PDF_TEXT_EXTRACTION_MVP.md @@ -2,7 +2,7 @@ 版本:v0.1.0 状态:P3 MVP 生效 -最后更新:2026-05-09 +最后更新:2026-09-24 PDF text extraction MVP 只面向文本型 PDF 的基础文本提取,不承诺高保真 PDF 到 Office。 @@ -15,12 +15,13 @@ PDF text extraction MVP 只面向文本型 PDF 的基础文本提取,不承诺 - 保留并解析解压后的 ToUnicode CMap,支持常见 CID -> Unicode 映射,用于中文 PDF 的 ` Tj/TJ` 文本恢复。 - PDF.js 失败时才回落到核心轻量解析器;回落解析中的 ToUnicode CMap 必须尽量按当前 `/F... Tf` 字体绑定,多 CMap 无法绑定时不输出猜测文本,避免错误识别污染转换结果。 - 输出 heading + paragraph blocks。 +- 按实际水平坐标推断英文片段间的空格;重复双栏页面按左栏后右栏的顺序恢复,避免仅凭字母/数字相邻插入空格。 - 生成 `PDF_TEXT_EXTRACTION_MVP` lossy warning。 ## 当前限制 - 不处理扫描 PDF。 - 不处理 OCR。 -- 不还原字体、图片、坐标、表格结构和复杂版面;PDF.js 文本顺序以 PDF 引擎返回的 text content 为准。 +- 不还原完整字体、图片、坐标、表格结构和复杂版面;PDF 多栏检测是启发式处理,跨栏标题/特殊阅读顺序仍可能降级。 - 不承诺所有字体子集、自定义 CMap、坐标重排或图形化文字都能恢复为可编辑文本。 - 不调用云端 PDF、OCR 或 AI 服务。 diff --git a/package.json b/package.json index 487cba7..76ae068 100644 --- a/package.json +++ b/package.json @@ -18,7 +18,7 @@ "desktop:check": "node scripts/desktop-shell-test.js", "desktop:dev": "npm exec @tauri-apps/cli -- dev", "desktop:build": "npm exec @tauri-apps/cli -- build", - "test": "node scripts/r0-p0-data-integrity-test.js && node scripts/server-hardening-test.js && node scripts/smoke-test.js && node scripts/conversion-snapshot-test.js && node scripts/conversion-capability-audit-test.js && node scripts/product-matrix-docs-test.js && node scripts/capability-matrix-consistency-test.js && node scripts/conversion-quality-test.js && node scripts/format-integrity-test.js && node scripts/format-validation-test.js && node scripts/worker-payload-test.js && node scripts/browser-smoke-test.js && node scripts/ui-conversion-e2e-test.js && node scripts/workbench-queue-test.js && node scripts/workspace-storage-test.js && node scripts/test-results-regression-test.js && node scripts/ui-accessibility-test.js && node scripts/desktop-shell-test.js && node scripts/local-security-test.js && node scripts/local-model-direction-test.js && node scripts/repair-engine-test.js && node scripts/rule-diff-test.js && node scripts/ssim-verification-test.js && node scripts/ocr-readback-test.js && node scripts/sample-corpus-test.js && node scripts/corpus-validation-test.js && node scripts/paddle-ocr-pipeline-test.js && node scripts/paddle-ocr-integration-test.js && node scripts/ocr-structure-test.js && node scripts/latex-math-test.js && node scripts/model-cache-test.js && node scripts/tesseract-sha256-test.js && node scripts/ocr-baseline-test.js && node scripts/resource-budget-test.js && node scripts/pdf-reader-test.js && node scripts/xlsx-writer-performance-test.js && node scripts/tesseract-worker-cleanup-test.js && node scripts/p2-responsiveness-test.js && node scripts/p4-p5-p6-test.js && node scripts/p7-release-productization-test.js && node scripts/release-readiness-test.js && node scripts/text-utils-test.js && node scripts/repair-handlers-test.js && node scripts/binary-text-extraction-test.js && node scripts/document-schema-test.js && node scripts/repair-actions-test.js && node scripts/ocr-result-test.js && node scripts/conversion-error-test.js && node scripts/release-user-path-e2e-test.js", + "test": "node scripts/r0-p0-data-integrity-test.js && node scripts/server-hardening-test.js && node scripts/smoke-test.js && node scripts/layout-offset-regression-test.js && node scripts/conversion-snapshot-test.js && node scripts/conversion-capability-audit-test.js && node scripts/product-matrix-docs-test.js && node scripts/capability-matrix-consistency-test.js && node scripts/conversion-quality-test.js && node scripts/format-integrity-test.js && node scripts/format-validation-test.js && node scripts/worker-payload-test.js && node scripts/browser-smoke-test.js && node scripts/ui-conversion-e2e-test.js && node scripts/workbench-queue-test.js && node scripts/workspace-storage-test.js && node scripts/test-results-regression-test.js && node scripts/ui-accessibility-test.js && node scripts/desktop-shell-test.js && node scripts/local-security-test.js && node scripts/local-model-direction-test.js && node scripts/repair-engine-test.js && node scripts/rule-diff-test.js && node scripts/ssim-verification-test.js && node scripts/ocr-readback-test.js && node scripts/sample-corpus-test.js && node scripts/corpus-validation-test.js && node scripts/paddle-ocr-pipeline-test.js && node scripts/paddle-ocr-integration-test.js && node scripts/ocr-structure-test.js && node scripts/latex-math-test.js && node scripts/model-cache-test.js && node scripts/tesseract-sha256-test.js && node scripts/ocr-baseline-test.js && node scripts/resource-budget-test.js && node scripts/pdf-reader-test.js && node scripts/xlsx-writer-performance-test.js && node scripts/tesseract-worker-cleanup-test.js && node scripts/p2-responsiveness-test.js && node scripts/p4-p5-p6-test.js && node scripts/p7-release-productization-test.js && node scripts/release-readiness-test.js && node scripts/text-utils-test.js && node scripts/repair-handlers-test.js && node scripts/binary-text-extraction-test.js && node scripts/document-schema-test.js && node scripts/repair-actions-test.js && node scripts/ocr-result-test.js && node scripts/conversion-error-test.js && node scripts/release-user-path-e2e-test.js", "release:user-path-e2e": "node scripts/release-user-path-e2e-test.js" }, "keywords": [ diff --git a/public/core/document-audit.js b/public/core/document-audit.js index b0a7e60..8922464 100644 --- a/public/core/document-audit.js +++ b/public/core/document-audit.js @@ -119,6 +119,16 @@ export function ensureDocumentAudit(model, { const cursor = { offset: 0 }; const sourceContext = createSourceContext(content); const metadataWarnings = Array.isArray(model.metadata?.warnings) ? model.metadata.warnings.map(normalizeWarning) : []; + const layoutSourceFormat = reader || model.sourceFormat || ""; + const sourceHasPageLayout = ["pdf", "docx", "pptx", "ofd", "png"].includes(layoutSourceFormat); + if (sourceHasPageLayout && targetFormat && !["docx", "pdf", "html"].includes(targetFormat)) { + metadataWarnings.push({ + severity: "lossy", + code: "LAYOUT_NOT_SUPPORTED_BY_TARGET", + message: `${targetFormat} cannot represent the source document's page layout; only text and supported structure are exported.`, + details: { sourceFormat: layoutSourceFormat, targetFormat }, + }); + } const blocks = (model.blocks || []).map((block, index) => { const blockWarnings = Array.isArray(block.warnings) ? block.warnings.map(normalizeWarning) : []; const identityPayload = JSON.stringify({ @@ -144,6 +154,11 @@ export function ensureDocumentAudit(model, { const blockWarnings = blocks.flatMap((block) => block.warnings || []); const warnings = [...metadataWarnings, ...blockWarnings] .filter((warning, index, all) => all.findIndex((candidate) => candidate.code === warning.code && candidate.message === warning.message) === index); + const carriesPageLayout = sourceHasPageLayout; + const hasLayoutLoss = warnings.some((warning) => + ["PDF_LAYOUT_HEURISTIC", "DOCX_TABLE_MERGE_APPROXIMATED", "DOCX_NESTED_TABLE_FLATTENED", "PDF_DOCX_LAYOUT_APPROXIMATED", "DOCX_PDF_LAYOUT_APPROXIMATED"].includes(warning.code) + || (warning.severity === "lossy" && /layout|position|alignment|column|分页|版面|定位|对齐|列宽|合并单元格/i.test(warning.message)) + ); const assets = (model.assets || []).map((asset) => ({ ...asset, @@ -173,6 +188,7 @@ export function ensureDocumentAudit(model, { // 修复 issue #122: 添加 textFidelity 字段 // 基于 warnings 中的文本相关降级判断文本保真度 textFidelity: warnings.some((w) => w.severity === "lossy" && /text|content|字符|编码/.test(w.message)) ? "medium" : "high", + layoutFidelity: !carriesPageLayout ? "not-applicable" : hasLayoutLoss ? "low" : "medium", warningCount: warnings.length, warningsBySeverity: warningSummary(warnings), downgradeCount: warnings.filter((warning) => ["lossy", "unsupported"].includes(warning.severity)).length, diff --git a/public/core/document-model.js b/public/core/document-model.js index 38cdb79..ef801dd 100644 --- a/public/core/document-model.js +++ b/public/core/document-model.js @@ -1,3 +1,5 @@ +import { inlinesToPlainText } from "./models/semantic-inlines.js"; + export function createDocumentModel({ title = "document", sourceFormat = "", @@ -99,7 +101,9 @@ export function getPlainText(model) { return model.blocks .map((block) => { if (block.type === "heading" || block.type === "paragraph" || block.type === "quote") { - return block.text; + return Array.isArray(block.inlines) && block.inlines.length > 0 + ? inlinesToPlainText(block.inlines) + : block.text; } if (block.type === "list") { return block.items.map((item, index) => { @@ -107,7 +111,11 @@ export function getPlainText(model) { const depth = Math.max(0, Number(block.itemMeta?.[index]?.depth) || 0); const indent = " ".repeat(depth); const marker = ordered && depth === 0 ? `${index + 1}.` : "-"; - return `${indent}${marker} ${item}`; + const itemInlines = block.itemInlines?.[index]; + const text = Array.isArray(itemInlines) && itemInlines.length > 0 + ? inlinesToPlainText(itemInlines) + : item; + return `${indent}${marker} ${text}`; }).join("\n"); } if (block.type === "code") { diff --git a/public/core/document-schema.js b/public/core/document-schema.js index 1198012..7fff73f 100644 --- a/public/core/document-schema.js +++ b/public/core/document-schema.js @@ -77,6 +77,33 @@ export function validateDocumentModel(model) { if (["paragraph", "quote"].includes(block.type) && typeof block.text !== "string") { errors.push(`blocks[${index}].text must be a string`); } + if (["paragraph", "heading"].includes(block.type) && block.paragraphFormat !== undefined) { + const format = block.paragraphFormat; + const allowedAlignments = new Set(["left", "center", "right", "justify"]); + const numericKeys = ["indentLeft", "indentRight", "firstLineIndent", "hangingIndent", "spacingBefore", "spacingAfter", "lineSpacing"]; + if (!isObject(format)) errors.push(`blocks[${index}].paragraphFormat must be an object`); + else { + if (format.alignment !== undefined && !allowedAlignments.has(format.alignment)) errors.push(`blocks[${index}].paragraphFormat.alignment is invalid`); + for (const key of numericKeys) { + if (format[key] !== undefined && !Number.isSafeInteger(format[key])) errors.push(`blocks[${index}].paragraphFormat.${key} must be an integer`); + } + for (const key of ["spacingBefore", "spacingAfter", "lineSpacing"]) { + if (format[key] !== undefined && format[key] < 0) errors.push(`blocks[${index}].paragraphFormat.${key} must be non-negative`); + } + if (format.tabStops !== undefined && (!Array.isArray(format.tabStops) || format.tabStops.some((tab) => !isObject(tab) || !Number.isSafeInteger(tab.position) || tab.position <= 0))) { + errors.push(`blocks[${index}].paragraphFormat.tabStops must contain positive positions`); + } + if (Array.isArray(format.tabStops)) format.tabStops.forEach((tab, tabIndex) => { + if (!isObject(tab)) return; + if (tab.alignment !== undefined && !["clear", "left", "center", "right", "decimal", "bar", "num"].includes(tab.alignment)) { + errors.push(`blocks[${index}].paragraphFormat.tabStops[${tabIndex}].alignment is invalid`); + } + if (tab.leader !== undefined && !["none", "dot", "hyphen", "underscore", "heavy", "middleDot"].includes(tab.leader)) { + errors.push(`blocks[${index}].paragraphFormat.tabStops[${tabIndex}].leader is invalid`); + } + }); + } + } if (block.type === "list") { if (typeof block.ordered !== "boolean") errors.push(`blocks[${index}].ordered must be a boolean`); if (!Array.isArray(block.items) || block.items.some((item) => typeof item !== "string")) errors.push(`blocks[${index}].items must be string[]`); @@ -90,6 +117,10 @@ export function validateDocumentModel(model) { if (!Array.isArray(block.headers) || block.headers.some((item) => typeof item !== "string")) errors.push(`blocks[${index}].headers must be string[]`); if (!Array.isArray(block.rows) || block.rows.some((row) => !Array.isArray(row) || row.some((cell) => typeof cell !== "string"))) errors.push(`blocks[${index}].rows must be string[][]`); if (block.alignments !== undefined && (!Array.isArray(block.alignments) || block.alignments.some((alignment) => typeof alignment !== "string"))) errors.push(`blocks[${index}].alignments must be string[]`); + if (block.columnWidths !== undefined && (!Array.isArray(block.columnWidths) || block.columnWidths.some((width) => !Number.isSafeInteger(width) || width <= 0))) errors.push(`blocks[${index}].columnWidths must contain positive integers`); + if (block.cellSpans !== undefined && (!Array.isArray(block.cellSpans) || block.cellSpans.some((row) => !Array.isArray(row) || row.some((cell) => !isObject(cell) || (cell.columnSpan !== undefined && (!Number.isSafeInteger(cell.columnSpan) || cell.columnSpan < 1)) || (cell.verticalMerge !== undefined && !["restart", "continue"].includes(cell.verticalMerge)))))) { + errors.push(`blocks[${index}].cellSpans must contain valid cell span metadata`); + } } if (block.type === "image") { if (typeof block.src !== "string") errors.push(`blocks[${index}].src must be a string`); @@ -122,7 +153,11 @@ export function validateDocumentModel(model) { if (isObject(model.metadata)) { if (model.metadata.warnings !== undefined) validateWarnings(model.metadata.warnings, "metadata.warnings", errors); if (model.metadata.conversion !== undefined && !isObject(model.metadata.conversion)) errors.push("metadata.conversion must be an object"); - if (model.metadata.qualityReport !== undefined && !isObject(model.metadata.qualityReport)) errors.push("metadata.qualityReport must be an object"); + if (model.metadata.qualityReport !== undefined && !isObject(model.metadata.qualityReport)) errors.push("metadata.qualityReport must be an object"); + if (isObject(model.metadata.qualityReport) && model.metadata.qualityReport.layoutFidelity !== undefined + && !["high", "medium", "low", "not-applicable"].includes(model.metadata.qualityReport.layoutFidelity)) { + errors.push("metadata.qualityReport.layoutFidelity is invalid"); + } } return { ok: errors.length === 0, errors }; diff --git a/public/formats/docx-output.js b/public/formats/docx-output.js index 10e198d..3eaf9ab 100644 --- a/public/formats/docx-output.js +++ b/public/formats/docx-output.js @@ -2,6 +2,7 @@ import { bytesToDataUrl, textToBytes } from "../core/binary-utils.js"; import { writeStoredZip } from "../core/zip-writer.js"; import { escapeXmlText } from "./text-utils.js"; import { getCellInlineTokens, getInlineTokens, parseInlineMarkdown } from "./inline-tokens.js"; +import { createWarning } from "../core/warnings.js"; const NS = "http" + "://schemas.openxmlformats.org"; const DC_NS = "http" + "://purl.org/dc/elements/1.1/"; @@ -65,10 +66,18 @@ function runPropertiesXml(style) { return parts.length > 0 ? `${parts.join("")}` : ""; } +function textToWordXml(value) { + return String(value || "").replace(/\r\n?/g, "\n").split(/([\t\n])/).map((part) => { + if (part === "\t") return ""; + if (part === "\n") return ""; + return part ? `${escapeXmlText(part)}` : ""; + }).join(""); +} + function renderRun(run, hyperlinks) { if (run.lineBreak) return `${runPropertiesXml(run.style || {})}`; const rPr = runPropertiesXml(run.style || {}); - const text = `${escapeXmlText(run.text || "")}`; + const text = textToWordXml(run.text); const baseRun = `${rPr}${text}`; if (run.hyperlinkHref) { const rId = hyperlinks.register(run.hyperlinkHref); @@ -107,8 +116,45 @@ function paragraphFromRuns(runs, opts = {}) { ].filter(Boolean).join("\n"); } +function paragraphFormatProperties(format) { + if (!format || typeof format !== "object") return ""; + const tabs = (Array.isArray(format.tabStops) ? format.tabStops : []).filter((tab) => Number.isSafeInteger(tab?.position) && tab.position > 0); + const tabProperties = tabs.length > 0 + ? `${tabs.map((tab) => { + const alignment = ["clear", "left", "center", "right", "decimal", "bar", "num"].includes(tab.alignment) ? tab.alignment : "left"; + const leader = ["none", "dot", "hyphen", "underscore", "heavy", "middleDot"].includes(tab.leader) ? ` w:leader="${tab.leader}"` : ""; + return ``; + }).join("")}` + : ""; + const spacingAttributes = [["spacingBefore", "before"], ["spacingAfter", "after"], ["lineSpacing", "line"]] + .filter(([key]) => Number.isSafeInteger(format[key]) && format[key] >= 0); + const spacingProperties = spacingAttributes.length > 0 + ? ` `w:${attr}="${format[key]}"`).join(" ")}/>` + : ""; + const indentAttributes = [ + ["indentLeft", "left"], ["indentRight", "right"], + ["firstLineIndent", "firstLine"], ["hangingIndent", "hanging"], + ].filter(([key]) => Number.isSafeInteger(format[key])); + const indentProperties = indentAttributes.length > 0 + ? ` `w:${attr}="${format[key]}"`).join(" ")}/>` + : ""; + const alignments = { left: "left", center: "center", right: "right", justify: "both" }; + const alignmentProperties = alignments[format.alignment] ? `` : ""; + return `${tabProperties}${spacingProperties}${indentProperties}${alignmentProperties}`; +} + +function mergeParagraphProperties(base, format) { + const extra = paragraphFormatProperties(format); + if (!extra) return base || ""; + const inner = String(base || "").replace(/^\s*]*>/, "").replace(/<\/w:pPr>\s*$/, ""); + return `${inner}${extra}`; +} + function paragraphBlock(block, hyperlinks, opts = {}) { - return paragraphFromRuns(runsFromBlock(block, hyperlinks), opts); + return paragraphFromRuns(runsFromBlock(block, hyperlinks), { + ...opts, + pPr: mergeParagraphProperties(opts.pPr, block.paragraphFormat), + }); } function paragraphFromText(text, hyperlinks, opts = {}) { @@ -133,16 +179,37 @@ function listItem(item, depth, ordered, hyperlinks, itemInlines) { function table(block, hyperlinks) { const rows = [block.headers, ...(block.rows || [])]; - const columnCount = Math.max(1, block.headers?.length || 1); - const columnWidth = Math.max(1200, Math.floor(9000 / columnCount)); + const cellSpans = Array.isArray(block.cellSpans) ? block.cellSpans : []; + const columnCount = Math.max(1, Array.isArray(block.columnWidths) ? block.columnWidths.length : 0, ...rows.map((row, rowIndex) => + row.reduce((count, _cell, cellIndex) => count + (Number.isSafeInteger(cellSpans[rowIndex]?.[cellIndex]?.columnSpan) && cellSpans[rowIndex][cellIndex].columnSpan > 0 ? cellSpans[rowIndex][cellIndex].columnSpan : 1), 0) + )); + const sourceWidths = Array.isArray(block.columnWidths) + && block.columnWidths.length === columnCount + && block.columnWidths.every((width) => Number.isSafeInteger(width) && width > 0) + ? block.columnWidths + : null; + const fallbackWidth = Math.max(1200, Math.floor(9000 / columnCount)); + const columnWidths = sourceWidths || Array.from({ length: columnCount }, () => fallbackWidth); + const tableWidth = columnWidths.reduce((sum, width) => sum + width, 0); const rowXml = rows.map((row, rowIndex) => [ " ", - ...row.map((cell) => { + ...row.map((cell, cellIndex) => { + const spanInfo = cellSpans[rowIndex]?.[cellIndex] || {}; + const columnSpan = Number.isSafeInteger(spanInfo.columnSpan) && spanInfo.columnSpan > 0 ? spanInfo.columnSpan : 1; + const columnIndex = row.slice(0, cellIndex).reduce((count, _value, index) => { + const priorSpan = cellSpans[rowIndex]?.[index]?.columnSpan; + return count + (Number.isSafeInteger(priorSpan) && priorSpan > 0 ? priorSpan : 1); + }, 0); + const cellWidth = columnWidths.slice(columnIndex, columnIndex + columnSpan).reduce((sum, width) => sum + width, 0) || fallbackWidth * columnSpan; const cellRuns = runsFromCell(cell, hyperlinks).join(""); const boldHeader = rowIndex === 0 ? '' : ""; + const mergeXml = [ + ...(columnSpan > 1 ? [``] : []), + ...(spanInfo.verticalMerge === "restart" ? [''] : spanInfo.verticalMerge === "continue" ? [""] : []), + ].join(""); return [ " ", - ` `, + ` ${mergeXml}`, ` ${boldHeader}${cellRuns}`, " ", ].join("\n"); @@ -152,9 +219,10 @@ function table(block, hyperlinks) { return [ " ", " ", - ' ', + ` `, ' ', " ", + ` ${columnWidths.map((width) => ``).join("")}`, rowXml, " ", ].join("\n"); @@ -164,7 +232,7 @@ function codeParagraph(block) { const lines = String(block.code ?? "").replace(/\r\n?/g, "\n").split("\n"); const runs = lines.map((line, index) => { const breaks = index < lines.length - 1 ? "" : ""; - return `${escapeXmlText(line)}${breaks}`; + return `${textToWordXml(line)}${breaks}`; }).join(""); return [ " ", @@ -235,13 +303,34 @@ ${allRels} } export function writeDocx({ model, title = model.title }) { + const warnings = []; + if (model.sourceFormat === "pdf") { + warnings.push(createWarning("lossy", "DOCX_PDF_LAYOUT_APPROXIMATED", "PDF coordinates and visual styling were converted to editable DOCX flow; exact page positions, fonts, and pagination are not preserved.")); + } + if (model.sourceFormat === "docx" || model.metadata?.ooxml?.pageLayout) { + warnings.push(createWarning("lossy", "DOCX_LAYOUT_PARTIAL", "Page geometry, paragraph alignment/indent/tabs, and supported table widths/merges are preserved; themes, exact fonts, borders, cell padding, floating objects, and pagination are regenerated or omitted.")); + } const hyperlinks = createHyperlinkRegistry(); const bodyXml = model.blocks.map((block) => blockToWordXml(block, hyperlinks)).join("\n"); + const pageLayout = model.metadata?.ooxml?.pageLayout || {}; + const dimension = (value, fallback) => Number.isSafeInteger(value) && value > 0 ? value : fallback; + const margin = (value, fallback) => Number.isSafeInteger(value) && value >= 0 ? value : fallback; + const pageWidth = dimension(pageLayout.width, 11906); + const pageHeight = dimension(pageLayout.height, 16838); + const orientation = ["portrait", "landscape"].includes(pageLayout.orientation) + ? pageLayout.orientation + : pageWidth > pageHeight ? "landscape" : "portrait"; + const pageMargins = [ + ["top", "marginTop", 1440], ["right", "marginRight", 1440], + ["bottom", "marginBottom", 1440], ["left", "marginLeft", 1440], + ["header", "headerDistance", 720], ["footer", "footerDistance", 720], + ["gutter", "gutter", 0], + ].map(([attribute, key, fallback]) => `w:${attribute}="${margin(pageLayout[key], fallback)}"`).join(" "); const documentXml = ` ${bodyXml} - + `; const zipBytes = writeStoredZip([ @@ -315,5 +404,6 @@ ${bodyXml} format: "docx", data: bytesToDataUrl(zipBytes, "application/vnd.openxmlformats-officedocument.wordprocessingml.document"), mime: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + warnings: warnings.length > 0 ? warnings : undefined, }; } diff --git a/public/formats/docx.js b/public/formats/docx.js index 5800eb2..7e44e26 100644 --- a/public/formats/docx.js +++ b/public/formats/docx.js @@ -126,19 +126,103 @@ function scanTopLevelBlocks(body) { } function parseTable(xml) { - const hasMergedCells = / 1; + const gridXml = String(xml ?? "").match(/]*>([\s\S]*?)<\/w:tblGrid>/)?.[1] || ""; + const columnWidths = [...gridXml.matchAll(/]*\/?\s*>/g)] + .map((match) => Number(getAttr(match[0], "w:w"))) + .filter((width) => Number.isFinite(width) && width > 0); // 嵌套表文本经 extractText 平铺进外层单元格;压缩连续换行/空格为单空格防止单元格内 // 换行破坏 md 表格,但保留 \t(issue #92——表格单元格内含制表符的真实文档存在) - const rows = scanBalanced(xml, "w:tr") - .map((rowXml) => scanBalanced(rowXml, "w:tc") - .map((cellXml) => extractText(cellXml).replace(/[ \n\r]+/g, " ").trim())) + const parsedRows = scanBalanced(xml, "w:tr") + .map((rowXml) => scanBalanced(rowXml, "w:tc").map((cellXml) => { + const gridSpan = cellXml.match(/]*\/?\s*>/)?.[0] || ""; + const spanValue = Number(getAttr(gridSpan, "w:val")); + const mergeTag = cellXml.match(/]*\/?\s*>/)?.[0] || ""; + const verticalMerge = mergeTag + ? (getAttr(mergeTag, "w:val") === "restart" ? "restart" : "continue") + : ""; + return { + text: extractText(cellXml).replace(/[ \n\r]+/g, " ").trim(), + columnSpan: Number.isSafeInteger(spanValue) && spanValue > 1 ? spanValue : 1, + verticalMerge, + }; + })) .filter((row) => row.length > 0); + const rows = parsedRows + .map((row) => row.map((cell) => cell.text)) + .filter((row) => row.length > 0); + const cellSpans = parsedRows.map((row) => row.map(({ columnSpan, verticalMerge }) => ({ + columnSpan, + ...(verticalMerge ? { verticalMerge } : {}), + }))); const headers = rows.shift() || []; const table = headers.length > 0 ? createTable(headers, rows) : null; + if (table && columnWidths.length > 0) { + table.columnWidths = columnWidths; + } + if (table && cellSpans.some((row) => row.some((cell) => cell.columnSpan > 1 || cell.verticalMerge))) { + table.cellSpans = cellSpans; + } return { table, hasMergedCells, hasNestedTable }; } +function parseParagraphFormat(xml) { + const pPr = String(xml ?? "").match(//)?.[0] || ""; + if (!pPr) return null; + const format = {}; + const alignment = getAttr(pPr.match(/]*\/?\s*>/)?.[0] || "", "w:val"); + const normalizedAlignment = { start: "left", end: "right", both: "justify", distribute: "justify" }[alignment] || alignment; + if (["left", "center", "right", "justify"].includes(normalizedAlignment)) format.alignment = normalizedAlignment; + + const indent = pPr.match(/]*\/?\s*>/)?.[0] || ""; + for (const [attribute, key] of [["w:left", "indentLeft"], ["w:right", "indentRight"], ["w:firstLine", "firstLineIndent"], ["w:hanging", "hangingIndent"]]) { + const value = getAttr(indent, attribute); + if (/^-?\d+$/.test(value)) format[key] = Number(value); + } + + const spacing = pPr.match(/]*\/?\s*>/)?.[0] || ""; + for (const [attribute, key] of [["w:before", "spacingBefore"], ["w:after", "spacingAfter"], ["w:line", "lineSpacing"]]) { + const value = getAttr(spacing, attribute); + if (/^\d+$/.test(value)) format[key] = Number(value); + } + + const tabStops = [...pPr.matchAll(/]*\/?\s*>/g)].map((match) => { + const position = Number(getAttr(match[0], "w:pos")); + const alignmentValue = getAttr(match[0], "w:val") || "left"; + const leader = getAttr(match[0], "w:leader"); + if (!Number.isSafeInteger(position) || position <= 0) return null; + return { + position, + ...( ["clear", "left", "center", "right", "decimal", "bar", "num"].includes(alignmentValue) ? { alignment: alignmentValue } : {}), + ...( ["none", "dot", "hyphen", "underscore", "heavy", "middleDot"].includes(leader) ? { leader } : {}), + }; + }).filter(Boolean); + if (tabStops.length > 0) format.tabStops = tabStops; + return Object.keys(format).length > 0 ? format : null; +} + +function parsePageLayout(xml) { + const sections = [...String(xml ?? "").matchAll(//g)]; + const section = sections.at(-1)?.[0] || ""; + if (!section) return null; + const pageSize = section.match(/]*\/?\s*>/)?.[0] || ""; + const pageMargins = section.match(/]*\/?\s*>/)?.[0] || ""; + const layout = {}; + for (const [attribute, key] of [["w:w", "width"], ["w:h", "height"]]) { + const value = getAttr(pageSize, attribute); + if (/^\d+$/.test(value) && Number(value) > 0) layout[key] = Number(value); + } + const orientation = getAttr(pageSize, "w:orient"); + if (["portrait", "landscape"].includes(orientation)) layout.orientation = orientation; + for (const [attribute, key] of [["w:top", "marginTop"], ["w:right", "marginRight"], ["w:bottom", "marginBottom"], ["w:left", "marginLeft"], ["w:header", "headerDistance"], ["w:footer", "footerDistance"], ["w:gutter", "gutter"]]) { + const value = getAttr(pageMargins, attribute); + if (/^\d+$/.test(value)) layout[key] = Number(value); + } + return Object.keys(layout).length > 0 ? layout : null; +} + // 从 styles.xml 解析每个 paragraph style 对应的 heading level(如果有)。 // 兼容 Word 中文模板:styleId 可能是 "1"/"af0"/"a3",w:name 可能是 "heading 1" 或 "标题 1"。 function parseHeadingStyleMap(xml) { @@ -271,6 +355,7 @@ function parseParagraph(xml, relationships, assetStore, zip, warnings, reference // issue #92:preserve tab,只压缩连续换行/空格为单空格 const text = inlinesToPlainText(inlines).replace(/[ \n\r]+/g, " ").trim(); const imageIds = [...xml.matchAll(/]*r:embed="([^"]+)"/g)].map((match) => match[1]); + const paragraphFormat = parseParagraphFormat(xml); const numPr = xml.match(//)?.[0] || ""; const listMeta = numPr ? { depth: Number(getAttr(numPr.match(/]*\/?>/)?.[0] || "", "w:val")) || 0, @@ -292,10 +377,12 @@ function parseParagraph(xml, relationships, assetStore, zip, warnings, reference : references.headingStyles.get(style); const heading = createHeading(level, text); if (inlines.length > 0) heading.inlines = inlines; + if (paragraphFormat) heading.paragraphFormat = paragraphFormat; blocks.push(heading); } else { const paragraph = createParagraph(text); if (inlines.length > 0) paragraph.inlines = inlines; + if (paragraphFormat) paragraph.paragraphFormat = paragraphFormat; blocks.push(paragraph); } } @@ -363,6 +450,7 @@ export function readDocx({ content, title = "document", fileName = "", format = const warnings = []; const blocks = []; const body = documentXml.match(//)?.[0] || documentXml; + const pageLayout = parsePageLayout(body); const references = { orderedNumIds: parseNumbering(zip.getText("word/numbering.xml")), headingStyles: parseHeadingStyleMap(zip.getText("word/styles.xml")), @@ -406,6 +494,7 @@ export function readDocx({ content, title = "document", fileName = "", format = relationshipCount: relationships.size, compressionMethods: zip.methods(), fileName, + ...(pageLayout ? { pageLayout } : {}), }, }, warnings), }); diff --git a/public/formats/html.js b/public/formats/html.js index 56567df..814dcf8 100644 --- a/public/formats/html.js +++ b/public/formats/html.js @@ -21,6 +21,7 @@ import { } from "../core/models/semantic-inlines.js"; import { escapeHtml } from "./text-utils.js"; import { modelToBodyHtml } from "./markdown.js"; +import { createWarning } from "../core/warnings.js"; const VOID_TAGS = new Set(["br", "hr", "img", "input", "meta", "link", "source", "col", "area", "embed", "param", "wbr"]); const BLOCK_TAGS = new Set([ @@ -536,6 +537,10 @@ ${formattedBody} } export function writeHtml({ model, title = model.title }) { + const warnings = []; + if (model.sourceFormat === "docx" || model.sourceFormat === "pdf" || model.metadata?.ooxml?.pageLayout) { + warnings.push(createWarning("lossy", "HTML_LAYOUT_APPROXIMATED", "Paragraph alignment/indent and table widths are represented in HTML where available; custom Word tab stops, exact fonts, page geometry, and pagination are not fully preserved.")); + } const assetMap = new Map((model.assets || []).map((asset) => [asset.id, asset])); const bodyHtml = modelToBodyHtml(model).replace( /
([\s\S]*?)<\/figcaption><\/figure>/g, @@ -553,5 +558,6 @@ export function writeHtml({ model, title = model.title }) { format: "html", data: renderHtmlDocument({ bodyHtml, title }), mime: "text/html;charset=utf-8", + warnings: warnings.length > 0 ? warnings : undefined, }; } diff --git a/public/formats/markdown.js b/public/formats/markdown.js index 2d07755..e6e3804 100644 --- a/public/formats/markdown.js +++ b/public/formats/markdown.js @@ -420,14 +420,33 @@ export function writeMarkdown({ model, options = {} }) { } export function blockToHtml(block) { + const paragraphStyle = (value) => { + const format = value.paragraphFormat; + const styles = []; + if (format && typeof format === "object") { + if (["left", "center", "right", "justify"].includes(format.alignment)) styles.push(`text-align:${format.alignment}`); + const indentLeft = Number(format.indentLeft) || 0; + const firstLine = Number(format.firstLineIndent) || 0; + const hanging = Number(format.hangingIndent) || 0; + if (indentLeft) styles.push(`margin-left:${indentLeft / 20}pt`); + if (firstLine || hanging) styles.push(`text-indent:${(firstLine - hanging) / 20}pt`); + if (Number.isFinite(Number(format.spacingBefore))) styles.push(`margin-top:${Math.max(0, Number(format.spacingBefore)) / 20}pt`); + if (Number.isFinite(Number(format.spacingAfter))) styles.push(`margin-bottom:${Math.max(0, Number(format.spacingAfter)) / 20}pt`); + if (Array.isArray(format.tabStops) && format.tabStops.length > 0) styles.push("white-space:pre-wrap;tab-size:8"); + } + const text = String(value.text || ""); + if ((text.includes("\t") || value.inlines?.some((node) => node?.type === "linebreak")) + && !styles.some((style) => style.startsWith("white-space:"))) styles.push("white-space:pre-wrap"); + return styles.length > 0 ? ` style="${escapeHtml(styles.join(";"))}"` : ""; + }; if (block.type === "heading") { - return `${blockTextToHtml(block)}`; + return `${blockTextToHtml(block)}`; } if (block.type === "paragraph") { - return `

${blockTextToHtml(block)}

`; + return `${blockTextToHtml(block)}

`; } if (block.type === "quote") { - return `
${blockTextToHtml(block)}
`; + return `${blockTextToHtml(block)}`; } if (block.type === "list") { return listBlockToHtml(block); @@ -437,21 +456,37 @@ export function blockToHtml(block) { return `
${escapeHtml(block.code)}
`; } if (block.type === "table") { - const alignAttr = (index) => { - const alignment = block.alignments?.[index] || ""; - return alignment ? ` style="text-align:${alignment}"` : ""; + const widths = Array.isArray(block.columnWidths) && block.columnWidths.length > 0 + ? block.columnWidths + : null; + const colgroup = widths + ? `${widths.map((width) => ``).join("")}` + : ""; + const spans = Array.isArray(block.cellSpans) ? block.cellSpans : []; + const renderCell = (cell, rowIndex, cellIndex, tag) => { + const span = spans[rowIndex]?.[cellIndex] || {}; + if (span.verticalMerge === "continue") return ""; + const columnSpan = Number.isSafeInteger(span.columnSpan) && span.columnSpan > 1 ? ` colspan="${span.columnSpan}"` : ""; + let rowSpan = 1; + if (span.verticalMerge === "restart") { + for (let next = rowIndex + 1; next < spans.length && spans[next]?.[cellIndex]?.verticalMerge === "continue"; next += 1) rowSpan += 1; + } + const rowSpanAttr = rowSpan > 1 ? ` rowspan="${rowSpan}"` : ""; + const alignment = block.alignments?.[cellIndex] || ""; + const alignAttr = alignment ? ` style="text-align:${alignment}"` : ""; + return `<${tag}${columnSpan}${rowSpanAttr}${alignAttr}>${inlinesToHtml(tableCellInlines(block, rowIndex === 0 ? -1 : rowIndex - 1, cellIndex, cell))}`; }; const head = [ " ", - ` ${block.headers.map((cell, index) => `${inlinesToHtml(tableCellInlines(block, -1, index, cell))}`).join("")}`, + ` ${block.headers.map((cell, index) => renderCell(cell, 0, index, "th")).join("")}`, " ", ].join("\n"); const body = [ " ", - ...block.rows.map((row, rowIndex) => ` ${row.map((cell, index) => `${inlinesToHtml(tableCellInlines(block, rowIndex, index, cell))}`).join("")}`), + ...block.rows.map((row, rowIndex) => ` ${row.map((cell, index) => renderCell(cell, rowIndex + 1, index, "td")).join("")}`), " ", ].join("\n"); - return `\n${head}\n${body}\n
`; + return `\n${colgroup ? `${colgroup}\n` : ""}${head}\n${body}\n
`; } if (block.type === "image") { return `${escapeHtml(block.alt)}`; diff --git a/public/formats/pdf-output.js b/public/formats/pdf-output.js index 6e76bad..9998441 100644 --- a/public/formats/pdf-output.js +++ b/public/formats/pdf-output.js @@ -30,6 +30,21 @@ function getPaperSize(paperFormat) { return PAPER_SIZES[paperFormat] || PAPER_SIZES[DEFAULT_PAPER]; } +function getDocumentPaperSize(model, paperFormat) { + if (paperFormat) return getPaperSize(paperFormat); + const layout = model.metadata?.ooxml?.pageLayout; + if (!layout || !(layout.width > 0) || !(layout.height > 0)) return getPaperSize(DEFAULT_PAPER); + const twipsToPoints = (value, fallback) => Number.isFinite(value) && value >= 0 ? value / 20 : fallback; + return { + width: layout.width / 20, + height: layout.height / 20, + marginLeft: twipsToPoints(layout.marginLeft, MARGIN_LEFT) + twipsToPoints(layout.gutter, 0), + marginRight: twipsToPoints(layout.marginRight, MARGIN_RIGHT), + marginTop: twipsToPoints(layout.marginTop, MARGIN_TOP), + marginBottom: twipsToPoints(layout.marginBottom, MARGIN_BOTTOM), + }; +} + const MARGIN_LEFT = 72; const MARGIN_RIGHT = 72; const MARGIN_TOP = 60; @@ -174,18 +189,30 @@ function flattenInlinesToSegments(tokens, parentStyle = {}, hrefStack = []) { // 按 block 计算字号 / 缩进 / 段后间距。 function blockLayout(block) { + let layout; if (block.type === "heading") { const level = Math.min(6, Math.max(1, Number(block.level) || 1)); const sizes = [22, 18, 16, 14, 13, 12]; - return { fontSize: sizes[level - 1], leading: sizes[level - 1] * 1.4, indent: 0, marginBottom: 8, forceBold: true }; - } - if (block.type === "quote") { - return { fontSize: 12, leading: 18, indent: 24, marginBottom: 6, forceItalic: true }; - } - if (block.type === "code") { - return { fontSize: 11, leading: 15, indent: 24, marginBottom: 6, allCode: true }; + layout = { fontSize: sizes[level - 1], leading: sizes[level - 1] * 1.4, indent: 0, marginBottom: 8, forceBold: true }; + } else if (block.type === "quote") { + layout = { fontSize: 12, leading: 18, indent: 24, marginBottom: 6, forceItalic: true }; + } else if (block.type === "code") { + layout = { fontSize: 11, leading: 15, indent: 24, marginBottom: 6, allCode: true }; + } else { + layout = { fontSize: 12, leading: 16, indent: 0, marginBottom: 6 }; } - return { fontSize: 12, leading: 16, indent: 0, marginBottom: 6 }; + const format = block.paragraphFormat; + if (!format || typeof format !== "object") return layout; + const indentLeft = Number(format.indentLeft) || 0; + const firstLine = Number(format.firstLineIndent) || 0; + const hanging = Number(format.hangingIndent) || 0; + return { + ...layout, + indent: layout.indent + Math.max(0, indentLeft + firstLine - hanging) / 20, + alignment: ["left", "center", "right", "justify"].includes(format.alignment) ? format.alignment : "left", + marginTop: Math.max(0, Number(format.spacingBefore) || 0) / 20, + marginBottom: Number.isFinite(Number(format.spacingAfter)) ? Math.max(0, Number(format.spacingAfter)) / 20 : layout.marginBottom, + }; } // 把 block 转成 layout lines:每个 line = { segments, indent, fontSize, leading, isLastInBlock } @@ -265,13 +292,15 @@ function blockToLines(block, stats) { const wrapped = wrapSegments(segments, layout.fontSize, maxWidth, stats); if (wrapped.length === 0) return []; - return wrapped.map((lineSegments, i) => ({ - segments: lineSegments, - indent: layout.indent, - fontSize: layout.fontSize, - leading: layout.leading, - marginAfter: i === wrapped.length - 1 ? layout.marginBottom : 0, - })); + return wrapped.map((lineSegments, i) => ({ + segments: lineSegments, + indent: layout.indent, + alignment: layout.alignment, + fontSize: layout.fontSize, + leading: layout.leading, + marginBefore: i === 0 ? layout.marginTop || 0 : 0, + marginAfter: i === wrapped.length - 1 ? layout.marginBottom : 0, + })); } function tableToLines(block, stats) { @@ -281,28 +310,45 @@ function tableToLines(block, stats) { const lines = []; const fontSize = 11; const leading = 15; - const colWidth = CONTENT_WIDTH / Math.max(1, headers.length); + const columnCount = Math.max(1, Array.isArray(block.columnWidths) ? block.columnWidths.length : 0, ...rows.map((row, rowIndex) => + row.reduce((count, _cell, cellIndex) => count + (Number.isSafeInteger(block.cellSpans?.[rowIndex]?.[cellIndex]?.columnSpan) && block.cellSpans[rowIndex][cellIndex].columnSpan > 0 ? block.cellSpans[rowIndex][cellIndex].columnSpan : 1), 0) + )); + const sourceWidths = Array.isArray(block.columnWidths) + && block.columnWidths.length === columnCount + && block.columnWidths.every((width) => Number.isSafeInteger(width) && width > 0) + ? block.columnWidths + : null; + const widthTotal = sourceWidths?.reduce((sum, width) => sum + width, 0) || columnCount; + const columnWidths = sourceWidths + ? sourceWidths.map((width) => width / widthTotal * CONTENT_WIDTH) + : Array.from({ length: columnCount }, () => CONTENT_WIDTH / columnCount); + const cellSpans = Array.isArray(block.cellSpans) ? block.cellSpans : []; rows.forEach((row, rowIndex) => { - const cellLines = row.map((cell) => { + let logicalColumn = 0; + const cellLines = row.map((cell, cellIndex) => { + const spanInfo = cellSpans[rowIndex]?.[cellIndex] || {}; + const columnSpan = Number.isSafeInteger(spanInfo.columnSpan) && spanInfo.columnSpan > 0 ? spanInfo.columnSpan : 1; + const cellWidth = columnWidths.slice(logicalColumn, logicalColumn + columnSpan).reduce((sum, width) => sum + width, 0) || CONTENT_WIDTH / columnCount * columnSpan; + logicalColumn += columnSpan; const tokens = getCellInlineTokens(cell); let segments = flattenInlinesToSegments(tokens); if (rowIndex === 0) { segments = segments.map((seg) => ({ ...seg, style: { ...seg.style, bold: true } })); } - return wrapSegments(segments, fontSize, colWidth - 8, stats); + return { lines: wrapSegments(segments, fontSize, Math.max(8, cellWidth - 8), stats), width: cellWidth }; }); - const maxLines = Math.max(1, ...cellLines.map((c) => c.length)); + const maxLines = Math.max(1, ...cellLines.map((cell) => cell.lines.length)); for (let lineIdx = 0; lineIdx < maxLines; lineIdx += 1) { const mergedSegments = []; - cellLines.forEach((cellWrapped, colIdx) => { - const lineSegments = cellWrapped[lineIdx] || []; + cellLines.forEach((cell, colIdx) => { + const lineSegments = cell.lines[lineIdx] || []; const usedWidth = lineSegments.reduce((sum, seg) => sum + seg.width, 0); if (lineSegments.length > 0) { - mergedSegments.push(...lineSegments.map((seg) => ({ ...seg, columnStart: colIdx * colWidth }))); + mergedSegments.push(...lineSegments.map((seg) => ({ ...seg, columnStart: columnWidths.slice(0, colIdx).reduce((sum, width) => sum + width, 0) }))); } - // 列分隔(简单空格填充,避免实现复杂的 cell box 绘制) - const pad = Math.max(0, colWidth - usedWidth); + // 列分隔按原始列宽投影后的 cell 宽度补齐。 + const pad = Math.max(0, cell.width - usedWidth); if (colIdx < cellLines.length - 1) { mergedSegments.push({ text: " ".repeat(Math.max(1, Math.floor(pad / (fontSize * 0.5)))), style: {}, href: "", width: pad }); } @@ -419,7 +465,11 @@ function buildPdfBytes(model, title, paperSize) { // 根据纸张尺寸设置页面参数 const PAGE_WIDTH = paperSize.width; const PAGE_HEIGHT = paperSize.height; - const CONTENT_WIDTH = PAGE_WIDTH - MARGIN_LEFT - MARGIN_RIGHT; + const marginLeft = Number.isFinite(paperSize.marginLeft) ? paperSize.marginLeft : MARGIN_LEFT; + const marginRight = Number.isFinite(paperSize.marginRight) ? paperSize.marginRight : MARGIN_RIGHT; + const marginTop = Number.isFinite(paperSize.marginTop) ? paperSize.marginTop : MARGIN_TOP; + const marginBottom = Number.isFinite(paperSize.marginBottom) ? paperSize.marginBottom : MARGIN_BOTTOM; + const CONTENT_WIDTH = PAGE_WIDTH - marginLeft - marginRight; const stats = { dropped: new Map() }; // issue #107: 收集降级字符 @@ -474,27 +524,38 @@ function buildPdfBytes(model, title, paperSize) { if (block.type === "table") { const lines = []; - const rows = Array.isArray(block.rows) ? block.rows : []; + const rows = [block.headers || [], ...(Array.isArray(block.rows) ? block.rows : [])]; const fontSize = 11; const leading = 15; - const cols = rows.length > 0 ? rows[0].length : 0; - const colWidth = cols > 0 ? Math.floor(CONTENT_WIDTH / cols) : CONTENT_WIDTH; + const cellSpans = Array.isArray(block.cellSpans) ? block.cellSpans : []; + const cols = Math.max(1, Array.isArray(block.columnWidths) ? block.columnWidths.length : 0, ...rows.map((row, rowIndex) => + row.reduce((count, _cell, cellIndex) => count + (Number.isSafeInteger(cellSpans[rowIndex]?.[cellIndex]?.columnSpan) && cellSpans[rowIndex][cellIndex].columnSpan > 0 ? cellSpans[rowIndex][cellIndex].columnSpan : 1), 0) + )); + const sourceWidths = Array.isArray(block.columnWidths) && block.columnWidths.length === cols && block.columnWidths.every((width) => Number.isSafeInteger(width) && width > 0) + ? block.columnWidths + : null; + const widthTotal = sourceWidths?.reduce((sum, width) => sum + width, 0) || cols; + const columnWidths = sourceWidths ? sourceWidths.map((width) => width / widthTotal * CONTENT_WIDTH) : Array.from({ length: cols }, () => CONTENT_WIDTH / cols); rows.forEach((row, rowIndex) => { - const cellLines = row.map((cell) => { + let logicalColumn = 0; + const cellLines = row.map((cell, cellIndex) => { + const spanInfo = cellSpans[rowIndex]?.[cellIndex] || {}; + const columnSpan = Number.isSafeInteger(spanInfo.columnSpan) && spanInfo.columnSpan > 0 ? spanInfo.columnSpan : 1; + const cellWidth = columnWidths.slice(logicalColumn, logicalColumn + columnSpan).reduce((sum, width) => sum + width, 0) || CONTENT_WIDTH / cols * columnSpan; + logicalColumn += columnSpan; const inlines = getCellInlineTokens(cell); - const segments = flattenInlinesToSegments(inlines); - return wrapSegments(segments, fontSize, colWidth - 8, stats); + let segments = flattenInlinesToSegments(inlines); + if (rowIndex === 0) segments = segments.map((segment) => ({ ...segment, style: { ...segment.style, bold: true } })); + return { lines: wrapSegments(segments, fontSize, Math.max(8, cellWidth - 8), stats), width: cellWidth }; }); - const maxLines = Math.max(...cellLines.map((lines) => lines.length), 1); + const maxLines = Math.max(...cellLines.map((cell) => cell.lines.length), 1); for (let lineIdx = 0; lineIdx < maxLines; lineIdx += 1) { const mergedSegments = []; - cellLines.forEach((lines, colIdx) => { - const lineSegments = lines[lineIdx] || []; + cellLines.forEach((cell, colIdx) => { + const lineSegments = cell.lines[lineIdx] || []; const usedWidth = lineSegments.reduce((sum, seg) => sum + seg.width, 0); - if (lineSegments.length > 0) { - mergedSegments.push(...lineSegments.map((seg) => ({ ...seg, columnStart: colIdx * colWidth }))); - } - const pad = Math.max(0, colWidth - usedWidth); + if (lineSegments.length > 0) mergedSegments.push(...lineSegments); + const pad = Math.max(0, cell.width - usedWidth); if (colIdx < cellLines.length - 1) { mergedSegments.push({ text: " ".repeat(Math.max(1, Math.floor(pad / (fontSize * 0.5)))), style: {}, href: "", width: pad }); } @@ -541,15 +602,16 @@ function buildPdfBytes(model, title, paperSize) { function paginateLocal(allLines) { const pages = []; let current = []; - let yCursor = PAGE_HEIGHT - MARGIN_TOP; + let yCursor = PAGE_HEIGHT - marginTop; for (const line of allLines) { - const needed = line.leading + (line.marginAfter || 0); - if (yCursor - needed < MARGIN_BOTTOM && current.length > 0) { + const needed = (line.marginBefore || 0) + line.leading + (line.marginAfter || 0); + if (yCursor - needed < marginBottom && current.length > 0) { pages.push(current); current = []; - yCursor = PAGE_HEIGHT - MARGIN_TOP; + yCursor = PAGE_HEIGHT - marginTop; } + yCursor -= line.marginBefore || 0; yCursor -= line.leading; current.push({ ...line, y: yCursor }); yCursor -= line.marginAfter || 0; @@ -562,7 +624,12 @@ function buildPdfBytes(model, title, paperSize) { function renderLineLocal(line) { const ops = []; const annotations = []; - let cursorX = MARGIN_LEFT + (line.indent || 0); + const contentWidth = CONTENT_WIDTH - (line.indent || 0); + const lineWidth = line.segments.reduce((sum, seg) => sum + (seg.width != null ? seg.width : String(seg.text || "").length * line.fontSize * 0.5), 0); + const alignOffset = line.alignment === "center" ? Math.max(0, (contentWidth - lineWidth) / 2) + : line.alignment === "right" ? Math.max(0, contentWidth - lineWidth) + : 0; + let cursorX = marginLeft + (line.indent || 0) + alignOffset; for (const seg of line.segments) { if (!seg.text) continue; @@ -714,8 +781,8 @@ function buildPdfBytes(model, title, paperSize) { // issue #108: 高保真失败时 warning,双路 warnings 合并透传 export function writePdfBinary({ model, title = model.title, options = {} }) { const warnings = []; - const paperFormat = options?.paperFormat || DEFAULT_PAPER; - const paperSize = getPaperSize(paperFormat); + const hasDocxLayout = model.sourceFormat === "docx" || Boolean(model.metadata?.ooxml?.pageLayout); + const paperSize = getDocumentPaperSize(model, options?.paperFormat); if (model.fixedLayout && model.fixedLayout.pages && model.fixedLayout.pages.length > 0) { try { @@ -734,6 +801,9 @@ export function writePdfBinary({ model, title = model.title, options = {} }) { const { bytes, warnings: buildWarnings } = buildPdfBytes(model, title, paperSize); if (buildWarnings) warnings.push(...buildWarnings); + if (hasDocxLayout) { + warnings.push(createWarning("lossy", "PDF_DOCX_LAYOUT_APPROXIMATED", "DOCX page size, margins, paragraph alignment/indent, and table widths are applied where available; exact fonts, line metrics, floating objects, and pagination are not preserved.")); + } return { type: "binary", diff --git a/public/formats/pdf.js b/public/formats/pdf.js index a957c90..cac4b8e 100644 --- a/public/formats/pdf.js +++ b/public/formats/pdf.js @@ -395,14 +395,16 @@ function shouldSeparatePdfItems(previous, current) { if (!previousText || !currentText || /\s$/.test(previousText) || /^\s/.test(currentText)) return false; // PDF.js often returns one text item per glyph/word and omits literal spaces. - // Use the measured horizontal gap when available, with an alphanumeric fallback - // for synthetic PDFs whose width/position fields are zero. - const previousEnd = Number(previous?.x || 0) + Number(previous?.width || 0); - const currentStart = Number(current?.x || 0); - const gap = currentStart - previousEnd; - const height = Math.max(Number(previous?.height || 0), Number(current?.height || 0), 12); - if (gap > Math.max(1.5, height * 0.12)) return true; - return /[A-Za-z0-9]$/.test(previousText) && /^[A-Za-z0-9]/.test(currentText); + // Only insert one when actual horizontal geometry proves a word gap. Character + // classes alone are not evidence of whitespace: they split English words and IDs. + if (previous?.hasHorizontalGeometry && current?.hasPosition) { + const previousEnd = Number(previous.x) + Number(previous.width); + const currentStart = Number(current.x); + const gap = currentStart - previousEnd; + const height = Math.max(Number(previous.height) || 0, Number(current.height) || 0, 12); + return gap > Math.max(1.5, height * 0.12); + } + return false; } function joinPdfItems(items, separator = " ") { @@ -482,6 +484,8 @@ async function extractTextWithPdfJs(content) { y: item.transform?.[5] ?? 0, width: Number(item.width) || 0, height: item.height || Math.abs(item.transform?.[3] ?? 0) || 12, + hasPosition: Number.isFinite(item.transform?.[4]), + hasHorizontalGeometry: Number.isFinite(item.transform?.[4]) && Number(item.width) > 0, fontName: String(item.fontName || ""), hasEOL: Boolean(item.hasEOL), })); @@ -550,9 +554,98 @@ async function collectPdfJsAnnotations(page) { } } +function distinctLayoutLineCount(segments, tolerance) { + const yValues = segments.map((segment) => segment.y).sort((a, b) => b - a); + let count = 0; + let previous = null; + for (const y of yValues) { + if (previous === null || Math.abs(previous - y) >= tolerance) { + count += 1; + previous = y; + } + } + return count; +} + +// Detect a persistent vertical gutter from line segments. Requiring at least three +// aligned rows per side avoids treating a normal label/value pair as columns. +function splitPageColumns(items) { + if (!Array.isArray(items) || items.length < 6 || items.some((item) => !Number.isFinite(item.x) || !Number.isFinite(item.y) || !(Number(item.width) > 0))) return null; + const heights = items.map((item) => Number(item.height) || 12).sort((a, b) => a - b); + const medianHeight = heights[Math.floor(heights.length / 2)] || 12; + const lineTolerance = medianHeight * 0.5; + const rowItems = []; + for (const item of [...items].sort((a, b) => b.y - a.y || a.x - b.x)) { + const row = rowItems[rowItems.length - 1]; + if (row && Math.abs(row.y - item.y) < Math.max(lineTolerance, (Number(item.height) || 12) * 0.5)) { + row.items.push(item); + } else { + rowItems.push({ y: item.y, items: [item] }); + } + } + + const segments = []; + const gutterThreshold = Math.max(42, medianHeight * 3); + for (const row of rowItems) { + const rowSegments = []; + for (const item of row.items.sort((a, b) => a.x - b.x)) { + const previous = rowSegments[rowSegments.length - 1]; + const previousItem = previous?.items[previous.items.length - 1]; + const gap = previousItem ? item.x - (previousItem.x + previousItem.width) : 0; + if (!previous || gap > gutterThreshold) rowSegments.push({ y: row.y, items: [item] }); + else previous.items.push(item); + } + for (const segment of rowSegments) { + segment.minX = segment.items[0].x; + segment.maxX = segment.items.reduce((maximum, item) => Math.max(maximum, item.x + item.width), segment.minX); + segments.push(segment); + } + } + + const starts = [...new Set(segments.map((segment) => segment.minX))].sort((a, b) => a - b); + let best = null; + for (let index = 1; index < starts.length; index += 1) { + const gap = starts[index] - starts[index - 1]; + if (gap <= gutterThreshold) continue; + const threshold = (starts[index] + starts[index - 1]) / 2; + const left = segments.filter((segment) => segment.maxX < threshold); + const right = segments.filter((segment) => segment.minX > threshold); + const spanning = segments.filter((segment) => segment.minX <= threshold && segment.maxX >= threshold); + if (distinctLayoutLineCount(left, lineTolerance) < 3 || distinctLayoutLineCount(right, lineTolerance) < 3) continue; + const topY = Math.max(...[...left, ...right].map((segment) => segment.y)); + const bottomY = Math.min(...[...left, ...right].map((segment) => segment.y)); + const spansContent = spanning.some((segment) => segment.y < topY - lineTolerance && segment.y > bottomY + lineTolerance); + if (spansContent) continue; + if (!best || gap > best.gap) best = { gap, threshold, left, right, spanning, topY, bottomY }; + } + if (!best) return null; + const top = best.spanning.filter((segment) => segment.y > best.topY + lineTolerance).flatMap((segment) => segment.items); + const bottom = best.spanning.filter((segment) => segment.y < best.bottomY - lineTolerance).flatMap((segment) => segment.items); + const flatten = (list) => list.flatMap((segment) => segment.items); + return { + top, + left: flatten(best.left), + right: flatten(best.right), + bottom, + }; +} + // 把 PDF 文本 item 按 y 坐标聚成行,再按字号 / 间距 / 行首符号区分 // 标题 / 列表 / 段落。坐标系 y 越大越靠上(PDF 原点在左下)。 -function analyzePageLayout(items) { +export function analyzePageLayout(items) { + const columns = splitPageColumns(items); + if (columns) { + return [ + ...analyzeSingleColumnLayout(columns.top), + ...analyzeSingleColumnLayout(columns.left), + ...analyzeSingleColumnLayout(columns.right), + ...analyzeSingleColumnLayout(columns.bottom), + ]; + } + return analyzeSingleColumnLayout(items); +} + +function analyzeSingleColumnLayout(items) { if (!items || items.length === 0) return []; const sorted = [...items].sort((a, b) => b.y - a.y || a.x - b.x); const lines = []; diff --git a/public/formats/plain-text.js b/public/formats/plain-text.js index 62c5a5e..7ea63e6 100644 --- a/public/formats/plain-text.js +++ b/public/formats/plain-text.js @@ -1,23 +1,33 @@ import { createDocumentModel, createParagraph } from "../core/document-model.js"; import { getPlainText } from "../core/document-model.js"; +import { createInlineLineBreak, createInlineText } from "../core/models/semantic-inlines.js"; import { stripMarkdownInlineSyntax } from "./text-utils.js"; export function readText({ content, title = "document", format = "txt" }) { const blocks = String(content ?? "") - .replace(/\r\n/g, "\n") + .replace(/\r\n?/g, "\n") .split(/\n{2,}/) - .map((chunk) => chunk.trim()) - .filter(Boolean) - .map((chunk) => createParagraph(chunk.replace(/\n/g, " "))); + .filter((chunk) => chunk.length > 0) + .map((chunk) => { + const paragraph = createParagraph(chunk); + if (chunk.includes("\n")) { + paragraph.inlines = chunk.split("\n").flatMap((line, index) => [ + ...(index > 0 ? [createInlineLineBreak()] : []), + createInlineText(line), + ]); + } + return paragraph; + }); return createDocumentModel({ title, sourceFormat: format, blocks }); } export function writeText({ model }) { + const text = stripMarkdownInlineSyntax(getPlainText(model)); return { type: "text", format: "txt", - data: `${stripMarkdownInlineSyntax(getPlainText(model))}\n`, + data: text.endsWith("\n") ? text : `${text}\n`, mime: "text/plain;charset=utf-8", }; } diff --git a/public/formats/text-utils.js b/public/formats/text-utils.js index f405ae5..a7569e1 100644 --- a/public/formats/text-utils.js +++ b/public/formats/text-utils.js @@ -53,7 +53,11 @@ export function stripMarkdownInlineSyntax(value) { .replace(/!\[([^\]]*)\]\([^\)]*\)/g, "$1") .replace(/\[([^\]]+)\]\([^\)]*\)/g, "$1") .replace(/`([^`]+)`/g, "$1") - .replace(/(\*\*|__)(.*?)\1/g, "$2") - .replace(/(\*|_)(.*?)\1/g, "$2") + .replace(/\*\*(\S(?:.*?\S)?)\*\*/g, "$1") + // Underscore emphasis requires non-word boundaries so identifiers such as + // field__id__legacy and snake_case are not treated as formatting delimiters. + .replace(/(^|[^\w])__(\S(?:.*?\S)?)__(?=$|[^\w])/g, "$1$2") + .replace(/\*(.*?)\*/g, "$1") + .replace(/(^|[^\w])_(\S(?:.*?\S)?)_(?=$|[^\w])/g, "$1$2") .replace(/~~(.*?)~~/g, "$1"); } diff --git a/scripts/layout-offset-regression-test.js b/scripts/layout-offset-regression-test.js new file mode 100644 index 0000000..537811f --- /dev/null +++ b/scripts/layout-offset-regression-test.js @@ -0,0 +1,123 @@ +import assert from "node:assert/strict"; + +import { analyzePageLayout } from "../public/formats/pdf.js"; +import { readText, writeText } from "../public/formats/plain-text.js"; +import { readDocx } from "../public/formats/docx.js"; +import { writeDocx } from "../public/formats/docx-output.js"; +import { writePdfBinary } from "../public/formats/pdf-output.js"; +import { writeHtml } from "../public/formats/html.js"; +import { createDocumentModel } from "../public/core/document-model.js"; +import { ensureDocumentAudit } from "../public/core/document-audit.js"; + +// TXT round-trip preserves ordinary underscores, indentation, and single line breaks. +const sourceText = " field__id__legacy: A-102\r\nnext line\r\n\r\n second_field: ready\r"; +const textModel = readText({ content: sourceText, title: "english-form", format: "txt" }); +const textOutput = writeText({ model: textModel }).data; +assert.equal(textOutput, " field__id__legacy: A-102\nnext line\n\n second_field: ready\n"); + +// Without horizontal measurements, letter adjacency must not invent a word space. +const unmeasuredEnglish = analyzePageLayout([ + { str: "Inter", x: 0, y: 500, width: 0, height: 12 }, + { str: "national", x: 0, y: 500, width: 0, height: 12 }, +]); +assert.equal(unmeasuredEnglish.map((block) => block.text).join(" "), "International"); + +// Real geometry inserts a space only when the measured gap is large enough. +const measuredEnglish = analyzePageLayout([ + { str: "North", x: 0, y: 500, width: 34, height: 12, hasPosition: true, hasHorizontalGeometry: true }, + { str: "Star", x: 39, y: 500, width: 24, height: 12, hasPosition: true, hasHorizontalGeometry: true }, +]); +assert.equal(measuredEnglish.map((block) => block.text).join(" "), "North Star"); + +// A repeated two-column page is read down the left column, then down the right. +const columnItems = [ + ["Account ID", "ACCT-102"], + ["Customer name", "Jane Doe"], + ["Billing address", "42 Cedar Road"], +].flatMap(([leftText, rightText], index) => { + const y = 720 - index * 22; + return [ + { str: leftText, x: 54, y, width: 112, height: 12 }, + { str: rightText, x: 330, y, width: 128, height: 12 }, + ]; +}); +const columnBlocks = analyzePageLayout(columnItems); +assert.deepEqual(columnBlocks.map((block) => block.text), [ + "Account ID", "Customer name", "Billing address", + "ACCT-102", "Jane Doe", "42 Cedar Road", +]); + +// DOCX round-trip retains page geometry, paragraph tabs/indents, and table merges. +const docxModel = createDocumentModel({ + title: "English form", + sourceFormat: "docx", + blocks: [ + { + type: "paragraph", + text: "Reference:\tREF-204", + paragraphFormat: { + alignment: "left", + indentLeft: 360, + spacingBefore: 120, + spacingAfter: 80, + tabStops: [{ position: 2880, alignment: "left", leader: "dot" }], + }, + }, + { + type: "table", + headers: ["Applicant"], + rows: [["Name", "Jane Doe"], ["", "ACCT-102"]], + columnWidths: [2400, 6960], + cellSpans: [ + [{ columnSpan: 2 }], + [{ columnSpan: 1, verticalMerge: "restart" }, { columnSpan: 1 }], + [{ columnSpan: 1, verticalMerge: "continue" }, { columnSpan: 1 }], + ], + }, + ], + metadata: { + ooxml: { + pageLayout: { + width: 16838, + height: 11906, + orientation: "landscape", + marginLeft: 900, + marginRight: 900, + marginTop: 720, + marginBottom: 720, + headerDistance: 720, + footerDistance: 720, + gutter: 0, + }, + }, + }, +}); +const generatedDocx = writeDocx({ model: docxModel }); +const docxBytes = new Uint8Array(Buffer.from(generatedDocx.data.split(",")[1], "base64")); +const roundTrippedDocx = readDocx({ content: docxBytes, title: "English form" }); +const paragraph = roundTrippedDocx.blocks.find((block) => block.type === "paragraph"); +const table = roundTrippedDocx.blocks.find((block) => block.type === "table"); +assert.deepEqual(roundTrippedDocx.metadata.ooxml.pageLayout, docxModel.metadata.ooxml.pageLayout); +assert.deepEqual(paragraph.paragraphFormat, docxModel.blocks[0].paragraphFormat); +assert.deepEqual(table.columnWidths, [2400, 6960]); +assert.deepEqual(table.cellSpans, docxModel.blocks[1].cellSpans); +const generatedPdf = writePdfBinary({ model: docxModel }); +const generatedPdfText = Buffer.from(generatedPdf.data.split(",")[1], "base64").toString("latin1"); +assert.match(generatedPdfText, /\/MediaBox \[0 0 841\.9 595\.3\]/); +assert.equal(generatedPdf.warnings.some((warning) => warning.code === "PDF_DOCX_LAYOUT_APPROXIMATED"), true); +const generatedHtml = writeHtml({ model: docxModel }); +assert.match(generatedHtml.data, /

/); +assert.match(generatedHtml.data, /<\/colgroup>/); +assert.equal(generatedHtml.warnings.some((warning) => warning.code === "HTML_LAYOUT_APPROXIMATED"), true); + +const docxQuality = ensureDocumentAudit(docxModel, { reader: "docx", writer: "docx", targetFormat: "docx" }); +const textQuality = ensureDocumentAudit(textModel, { reader: "txt", writer: "txt", targetFormat: "txt" }); +assert.equal(docxQuality.metadata.qualityReport.layoutFidelity, "medium"); +assert.equal(textQuality.metadata.qualityReport.layoutFidelity, "not-applicable"); +const reflowedDocxQuality = ensureDocumentAudit({ + ...docxModel, + metadata: { ...docxModel.metadata, warnings: generatedPdf.warnings }, +}, { reader: "docx", writer: "pdf", targetFormat: "pdf" }); +assert.equal(reflowedDocxQuality.metadata.qualityReport.layoutFidelity, "low"); + +console.log("Layout offset regressions passed: TXT whitespace, PDF English spacing/columns, and DOCX form geometry."); diff --git a/scripts/smoke-test.js b/scripts/smoke-test.js index d9c3859..4beaa87 100644 --- a/scripts/smoke-test.js +++ b/scripts/smoke-test.js @@ -236,7 +236,7 @@ function createAdvancedDocxFixture() { Advanced Docx First item Nested item - Merged + MergedLegacy merged Main body `, @@ -442,7 +442,7 @@ test("DOCX reader emits structured inline nodes for runs and hyperlinks (P9-C)", assert.match(md, /Hello \[Example\]\(https:\/\/example\.com\)/); }); -test("DOCX input enhancement extracts lists, header/footer, footnotes, comments, merge warnings, and image alt text", () => { +test("DOCX input enhancement extracts lists, header/footer, footnotes, comments, merged cells, and image alt text", () => { const model = toDocumentModel(createAdvancedDocxFixture(), "docx", "advanced.docx"); assert.equal(validateDocumentModel(model).ok, true); assert.equal(model.blocks.some((block) => block.type === "list" && block.items.includes("First item")), true); @@ -452,6 +452,8 @@ test("DOCX input enhancement extracts lists, header/footer, footnotes, comments, assert.equal(model.blocks.some((block) => block.type === "paragraph" && block.text.includes("Comment text")), true); assert.equal(model.blocks.some((block) => block.type === "asset" && block.alt === "Logo alt text"), true); assert.equal(model.metadata.warnings.some((warning) => warning.code === "DOCX_TABLE_MERGE_APPROXIMATED"), true); + const mergedTable = model.blocks.find((block) => block.type === "table"); + assert.equal(mergedTable.cellSpans?.[0]?.[0]?.columnSpan, 2); assert.equal(model.metadata.ooxml.compressionMethods.includes(8), true); }); diff --git a/tests/snapshots/conversions/empty-md-to-json.json b/tests/snapshots/conversions/empty-md-to-json.json index 3c53a86..3e9ebd6 100644 --- a/tests/snapshots/conversions/empty-md-to-json.json +++ b/tests/snapshots/conversions/empty-md-to-json.json @@ -24,6 +24,7 @@ "tableFidelity": "not-applicable", "assetFidelity": "not-applicable", "textFidelity": "high", + "layoutFidelity": "not-applicable", "warningCount": 0, "warningsBySeverity": {}, "downgradeCount": 0