@a200888213/gbdocx 0.5.1 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +215 -207
- package/index.html +3 -2
- package/package.json +48 -48
- package/serve.mjs +3 -2
- package/src/app/file-io.js +122 -122
- package/src/app/main.js +9 -9
- package/src/app/word/catalog.js +52 -52
- package/src/app/word/comments.js +112 -112
- package/src/app/word/doc.js +113 -113
- package/src/app/word/edit.js +72 -72
- package/src/app/word/file.js +30 -1
- package/src/app/word/hf.js +76 -76
- package/src/app/word/layout.js +155 -155
- package/src/app/word/notes.js +110 -110
- package/src/app/word/shared.js +22 -22
- package/src/app/word/view.js +22 -6
- package/src/app/word-app.js +486 -467
- package/src/app/word-sheets.js +101 -101
- package/src/kernel/docx/codec/blocks.js +123 -123
- package/src/kernel/docx/codec/carry.js +129 -129
- package/src/kernel/docx/codec/comments.js +25 -25
- package/src/kernel/docx/codec/docx.js +198 -198
- package/src/kernel/docx/codec/docxStyles.js +177 -177
- package/src/kernel/docx/codec/fonts.js +195 -195
- package/src/kernel/docx/codec/helpers.js +161 -161
- package/src/kernel/docx/codec/hfHtml.js +152 -152
- package/src/kernel/docx/codec/html.js +739 -739
- package/src/kernel/docx/codec/losses.js +420 -420
- package/src/kernel/docx/codec/markdown.js +170 -170
- package/src/kernel/docx/codec/parts.js +249 -249
- package/src/kernel/docx/codec/read.js +603 -603
- package/src/kernel/docx/codec/render.js +1156 -1156
- package/src/kernel/docx/codec/roundtrip.js +236 -236
- package/src/kernel/docx/codec/write.js +833 -833
- package/src/kernel/docx/comments.js +14 -14
- package/src/kernel/docx/pageGeometry.js +123 -123
- package/src/kernel/docx/pagination.js +481 -481
- package/src/kernel/docx/watermark.js +45 -45
- package/src/kernel/editor/constants.js +8 -8
- package/src/kernel/editor/engine/blocks.js +594 -594
- package/src/kernel/editor/engine/blocksEnter.js +109 -109
- package/src/kernel/editor/engine/blocksInsert.js +254 -254
- package/src/kernel/editor/engine/blocksStructure.js +226 -226
- package/src/kernel/editor/engine/commands.js +181 -181
- package/src/kernel/editor/engine/dom.js +646 -646
- package/src/kernel/editor/engine/history.js +149 -149
- package/src/kernel/editor/engine/inline.js +656 -656
- package/src/kernel/editor/engine/input.js +554 -554
- package/src/kernel/editor/engine/interaction.js +137 -137
- package/src/kernel/editor/engine/pointer.js +39 -39
- package/src/kernel/editor/engine/revision.js +138 -138
- package/src/kernel/editor/engine/schema.js +417 -417
- package/src/kernel/editor/engine/selection.js +119 -119
- package/src/kernel/editor/engine/state.js +118 -118
- package/src/kernel/editor/engine/tableClip.js +154 -154
- package/src/kernel/editor/engine/tableGrid.js +55 -55
- package/src/kernel/editor/engine/tableInteraction.js +388 -388
- package/src/kernel/editor/engine/tableMenu.js +250 -250
- package/src/kernel/editor/engine/tableOps.js +174 -174
- package/src/kernel/editor/engine/tables.js +732 -732
- package/src/kernel/editor/overlayGeometry.js +20 -20
- package/src/kernel/editor/utils.js +48 -48
- package/src/kernel/keyboard.js +114 -114
- package/src/kernel/textStyles.js +84 -84
- package/src/kernel/util/imageFile.js +91 -91
- package/src/kernel/util/shortcutKey.js +33 -33
- package/src/surface/editor-surface.js +600 -600
- package/src/ui/color-panel.js +69 -69
- package/src/ui/context-menu.js +133 -133
- package/src/ui/find-bar.js +151 -151
- package/src/ui/icons.js +137 -135
- package/src/ui/menubar.js +28 -28
- package/src/ui/panels.js +115 -115
- package/src/ui/prompt.js +89 -89
- package/src/ui/ribbon.js +485 -485
- package/src/ui/special-chars.js +39 -39
- package/src/ui/statusbar.js +81 -81
- package/src/ui/toolbar.js +32 -32
- package/styles/editor-content.css +440 -440
- package/styles/tokens.css +154 -154
|
@@ -1,603 +1,603 @@
|
|
|
1
|
-
// [文件] web·docx·codec·read —— 解析:.docx 部件还原成 Document(正文 HTML 子集 + 页面设置 + 页眉页脚 + 批注 + 脚注尾注 + 文档属性 + 保存必丢清单)
|
|
2
|
-
/*
|
|
3
|
-
解析覆盖:段落与标题样式、对齐、缩进、行距、粗斜下划线删除线、字体颜色/字号/字体族与文字底色、
|
|
4
|
-
超链接、无序与有序列表、表格(列宽、单元格底色、横向与纵向合并)、内嵌图片(还原成 data URL)、
|
|
5
|
-
换行与分页符、sectPr 的纸张/方向/页边距/分栏、批注锚点、修订标记。页眉页脚只取纯文本。
|
|
6
|
-
另在读入时盘点「保存必丢」清单(见 losses.js):保存前据此向用户确认。
|
|
7
|
-
|
|
8
|
-
[坑] 旧版二进制 .doc 是 OLE 复合文档(魔数 D0CF)而不是 zip,直接交给 zip 解析只会得到
|
|
9
|
-
一句没头没尾的「不是有效的 docx 文件」,所以先按魔数拦掉并给出可照做的提示。
|
|
10
|
-
*/
|
|
11
|
-
import { REL_NS, hexColor, openOpc, parseNode } from 'gbooxml';
|
|
12
|
-
import { HF_MODE, PAGE_NUM_CHINESE, PAGE_NUM_DASH, PAGE_SIZES_TWIPS, round1, twipsToMM } from './docx.js';
|
|
13
|
-
import { PART_DOCUMENT, PART_ENDNOTES, PART_FOOTNOTES, PART_NUMBERING, PART_PROPS, PART_SETTINGS } from './parts.js';
|
|
14
|
-
import { parseComments } from './comments.js';
|
|
15
|
-
import { collectLosses } from './losses.js';
|
|
16
|
-
import { collectCarry } from './carry.js';
|
|
17
|
-
import { flattenSdt, renderBlocks, renderRuns } from './render.js';
|
|
18
|
-
import { tableStylesOf, themePalette } from './docxStyles.js';
|
|
19
|
-
import { hfHtmlOf } from './hfHtml.js';
|
|
20
|
-
import { attrFloat, attrIntOf } from './helpers.js';
|
|
21
|
-
|
|
22
|
-
/** 页码对齐白名单(其余值一律按左对齐读,避免把未知串当位置) */
|
|
23
|
-
const PAGE_NUM_ALIGNS = new Set(['left', 'center', 'right']);
|
|
24
|
-
|
|
25
|
-
/** 只有 PAGE 域占位(无任何正文)的页眉页脚归一为空:页码由 pageNumbers 单独承载,
|
|
26
|
-
* 写端在 pageNumbers.enabled 时必写一份只含 PAGE 域的页脚部件——不归一的话「开了页码但没写页脚文字」
|
|
27
|
-
* 会被读回成一段域占位 HTML,与模型口径不一致,保存自检当场拒存。
|
|
28
|
-
* [坑] 只认 PAGE:NUMPAGES/SECTIONPAGES 没有独立模型字段,一并剥掉等于把整段页眉页脚丢光。 */
|
|
29
|
-
const FIELD_SPAN_ONLY = /^(?:<span[^>]*\bdata-fld="PAGE"[^>]*><\/span>)+$/i;
|
|
30
|
-
const normalizeHf = (html) => {
|
|
31
|
-
const raw = String(html || '');
|
|
32
|
-
return FIELD_SPAN_ONLY.test(raw.trim()) ? '' : raw;
|
|
33
|
-
};
|
|
34
|
-
|
|
35
|
-
/** 页边距是否相同(跨栏连续节判定用) */
|
|
36
|
-
const sameMargins = (a, b) => {
|
|
37
|
-
const ma = a || {};
|
|
38
|
-
const mb = b || {};
|
|
39
|
-
return ['top', 'right', 'bottom', 'left'].every((side) => (ma[side] || 25.4) === (mb[side] || 25.4));
|
|
40
|
-
};
|
|
41
|
-
|
|
42
|
-
/** 跨栏连续节判定:本节是 continuous 且与下一节仅分栏数不同(Word 用连续节表达跨栏标题/栏切换),由 spanAll 机制处理 */
|
|
43
|
-
const isInlineSection = (cur, next) => {
|
|
44
|
-
if (!cur || !next || cur.type !== 'continuous') return false;
|
|
45
|
-
const a = cur.page;
|
|
46
|
-
const b = next.page;
|
|
47
|
-
if (!a || !b || (a.columns || 1) === (b.columns || 1)) return false;
|
|
48
|
-
return a.size === b.size && a.orientation === b.orientation && sameMargins(a.margins, b.margins);
|
|
49
|
-
};
|
|
50
|
-
|
|
51
|
-
/** 按长宽距离把 pgSz 归到最接近的内置纸张 */
|
|
52
|
-
const nearestPaper = (w, h) => {
|
|
53
|
-
let best = 'A4';
|
|
54
|
-
let bestD = 0;
|
|
55
|
-
let first = true;
|
|
56
|
-
for (const [name, [dw0, dh0]] of Object.entries(PAGE_SIZES_TWIPS)) {
|
|
57
|
-
const dw = dw0 - w;
|
|
58
|
-
const dh = dh0 - h;
|
|
59
|
-
const d = dw * dw + dh * dh;
|
|
60
|
-
if (first || d < bestD) {
|
|
61
|
-
first = false;
|
|
62
|
-
bestD = d;
|
|
63
|
-
best = name;
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
return best;
|
|
67
|
-
};
|
|
68
|
-
|
|
69
|
-
/* ---------- 编号表 ---------- */
|
|
70
|
-
|
|
71
|
-
/** numberingFormats 建立 numId → bullet|decimal 的映射(列表类型藏在 numbering.xml 里) */
|
|
72
|
-
const numberingFormats = (pkg) => {
|
|
73
|
-
const out = new Map();
|
|
74
|
-
const raw = pkg.part(PART_NUMBERING);
|
|
75
|
-
if (!raw) return out;
|
|
76
|
-
let tree;
|
|
77
|
-
try {
|
|
78
|
-
tree = parseNode(raw);
|
|
79
|
-
} catch {
|
|
80
|
-
return out;
|
|
81
|
-
}
|
|
82
|
-
const abstract = new Map();
|
|
83
|
-
for (const an of tree.children('abstractNum')) {
|
|
84
|
-
const lvl = an.child('lvl');
|
|
85
|
-
if (!lvl) continue;
|
|
86
|
-
const nf = lvl.child('numFmt');
|
|
87
|
-
if (!nf) continue;
|
|
88
|
-
// 待办列表(本项目写出端)用勾选字形区分:lvlText 是 ☑/☐ 时映射回 task 语义
|
|
89
|
-
const glyph = lvl.child('lvlText')?.attr('val') || '';
|
|
90
|
-
const task = glyph === '☑' ? 'checked' : glyph === '☐' ? 'unchecked' : '';
|
|
91
|
-
abstract.set(an.attr('abstractNumId'), { kind: nf.attr('val') === 'bullet' ? 'ul' : 'ol', task });
|
|
92
|
-
}
|
|
93
|
-
for (const num of tree.children('num')) {
|
|
94
|
-
const ref = num.child('abstractNumId');
|
|
95
|
-
if (ref && abstract.has(ref.attr('val'))) out.set(num.attr('numId'), abstract.get(ref.attr('val')));
|
|
96
|
-
}
|
|
97
|
-
return out;
|
|
98
|
-
};
|
|
99
|
-
|
|
100
|
-
/* ---------- 页眉页脚小工具 ---------- */
|
|
101
|
-
|
|
102
|
-
/** 页眉页脚段落的对齐(页码位置读回来靠它;缺省左对齐) */
|
|
103
|
-
const hfAlign = (tree) => {
|
|
104
|
-
const jc = tree.find('p', 'pPr', 'jc');
|
|
105
|
-
if (jc) {
|
|
106
|
-
const v = jc.attr('val');
|
|
107
|
-
if (PAGE_NUM_ALIGNS.has(v)) return v;
|
|
108
|
-
}
|
|
109
|
-
return 'left';
|
|
110
|
-
};
|
|
111
|
-
|
|
112
|
-
/** 从 w:pgNumType 取编号格式与起始页码(只是「设置」,不代表页脚里真有 PAGE 域) */
|
|
113
|
-
const pgNumOf = (sect) => {
|
|
114
|
-
const nt = sect.child('pgNumType');
|
|
115
|
-
if (!nt) return null;
|
|
116
|
-
const pn = {};
|
|
117
|
-
const fmt = nt.attr('fmt');
|
|
118
|
-
if (fmt === 'chineseCounting') pn.format = PAGE_NUM_CHINESE;
|
|
119
|
-
// 公文页码「- 1 -」就是 numberInDash,不认就等于把页码样式丢掉
|
|
120
|
-
else if (fmt === 'numberInDash') pn.format = PAGE_NUM_DASH;
|
|
121
|
-
const start = attrIntOf(nt, 'start');
|
|
122
|
-
if (start > 0) pn.start = start;
|
|
123
|
-
return Object.keys(pn).length ? pn : null;
|
|
124
|
-
};
|
|
125
|
-
|
|
126
|
-
/** 从 "font-family:Arial;font-size:120pt" 这类 style 串里取指定属性的数值 */
|
|
127
|
-
const attrOfStyle = (style, key) => {
|
|
128
|
-
for (const part of String(style || '').split(';')) {
|
|
129
|
-
const idx = part.indexOf(':');
|
|
130
|
-
if (idx < 0) continue;
|
|
131
|
-
if (part.slice(0, idx).trim() !== key) continue;
|
|
132
|
-
const v = Number.parseFloat(part.slice(idx + 1).trim().replace(/pt$/, ''));
|
|
133
|
-
return Number.isNaN(v) ? 0 : v;
|
|
134
|
-
}
|
|
135
|
-
return 0;
|
|
136
|
-
};
|
|
137
|
-
|
|
138
|
-
/* ---------- 脚注 / 尾注 / 文档属性 ---------- */
|
|
139
|
-
|
|
140
|
-
/**
|
|
141
|
-
* 脚注/尾注回读:id 与正文锚点对得上,text 是写出保底(多段/富文本压成一段纯文本)。
|
|
142
|
-
* separator 占位条目(Word 每份文档都带)不计入。
|
|
143
|
-
*/
|
|
144
|
-
const readNotes = (pkg, part, tag) => {
|
|
145
|
-
const raw = pkg.part(part);
|
|
146
|
-
if (!raw) return [];
|
|
147
|
-
let tree;
|
|
148
|
-
try {
|
|
149
|
-
tree = parseNode(raw);
|
|
150
|
-
} catch {
|
|
151
|
-
return [];
|
|
152
|
-
}
|
|
153
|
-
return tree
|
|
154
|
-
.children(tag)
|
|
155
|
-
.filter((n) => n.attr('type') !== 'separator' && n.attr('type') !== 'continuationSeparator')
|
|
156
|
-
.map((n) => ({ id: n.attr('id'), text: n.texts().join(' ') }));
|
|
157
|
-
};
|
|
158
|
-
|
|
159
|
-
/** 读 docProps/core.xml(标题/主题/作者/备注/最后修改者;缺部件或损坏 = 无) */
|
|
160
|
-
const readProps = (pkg) => {
|
|
161
|
-
const raw = pkg.part(PART_PROPS);
|
|
162
|
-
if (!raw) return null;
|
|
163
|
-
let tree;
|
|
164
|
-
try {
|
|
165
|
-
tree = parseNode(raw);
|
|
166
|
-
} catch {
|
|
167
|
-
return null;
|
|
168
|
-
}
|
|
169
|
-
const pick = (tag) => {
|
|
170
|
-
const n = tree.child(tag);
|
|
171
|
-
return n ? n.text.trim() : '';
|
|
172
|
-
};
|
|
173
|
-
const props = {
|
|
174
|
-
title: pick('title'),
|
|
175
|
-
subject: pick('subject'),
|
|
176
|
-
creator: pick('creator'),
|
|
177
|
-
description: pick('description'),
|
|
178
|
-
lastModifiedBy: pick('lastModifiedBy')
|
|
179
|
-
};
|
|
180
|
-
return Object.values(props).some((v) => v !== '') ? props : null;
|
|
181
|
-
};
|
|
182
|
-
|
|
183
|
-
/** settings.xml 的 w:defaultTabStop(twips;缺省 720 = 0.5 英寸);tab 的显示宽度按它折算 */
|
|
184
|
-
const defaultTabStopOf = (pkg) => {
|
|
185
|
-
const raw = pkg.part(PART_SETTINGS);
|
|
186
|
-
if (!raw) return 720;
|
|
187
|
-
try {
|
|
188
|
-
const v = attrIntOf(parseNode(raw).child('defaultTabStop'), 'val');
|
|
189
|
-
return v > 0 ? v : 720;
|
|
190
|
-
} catch {
|
|
191
|
-
return 720;
|
|
192
|
-
}
|
|
193
|
-
};
|
|
194
|
-
|
|
195
|
-
/** settings.xml 的 w:characterSpacingControl:compressPunctuation 时全角标点按半角排(Word/WPS 中文缺省) */
|
|
196
|
-
const compressPunctOf = (pkg) => {
|
|
197
|
-
const raw = pkg.part(PART_SETTINGS);
|
|
198
|
-
if (!raw) return false;
|
|
199
|
-
try {
|
|
200
|
-
return parseNode(raw).child('characterSpacingControl')?.attr('val') === 'compressPunctuation';
|
|
201
|
-
} catch {
|
|
202
|
-
return false;
|
|
203
|
-
}
|
|
204
|
-
};
|
|
205
|
-
|
|
206
|
-
/* ---------- 读回上下文 ---------- */
|
|
207
|
-
|
|
208
|
-
/** 读回上下文(正文渲染共用:render.js 的函数都接收本实例) */
|
|
209
|
-
export class DocxReader {
|
|
210
|
-
constructor(pkg) {
|
|
211
|
-
this.pkg = pkg;
|
|
212
|
-
this.docRel = pkg.rels(PART_DOCUMENT);
|
|
213
|
-
this.numFmt = numberingFormats(pkg);
|
|
214
|
-
/** 主题调色板(themeColor 在 val 无效时的显示兜底;无主题部件为 null) */
|
|
215
|
-
this.theme = themePalette(pkg);
|
|
216
|
-
/** 表样式定义表(styleId → 边框/边距/首行与隔行条件;tblStyle 渲染时摊平) */
|
|
217
|
-
this.tableStyles = tableStylesOf(pkg);
|
|
218
|
-
/** 默认制表位(twips;tab 渲染宽度与写出 settings 共用这一份读数) */
|
|
219
|
-
this.tabStop = defaultTabStopOf(pkg);
|
|
220
|
-
/** 标点挤压(settings 的 characterSpacingControl=compressPunctuation) */
|
|
221
|
-
this.compressPunct = compressPunctOf(pkg);
|
|
222
|
-
/** 顶层里属于单栏节的块(多栏文档的跨栏标题) */
|
|
223
|
-
this.spanAt = new Set();
|
|
224
|
-
/** 纯分节段落(没有文字,丢弃) */
|
|
225
|
-
this.dropAt = new Set();
|
|
226
|
-
/** 要输出节边界标记的段落索引(collectSections 填充;跨栏连续节不在此列) */
|
|
227
|
-
this.emitSecAt = new Set();
|
|
228
|
-
/** 脚注/尾注 id → 显示序号(按各自序列的出现位置,render 渲染锚点时用) */
|
|
229
|
-
this.noteOrdFn = new Map();
|
|
230
|
-
this.noteOrdEn = new Map();
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
/** pageConfOf 从单个 sectPr 取页面设置(正文转换依赖分栏数,必须先于正文解析) */
|
|
234
|
-
pageConfOf(sect) {
|
|
235
|
-
if (!sect) return [null, ''];
|
|
236
|
-
const pc = { size: 'A4', orientation: 'portrait' };
|
|
237
|
-
let hfMode = '';
|
|
238
|
-
const sz = sect.child('pgSz');
|
|
239
|
-
if (sz) {
|
|
240
|
-
let w = attrIntOf(sz, 'w');
|
|
241
|
-
let h = attrIntOf(sz, 'h');
|
|
242
|
-
if (sz.attr('orient') === 'landscape' || w > h) {
|
|
243
|
-
pc.orientation = 'landscape';
|
|
244
|
-
const swap = w;
|
|
245
|
-
w = h;
|
|
246
|
-
h = swap;
|
|
247
|
-
}
|
|
248
|
-
pc.size = nearestPaper(w, h);
|
|
249
|
-
}
|
|
250
|
-
const mar = sect.child('pgMar');
|
|
251
|
-
if (mar) {
|
|
252
|
-
const m = { top: 25.4, right: 25.4, bottom: 25.4, left: 25.4 };
|
|
253
|
-
let v = attrIntOf(mar, 'top');
|
|
254
|
-
if (v > 0) m.top = round1(twipsToMM(v));
|
|
255
|
-
v = attrIntOf(mar, 'right');
|
|
256
|
-
if (v > 0) m.right = round1(twipsToMM(v));
|
|
257
|
-
v = attrIntOf(mar, 'bottom');
|
|
258
|
-
if (v > 0) m.bottom = round1(twipsToMM(v));
|
|
259
|
-
v = attrIntOf(mar, 'left');
|
|
260
|
-
if (v > 0) m.left = round1(twipsToMM(v));
|
|
261
|
-
pc.margins = m;
|
|
262
|
-
// 页眉页脚距纸张边缘:Word 的默认值(720 twips)不回写,免得每份文档都挂一对冗余字段
|
|
263
|
-
v = attrIntOf(mar, 'header');
|
|
264
|
-
if (v > 0 && v !== 720) pc.headerTop = round1(twipsToMM(v));
|
|
265
|
-
v = attrIntOf(mar, 'footer');
|
|
266
|
-
if (v > 0 && v !== 720) pc.footerBottom = round1(twipsToMM(v));
|
|
267
|
-
}
|
|
268
|
-
if (sect.child('titlePg')) {
|
|
269
|
-
// 「首页不同」但没给首页部件:编辑器的口径是「除首页外每页显示」
|
|
270
|
-
hfMode = HF_MODE.EXCEPT_FIRST;
|
|
271
|
-
}
|
|
272
|
-
const cols = sect.child('cols');
|
|
273
|
-
if (cols) {
|
|
274
|
-
const n = attrIntOf(cols, 'num');
|
|
275
|
-
if (n > 1) {
|
|
276
|
-
pc.columns = n;
|
|
277
|
-
const sp = attrIntOf(cols, 'space');
|
|
278
|
-
if (sp > 0) pc.colGap = round1(twipsToMM(sp));
|
|
279
|
-
pc.colSeparator = cols.attr('sep') === '1';
|
|
280
|
-
// 每列自定义宽度(w:col 子元素):渲染按等宽近似,定义原样往返
|
|
281
|
-
const defs = cols.children('col').map((c) => ({ w: attrIntOf(c, 'w'), space: attrIntOf(c, 'space') }));
|
|
282
|
-
if (defs.some((c) => c.w > 0 || c.space > 0)) pc.colWidths = defs;
|
|
283
|
-
}
|
|
284
|
-
}
|
|
285
|
-
return [pc, hfMode];
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
/** 一节的节属性读数(type 缺省 = nextPage;分栏数供跨栏判定) */
|
|
289
|
-
sectionConfOf(sect) {
|
|
290
|
-
const [page, hfMode] = this.pageConfOf(sect);
|
|
291
|
-
const type = sect.child('type');
|
|
292
|
-
return { type: type ? type.attr('val') : '', page, hfMode };
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
/** collectSections 全部节(文档序:内嵌 sectPr 逐节 + 末节收尾);跨栏连续节剔除并记入 emitSecAt
|
|
296
|
-
* [设计] 跨栏连续节(与相邻节仅分栏数不同的 continuous 节)沿用既有 spanAll 机制,
|
|
297
|
-
* 不作为多节边界输出——否则「跨栏标题」会被渲染/写回成一次多余的节切换 */
|
|
298
|
-
collectSections(body) {
|
|
299
|
-
const kids = flattenSdt(body.kids);
|
|
300
|
-
const at = [];
|
|
301
|
-
kids.forEach((n, i) => {
|
|
302
|
-
if (n.name !== 'p') return;
|
|
303
|
-
const sect = n.find('pPr', 'sectPr');
|
|
304
|
-
if (sect) at.push({ i, sect });
|
|
305
|
-
});
|
|
306
|
-
const lastSect = body.child('sectPr');
|
|
307
|
-
// [坑] 每节的页眉/页脚/页码/水印必须在此读进节配置(sectionHf 归还 conf):
|
|
308
|
-
// 否则打开一份带页眉页码的 .docx 时这些外观全读不回来,保存自检也会因模型与读回不一致而拒存
|
|
309
|
-
// [设计] 按文档序逐节读、把上一节传进去:Word 里没有 headerReference/footerReference 的节
|
|
310
|
-
// 继承上一节的页眉页脚,不继承会让「链接到前一节」的普通多节文档整段页眉页脚消失。
|
|
311
|
-
const all = [];
|
|
312
|
-
const readSection = (sect) => {
|
|
313
|
-
all.push(this.sectionHf(this.sectionConfOf(sect), sect, all[all.length - 1]));
|
|
314
|
-
};
|
|
315
|
-
for (const { sect } of at) readSection(sect);
|
|
316
|
-
if (lastSect) readSection(lastSect);
|
|
317
|
-
const emit = new Set();
|
|
318
|
-
const kept = [];
|
|
319
|
-
all.forEach((conf, idx) => {
|
|
320
|
-
if (isInlineSection(conf, all[idx + 1])) return;
|
|
321
|
-
kept.push(conf);
|
|
322
|
-
if (idx < at.length) emit.add(at[idx].i);
|
|
323
|
-
});
|
|
324
|
-
this.emitSecAt = emit;
|
|
325
|
-
return kept;
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
/** markSpanSections 找出段落内嵌的 sectPr(分节符):多栏文档里属于单栏节的块就是跨栏块 */
|
|
329
|
-
markSpanSections(body) {
|
|
330
|
-
let pending = [];
|
|
331
|
-
// 与渲染侧同一份展开序列(内容控件视作透明容器),两边索引必须一致才能对上 spanAt/dropAt
|
|
332
|
-
flattenSdt(body.kids).forEach((n, i) => {
|
|
333
|
-
const name = n.name;
|
|
334
|
-
if (name !== 'p' && name !== 'tbl') return;
|
|
335
|
-
if (name === 'p') {
|
|
336
|
-
const sect = n.find('pPr', 'sectPr');
|
|
337
|
-
if (sect) {
|
|
338
|
-
if (attrIntOf(sect.child('cols'), 'num') <= 1) {
|
|
339
|
-
for (const j of pending) this.spanAt.add(j);
|
|
340
|
-
this.spanAt.add(i);
|
|
341
|
-
}
|
|
342
|
-
if (this.renderRunsHtml(n).trim() === '') this.dropAt.add(i); // 纯分节段落
|
|
343
|
-
pending = [];
|
|
344
|
-
return;
|
|
345
|
-
}
|
|
346
|
-
}
|
|
347
|
-
pending.push(i);
|
|
348
|
-
});
|
|
349
|
-
}
|
|
350
|
-
|
|
351
|
-
/* ---------- 页眉页脚 ---------- */
|
|
352
|
-
|
|
353
|
-
/**
|
|
354
|
-
* 把一节 sectPr 的页眉/页脚/页码/水印读进该节配置(部件按引用查,不扫目录)
|
|
355
|
-
* [设计] 走引用而不是扫 word/header*:奇偶各一份时,只有引用上的 type 能区分哪份是偶数页,
|
|
356
|
-
* 扫目录会把偶数页那份当成奇数页(部件按名排序 header1 在前,正好也是错的那一侧)。
|
|
357
|
-
*/
|
|
358
|
-
sectionHf(conf, sect, prev) {
|
|
359
|
-
/** 本节是否有该类页眉页脚引用(没有 = 继承上一节) */
|
|
360
|
-
const has = (tag, typ) => this.hfPartName(sect, tag, typ) !== '';
|
|
361
|
-
const inheritPrev = (key, fallback) => {
|
|
362
|
-
if (prev && prev[key] !== undefined) conf[key] = prev[key];
|
|
363
|
-
else if (fallback !== undefined) conf[key] = fallback;
|
|
364
|
-
};
|
|
365
|
-
|
|
366
|
-
if (has('headerReference', 'default')) {
|
|
367
|
-
conf.header = normalizeHf(this.hfHtml(sect, 'headerReference', 'default'));
|
|
368
|
-
conf.watermark = this.watermark(sect, 'headerReference', 'default');
|
|
369
|
-
} else {
|
|
370
|
-
inheritPrev('header', '');
|
|
371
|
-
// 水印是页眉里的图形,随页眉一起继承;本节有自己的页眉就不再继承上一节的水印
|
|
372
|
-
inheritPrev('watermark', null);
|
|
373
|
-
if (conf.watermark) conf.watermark = { ...conf.watermark };
|
|
374
|
-
}
|
|
375
|
-
|
|
376
|
-
if (has('footerReference', 'default')) {
|
|
377
|
-
conf.footer = normalizeHf(this.hfHtml(sect, 'footerReference', 'default'));
|
|
378
|
-
conf.pageNumbers = this.hfFooter(sect, 'footerReference', 'default');
|
|
379
|
-
} else {
|
|
380
|
-
inheritPrev('footer', '');
|
|
381
|
-
inheritPrev('pageNumbers', null);
|
|
382
|
-
if (conf.pageNumbers) conf.pageNumbers = { ...conf.pageNumbers };
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
const even = this.hasEvenOddHeaders();
|
|
386
|
-
const first = conf.hfMode === HF_MODE.EXCEPT_FIRST;
|
|
387
|
-
conf.hfMode = even && first ? HF_MODE.ODD_EVEN_FIRST
|
|
388
|
-
: even ? HF_MODE.ODD_EVEN
|
|
389
|
-
: first ? HF_MODE.EXCEPT_FIRST
|
|
390
|
-
: HF_MODE.ALL;
|
|
391
|
-
|
|
392
|
-
if (even) {
|
|
393
|
-
if (has('headerReference', 'even')) conf.headerEven = normalizeHf(this.hfHtml(sect, 'headerReference', 'even'));
|
|
394
|
-
else inheritPrev('headerEven', '');
|
|
395
|
-
if (has('footerReference', 'even')) conf.footerEven = normalizeHf(this.hfHtml(sect, 'footerReference', 'even'));
|
|
396
|
-
else inheritPrev('footerEven', '');
|
|
397
|
-
const evenNum = has('footerReference', 'even') ? this.hfFooter(sect, 'footerReference', 'even') : null;
|
|
398
|
-
if (!conf.pageNumbers && evenNum) conf.pageNumbers = evenNum;
|
|
399
|
-
}
|
|
400
|
-
|
|
401
|
-
// 「首页不同」的页眉页脚独立成对:缺引用同样继承上一节;首页没有内容就是空白页眉页脚
|
|
402
|
-
// [坑] 首页部件不走 normalizeHf:默认/偶数页的「只有 PAGE 域」由 pageNumbers 承载,
|
|
403
|
-
// 但首页页码没有独立字段,剥掉域占位会让「首页只有页码」保存后凭空消失
|
|
404
|
-
if (first) {
|
|
405
|
-
if (has('headerReference', 'first')) conf.headerFirst = this.hfHtml(sect, 'headerReference', 'first');
|
|
406
|
-
else inheritPrev('headerFirst', '');
|
|
407
|
-
if (has('footerReference', 'first')) conf.footerFirst = this.hfHtml(sect, 'footerReference', 'first');
|
|
408
|
-
else inheritPrev('footerFirst', '');
|
|
409
|
-
const firstNum = has('footerReference', 'first') ? this.hfFooter(sect, 'footerReference', 'first') : null;
|
|
410
|
-
if (!conf.pageNumbers && firstNum) conf.pageNumbers = firstNum;
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
// 编号格式与起始页码挂在节上(页脚里的 PAGE 域只说明「有页码」)。
|
|
414
|
-
// [坑] 只有 pgNumType、没有 PAGE 域时不能把页码打开,否则会凭设置凭空显示出一串页码。
|
|
415
|
-
const num = pgNumOf(sect);
|
|
416
|
-
if (num) {
|
|
417
|
-
if (!conf.pageNumbers) conf.pageNumbers = { enabled: false, ...num };
|
|
418
|
-
else Object.assign(conf.pageNumbers, num);
|
|
419
|
-
}
|
|
420
|
-
return conf;
|
|
421
|
-
}
|
|
422
|
-
|
|
423
|
-
/** 按引用类型与 r:id 找到部件路径(关系 target 是相对部件所在目录的路径) */
|
|
424
|
-
hfPartName(sect, tag, typ) {
|
|
425
|
-
for (const ref of sect.children(tag)) {
|
|
426
|
-
if (ref.attr('type') !== typ) continue;
|
|
427
|
-
const rel = this.docRel.get(ref.attrNS(REL_NS, 'id'));
|
|
428
|
-
if (!rel) continue;
|
|
429
|
-
const t = (rel.target || '').trim().replace(/^\.\//, '');
|
|
430
|
-
if (t.startsWith('/')) return t.slice(1);
|
|
431
|
-
return `word/${t}`;
|
|
432
|
-
}
|
|
433
|
-
return '';
|
|
434
|
-
}
|
|
435
|
-
|
|
436
|
-
/** 取指定引用的页眉/页脚受限 HTML(富文本:格式 + 域占位;见 hfHtmlOf) */
|
|
437
|
-
hfHtml(sect, tag, typ) {
|
|
438
|
-
const name = this.hfPartName(sect, tag, typ);
|
|
439
|
-
if (!name) return '';
|
|
440
|
-
const raw = this.pkg.part(name);
|
|
441
|
-
if (!raw) return '';
|
|
442
|
-
try {
|
|
443
|
-
// 页眉页脚里的超链接,r:id 指向页眉页脚部件自己的 .rels,不是 document.xml 的
|
|
444
|
-
return hfHtmlOf({ docRel: this.pkg.rels(name) }, parseNode(raw));
|
|
445
|
-
} catch {
|
|
446
|
-
return '';
|
|
447
|
-
}
|
|
448
|
-
}
|
|
449
|
-
|
|
450
|
-
/**
|
|
451
|
-
* 从页眉部件的 VML 里取回水印
|
|
452
|
-
* [设计] 水印只认 v:textpath 的 string:Word 的水印就是页眉里那张旋转文字图,
|
|
453
|
-
* 没有别的地方记这个数据,不回读就等于保存一次把水印静默丢掉。
|
|
454
|
-
*/
|
|
455
|
-
watermark(sect, tag, typ) {
|
|
456
|
-
const name = this.hfPartName(sect, tag, typ);
|
|
457
|
-
if (!name) return null;
|
|
458
|
-
const raw = this.pkg.part(name);
|
|
459
|
-
if (!raw) return null;
|
|
460
|
-
let tree;
|
|
461
|
-
try {
|
|
462
|
-
tree = parseNode(raw);
|
|
463
|
-
} catch {
|
|
464
|
-
return null;
|
|
465
|
-
}
|
|
466
|
-
let text = null;
|
|
467
|
-
const find = (n) => {
|
|
468
|
-
if (text) return;
|
|
469
|
-
if (n.name === 'textpath' && n.attr('string') !== '') {
|
|
470
|
-
text = n;
|
|
471
|
-
return;
|
|
472
|
-
}
|
|
473
|
-
for (const k of n.kids) find(k);
|
|
474
|
-
};
|
|
475
|
-
find(tree);
|
|
476
|
-
if (!text) return null;
|
|
477
|
-
const wm = { data: text.attr('string') };
|
|
478
|
-
const size = attrOfStyle(text.attr('style'), 'font-size');
|
|
479
|
-
if (size > 0) wm.size = size;
|
|
480
|
-
// 颜色在 shape 的 fillcolor 上,透明度在 v:fill 的 opacity 上(都在同一个 shape 里)
|
|
481
|
-
const findShape = (n) => {
|
|
482
|
-
if (n.attr('fillcolor') !== '') return n;
|
|
483
|
-
for (const k of n.kids) {
|
|
484
|
-
const hit = findShape(k);
|
|
485
|
-
if (hit) return hit;
|
|
486
|
-
}
|
|
487
|
-
return null;
|
|
488
|
-
};
|
|
489
|
-
const shape = findShape(tree);
|
|
490
|
-
if (shape) {
|
|
491
|
-
// 颜色按合法十六进制收敛:文件里的任意字符串不能直接进模型(写出端会把它拼进 XML 属性)
|
|
492
|
-
const fill = hexColor(shape.attr('fillcolor'), '');
|
|
493
|
-
if (fill) wm.color = `#${fill}`;
|
|
494
|
-
// [坑] 解析不出就别写 0:前端用「缺省值 + 覆盖」合并文档模型,写 0 会把默认透明度顶成全透明
|
|
495
|
-
const fillNode = shape.child('fill');
|
|
496
|
-
if (fillNode) {
|
|
497
|
-
const v = attrFloat(fillNode, 'opacity');
|
|
498
|
-
if (v > 0) wm.opacity = v;
|
|
499
|
-
}
|
|
500
|
-
}
|
|
501
|
-
return wm;
|
|
502
|
-
}
|
|
503
|
-
|
|
504
|
-
/** 页脚的页码设置(PAGE 域即开关,段落对齐即页码位置);没有 PAGE 域返回 null */
|
|
505
|
-
hfFooter(sect, tag, typ) {
|
|
506
|
-
const name = this.hfPartName(sect, tag, typ);
|
|
507
|
-
if (!name) return null;
|
|
508
|
-
const raw = this.pkg.part(name);
|
|
509
|
-
if (!raw) return null;
|
|
510
|
-
let tree;
|
|
511
|
-
try {
|
|
512
|
-
tree = parseNode(raw);
|
|
513
|
-
} catch {
|
|
514
|
-
return null;
|
|
515
|
-
}
|
|
516
|
-
let hasPage = false;
|
|
517
|
-
const walk = (n) => {
|
|
518
|
-
for (const k of n.kids) {
|
|
519
|
-
// 按域码精确比对:'NUMPAGES'.includes('PAGE') 会误判(旧口径的坑)
|
|
520
|
-
if (k.name === 'instrText' && (k.text.trim().toUpperCase().split(/\s+/)[0] || '') === 'PAGE') hasPage = true;
|
|
521
|
-
// 简单域形式:<w:fldSimple w:instr=" PAGE ">
|
|
522
|
-
if (k.name === 'fldSimple' && (k.attr('instr').trim().toUpperCase().split(/\s+/)[0] || '') === 'PAGE') hasPage = true;
|
|
523
|
-
walk(k);
|
|
524
|
-
}
|
|
525
|
-
};
|
|
526
|
-
walk(tree);
|
|
527
|
-
return hasPage ? { enabled: true, align: hfAlign(tree) } : null;
|
|
528
|
-
}
|
|
529
|
-
|
|
530
|
-
/** settings.xml 里声明了奇偶页不同(只挂 even 引用而没声明,Word 会忽略偶数页部件) */
|
|
531
|
-
hasEvenOddHeaders() {
|
|
532
|
-
const raw = this.pkg.part(PART_SETTINGS);
|
|
533
|
-
if (!raw) return false;
|
|
534
|
-
try {
|
|
535
|
-
return parseNode(raw).child('evenAndOddHeaders') !== null;
|
|
536
|
-
} catch {
|
|
537
|
-
return false;
|
|
538
|
-
}
|
|
539
|
-
}
|
|
540
|
-
|
|
541
|
-
/* ---------- 正文(实现见 render.js;方法名与 Go 逐条对应) ---------- */
|
|
542
|
-
|
|
543
|
-
blocksHtml(parent, top) {
|
|
544
|
-
return renderBlocks(this, parent, top);
|
|
545
|
-
}
|
|
546
|
-
|
|
547
|
-
renderRunsHtml(p) {
|
|
548
|
-
return renderRuns(this, p);
|
|
549
|
-
}
|
|
550
|
-
}
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
/**
|
|
554
|
-
* 把 .docx 字节解析成 Document(读方向总入口)
|
|
555
|
-
* @param {Uint8Array|ArrayBuffer} data
|
|
556
|
-
* @returns {Promise<import('./docx.js').Document>}
|
|
557
|
-
*/
|
|
558
|
-
export async function readDocument(data) {
|
|
559
|
-
const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
|
|
560
|
-
if (bytes.length > 8 && bytes[0] === 0xd0 && bytes[1] === 0xcf) {
|
|
561
|
-
throw new Error('旧版二进制 .doc 不支持,请先另存为 .docx');
|
|
562
|
-
}
|
|
563
|
-
let pkg;
|
|
564
|
-
try {
|
|
565
|
-
pkg = await openOpc(bytes);
|
|
566
|
-
} catch {
|
|
567
|
-
throw new Error('不是有效的 docx 文件');
|
|
568
|
-
}
|
|
569
|
-
const raw = pkg.part(PART_DOCUMENT);
|
|
570
|
-
if (!raw) throw new Error('docx 缺少 word/document.xml');
|
|
571
|
-
let tree;
|
|
572
|
-
try {
|
|
573
|
-
tree = parseNode(raw);
|
|
574
|
-
} catch (err) {
|
|
575
|
-
throw new Error(`无法解析 document.xml: ${err.message}`);
|
|
576
|
-
}
|
|
577
|
-
const body = tree.child('body');
|
|
578
|
-
if (!body) throw new Error('docx 缺少正文');
|
|
579
|
-
|
|
580
|
-
const rd = new DocxReader(pkg);
|
|
581
|
-
const doc = {};
|
|
582
|
-
// 全部节(按文档序,末节收尾):正文渲染与写回都以这个序列为基准
|
|
583
|
-
doc.sections = rd.collectSections(body);
|
|
584
|
-
const base = doc.sections[doc.sections.length - 1];
|
|
585
|
-
// 脚注/尾注的显示序号按各自序列的出现位置(readNotes 的返回顺序 = 文档顺序)
|
|
586
|
-
const footnotes = readNotes(pkg, PART_FOOTNOTES, 'footnote');
|
|
587
|
-
const endnotes = readNotes(pkg, PART_ENDNOTES, 'endnote');
|
|
588
|
-
footnotes.forEach((n, i) => rd.noteOrdFn.set(n.id, i + 1));
|
|
589
|
-
endnotes.forEach((n, i) => rd.noteOrdEn.set(n.id, i + 1));
|
|
590
|
-
// Word 把跨栏标题写成独立的单栏节,回读时映射成 col-span-all 块
|
|
591
|
-
if (base && base.page && base.page.columns > 1) rd.markSpanSections(body);
|
|
592
|
-
doc.html = rd.blocksHtml(body, true);
|
|
593
|
-
doc.comments = parseComments(pkg);
|
|
594
|
-
doc.footnotes = footnotes;
|
|
595
|
-
doc.endnotes = endnotes;
|
|
596
|
-
doc.props = readProps(pkg);
|
|
597
|
-
doc.defaultTabStop = rd.tabStop;
|
|
598
|
-
doc.compressPunctuation = rd.compressPunct;
|
|
599
|
-
doc.carry = collectCarry(pkg);
|
|
600
|
-
doc.losses = collectLosses(pkg, body);
|
|
601
|
-
return doc;
|
|
602
|
-
}
|
|
603
|
-
|
|
1
|
+
// [文件] web·docx·codec·read —— 解析:.docx 部件还原成 Document(正文 HTML 子集 + 页面设置 + 页眉页脚 + 批注 + 脚注尾注 + 文档属性 + 保存必丢清单)
|
|
2
|
+
/*
|
|
3
|
+
解析覆盖:段落与标题样式、对齐、缩进、行距、粗斜下划线删除线、字体颜色/字号/字体族与文字底色、
|
|
4
|
+
超链接、无序与有序列表、表格(列宽、单元格底色、横向与纵向合并)、内嵌图片(还原成 data URL)、
|
|
5
|
+
换行与分页符、sectPr 的纸张/方向/页边距/分栏、批注锚点、修订标记。页眉页脚只取纯文本。
|
|
6
|
+
另在读入时盘点「保存必丢」清单(见 losses.js):保存前据此向用户确认。
|
|
7
|
+
|
|
8
|
+
[坑] 旧版二进制 .doc 是 OLE 复合文档(魔数 D0CF)而不是 zip,直接交给 zip 解析只会得到
|
|
9
|
+
一句没头没尾的「不是有效的 docx 文件」,所以先按魔数拦掉并给出可照做的提示。
|
|
10
|
+
*/
|
|
11
|
+
import { REL_NS, hexColor, openOpc, parseNode } from 'gbooxml';
|
|
12
|
+
import { HF_MODE, PAGE_NUM_CHINESE, PAGE_NUM_DASH, PAGE_SIZES_TWIPS, round1, twipsToMM } from './docx.js';
|
|
13
|
+
import { PART_DOCUMENT, PART_ENDNOTES, PART_FOOTNOTES, PART_NUMBERING, PART_PROPS, PART_SETTINGS } from './parts.js';
|
|
14
|
+
import { parseComments } from './comments.js';
|
|
15
|
+
import { collectLosses } from './losses.js';
|
|
16
|
+
import { collectCarry } from './carry.js';
|
|
17
|
+
import { flattenSdt, renderBlocks, renderRuns } from './render.js';
|
|
18
|
+
import { tableStylesOf, themePalette } from './docxStyles.js';
|
|
19
|
+
import { hfHtmlOf } from './hfHtml.js';
|
|
20
|
+
import { attrFloat, attrIntOf } from './helpers.js';
|
|
21
|
+
|
|
22
|
+
/** 页码对齐白名单(其余值一律按左对齐读,避免把未知串当位置) */
|
|
23
|
+
const PAGE_NUM_ALIGNS = new Set(['left', 'center', 'right']);
|
|
24
|
+
|
|
25
|
+
/** 只有 PAGE 域占位(无任何正文)的页眉页脚归一为空:页码由 pageNumbers 单独承载,
|
|
26
|
+
* 写端在 pageNumbers.enabled 时必写一份只含 PAGE 域的页脚部件——不归一的话「开了页码但没写页脚文字」
|
|
27
|
+
* 会被读回成一段域占位 HTML,与模型口径不一致,保存自检当场拒存。
|
|
28
|
+
* [坑] 只认 PAGE:NUMPAGES/SECTIONPAGES 没有独立模型字段,一并剥掉等于把整段页眉页脚丢光。 */
|
|
29
|
+
const FIELD_SPAN_ONLY = /^(?:<span[^>]*\bdata-fld="PAGE"[^>]*><\/span>)+$/i;
|
|
30
|
+
const normalizeHf = (html) => {
|
|
31
|
+
const raw = String(html || '');
|
|
32
|
+
return FIELD_SPAN_ONLY.test(raw.trim()) ? '' : raw;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
/** 页边距是否相同(跨栏连续节判定用) */
|
|
36
|
+
const sameMargins = (a, b) => {
|
|
37
|
+
const ma = a || {};
|
|
38
|
+
const mb = b || {};
|
|
39
|
+
return ['top', 'right', 'bottom', 'left'].every((side) => (ma[side] || 25.4) === (mb[side] || 25.4));
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
/** 跨栏连续节判定:本节是 continuous 且与下一节仅分栏数不同(Word 用连续节表达跨栏标题/栏切换),由 spanAll 机制处理 */
|
|
43
|
+
const isInlineSection = (cur, next) => {
|
|
44
|
+
if (!cur || !next || cur.type !== 'continuous') return false;
|
|
45
|
+
const a = cur.page;
|
|
46
|
+
const b = next.page;
|
|
47
|
+
if (!a || !b || (a.columns || 1) === (b.columns || 1)) return false;
|
|
48
|
+
return a.size === b.size && a.orientation === b.orientation && sameMargins(a.margins, b.margins);
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
/** 按长宽距离把 pgSz 归到最接近的内置纸张 */
|
|
52
|
+
const nearestPaper = (w, h) => {
|
|
53
|
+
let best = 'A4';
|
|
54
|
+
let bestD = 0;
|
|
55
|
+
let first = true;
|
|
56
|
+
for (const [name, [dw0, dh0]] of Object.entries(PAGE_SIZES_TWIPS)) {
|
|
57
|
+
const dw = dw0 - w;
|
|
58
|
+
const dh = dh0 - h;
|
|
59
|
+
const d = dw * dw + dh * dh;
|
|
60
|
+
if (first || d < bestD) {
|
|
61
|
+
first = false;
|
|
62
|
+
bestD = d;
|
|
63
|
+
best = name;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return best;
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
/* ---------- 编号表 ---------- */
|
|
70
|
+
|
|
71
|
+
/** numberingFormats 建立 numId → bullet|decimal 的映射(列表类型藏在 numbering.xml 里) */
|
|
72
|
+
const numberingFormats = (pkg) => {
|
|
73
|
+
const out = new Map();
|
|
74
|
+
const raw = pkg.part(PART_NUMBERING);
|
|
75
|
+
if (!raw) return out;
|
|
76
|
+
let tree;
|
|
77
|
+
try {
|
|
78
|
+
tree = parseNode(raw);
|
|
79
|
+
} catch {
|
|
80
|
+
return out;
|
|
81
|
+
}
|
|
82
|
+
const abstract = new Map();
|
|
83
|
+
for (const an of tree.children('abstractNum')) {
|
|
84
|
+
const lvl = an.child('lvl');
|
|
85
|
+
if (!lvl) continue;
|
|
86
|
+
const nf = lvl.child('numFmt');
|
|
87
|
+
if (!nf) continue;
|
|
88
|
+
// 待办列表(本项目写出端)用勾选字形区分:lvlText 是 ☑/☐ 时映射回 task 语义
|
|
89
|
+
const glyph = lvl.child('lvlText')?.attr('val') || '';
|
|
90
|
+
const task = glyph === '☑' ? 'checked' : glyph === '☐' ? 'unchecked' : '';
|
|
91
|
+
abstract.set(an.attr('abstractNumId'), { kind: nf.attr('val') === 'bullet' ? 'ul' : 'ol', task });
|
|
92
|
+
}
|
|
93
|
+
for (const num of tree.children('num')) {
|
|
94
|
+
const ref = num.child('abstractNumId');
|
|
95
|
+
if (ref && abstract.has(ref.attr('val'))) out.set(num.attr('numId'), abstract.get(ref.attr('val')));
|
|
96
|
+
}
|
|
97
|
+
return out;
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
/* ---------- 页眉页脚小工具 ---------- */
|
|
101
|
+
|
|
102
|
+
/** 页眉页脚段落的对齐(页码位置读回来靠它;缺省左对齐) */
|
|
103
|
+
const hfAlign = (tree) => {
|
|
104
|
+
const jc = tree.find('p', 'pPr', 'jc');
|
|
105
|
+
if (jc) {
|
|
106
|
+
const v = jc.attr('val');
|
|
107
|
+
if (PAGE_NUM_ALIGNS.has(v)) return v;
|
|
108
|
+
}
|
|
109
|
+
return 'left';
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
/** 从 w:pgNumType 取编号格式与起始页码(只是「设置」,不代表页脚里真有 PAGE 域) */
|
|
113
|
+
const pgNumOf = (sect) => {
|
|
114
|
+
const nt = sect.child('pgNumType');
|
|
115
|
+
if (!nt) return null;
|
|
116
|
+
const pn = {};
|
|
117
|
+
const fmt = nt.attr('fmt');
|
|
118
|
+
if (fmt === 'chineseCounting') pn.format = PAGE_NUM_CHINESE;
|
|
119
|
+
// 公文页码「- 1 -」就是 numberInDash,不认就等于把页码样式丢掉
|
|
120
|
+
else if (fmt === 'numberInDash') pn.format = PAGE_NUM_DASH;
|
|
121
|
+
const start = attrIntOf(nt, 'start');
|
|
122
|
+
if (start > 0) pn.start = start;
|
|
123
|
+
return Object.keys(pn).length ? pn : null;
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
/** 从 "font-family:Arial;font-size:120pt" 这类 style 串里取指定属性的数值 */
|
|
127
|
+
const attrOfStyle = (style, key) => {
|
|
128
|
+
for (const part of String(style || '').split(';')) {
|
|
129
|
+
const idx = part.indexOf(':');
|
|
130
|
+
if (idx < 0) continue;
|
|
131
|
+
if (part.slice(0, idx).trim() !== key) continue;
|
|
132
|
+
const v = Number.parseFloat(part.slice(idx + 1).trim().replace(/pt$/, ''));
|
|
133
|
+
return Number.isNaN(v) ? 0 : v;
|
|
134
|
+
}
|
|
135
|
+
return 0;
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
/* ---------- 脚注 / 尾注 / 文档属性 ---------- */
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* 脚注/尾注回读:id 与正文锚点对得上,text 是写出保底(多段/富文本压成一段纯文本)。
|
|
142
|
+
* separator 占位条目(Word 每份文档都带)不计入。
|
|
143
|
+
*/
|
|
144
|
+
const readNotes = (pkg, part, tag) => {
|
|
145
|
+
const raw = pkg.part(part);
|
|
146
|
+
if (!raw) return [];
|
|
147
|
+
let tree;
|
|
148
|
+
try {
|
|
149
|
+
tree = parseNode(raw);
|
|
150
|
+
} catch {
|
|
151
|
+
return [];
|
|
152
|
+
}
|
|
153
|
+
return tree
|
|
154
|
+
.children(tag)
|
|
155
|
+
.filter((n) => n.attr('type') !== 'separator' && n.attr('type') !== 'continuationSeparator')
|
|
156
|
+
.map((n) => ({ id: n.attr('id'), text: n.texts().join(' ') }));
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
/** 读 docProps/core.xml(标题/主题/作者/备注/最后修改者;缺部件或损坏 = 无) */
|
|
160
|
+
const readProps = (pkg) => {
|
|
161
|
+
const raw = pkg.part(PART_PROPS);
|
|
162
|
+
if (!raw) return null;
|
|
163
|
+
let tree;
|
|
164
|
+
try {
|
|
165
|
+
tree = parseNode(raw);
|
|
166
|
+
} catch {
|
|
167
|
+
return null;
|
|
168
|
+
}
|
|
169
|
+
const pick = (tag) => {
|
|
170
|
+
const n = tree.child(tag);
|
|
171
|
+
return n ? n.text.trim() : '';
|
|
172
|
+
};
|
|
173
|
+
const props = {
|
|
174
|
+
title: pick('title'),
|
|
175
|
+
subject: pick('subject'),
|
|
176
|
+
creator: pick('creator'),
|
|
177
|
+
description: pick('description'),
|
|
178
|
+
lastModifiedBy: pick('lastModifiedBy')
|
|
179
|
+
};
|
|
180
|
+
return Object.values(props).some((v) => v !== '') ? props : null;
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
/** settings.xml 的 w:defaultTabStop(twips;缺省 720 = 0.5 英寸);tab 的显示宽度按它折算 */
|
|
184
|
+
const defaultTabStopOf = (pkg) => {
|
|
185
|
+
const raw = pkg.part(PART_SETTINGS);
|
|
186
|
+
if (!raw) return 720;
|
|
187
|
+
try {
|
|
188
|
+
const v = attrIntOf(parseNode(raw).child('defaultTabStop'), 'val');
|
|
189
|
+
return v > 0 ? v : 720;
|
|
190
|
+
} catch {
|
|
191
|
+
return 720;
|
|
192
|
+
}
|
|
193
|
+
};
|
|
194
|
+
|
|
195
|
+
/** settings.xml 的 w:characterSpacingControl:compressPunctuation 时全角标点按半角排(Word/WPS 中文缺省) */
|
|
196
|
+
const compressPunctOf = (pkg) => {
|
|
197
|
+
const raw = pkg.part(PART_SETTINGS);
|
|
198
|
+
if (!raw) return false;
|
|
199
|
+
try {
|
|
200
|
+
return parseNode(raw).child('characterSpacingControl')?.attr('val') === 'compressPunctuation';
|
|
201
|
+
} catch {
|
|
202
|
+
return false;
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
/* ---------- 读回上下文 ---------- */
|
|
207
|
+
|
|
208
|
+
/** 读回上下文(正文渲染共用:render.js 的函数都接收本实例) */
|
|
209
|
+
export class DocxReader {
|
|
210
|
+
constructor(pkg) {
|
|
211
|
+
this.pkg = pkg;
|
|
212
|
+
this.docRel = pkg.rels(PART_DOCUMENT);
|
|
213
|
+
this.numFmt = numberingFormats(pkg);
|
|
214
|
+
/** 主题调色板(themeColor 在 val 无效时的显示兜底;无主题部件为 null) */
|
|
215
|
+
this.theme = themePalette(pkg);
|
|
216
|
+
/** 表样式定义表(styleId → 边框/边距/首行与隔行条件;tblStyle 渲染时摊平) */
|
|
217
|
+
this.tableStyles = tableStylesOf(pkg);
|
|
218
|
+
/** 默认制表位(twips;tab 渲染宽度与写出 settings 共用这一份读数) */
|
|
219
|
+
this.tabStop = defaultTabStopOf(pkg);
|
|
220
|
+
/** 标点挤压(settings 的 characterSpacingControl=compressPunctuation) */
|
|
221
|
+
this.compressPunct = compressPunctOf(pkg);
|
|
222
|
+
/** 顶层里属于单栏节的块(多栏文档的跨栏标题) */
|
|
223
|
+
this.spanAt = new Set();
|
|
224
|
+
/** 纯分节段落(没有文字,丢弃) */
|
|
225
|
+
this.dropAt = new Set();
|
|
226
|
+
/** 要输出节边界标记的段落索引(collectSections 填充;跨栏连续节不在此列) */
|
|
227
|
+
this.emitSecAt = new Set();
|
|
228
|
+
/** 脚注/尾注 id → 显示序号(按各自序列的出现位置,render 渲染锚点时用) */
|
|
229
|
+
this.noteOrdFn = new Map();
|
|
230
|
+
this.noteOrdEn = new Map();
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** pageConfOf 从单个 sectPr 取页面设置(正文转换依赖分栏数,必须先于正文解析) */
|
|
234
|
+
pageConfOf(sect) {
|
|
235
|
+
if (!sect) return [null, ''];
|
|
236
|
+
const pc = { size: 'A4', orientation: 'portrait' };
|
|
237
|
+
let hfMode = '';
|
|
238
|
+
const sz = sect.child('pgSz');
|
|
239
|
+
if (sz) {
|
|
240
|
+
let w = attrIntOf(sz, 'w');
|
|
241
|
+
let h = attrIntOf(sz, 'h');
|
|
242
|
+
if (sz.attr('orient') === 'landscape' || w > h) {
|
|
243
|
+
pc.orientation = 'landscape';
|
|
244
|
+
const swap = w;
|
|
245
|
+
w = h;
|
|
246
|
+
h = swap;
|
|
247
|
+
}
|
|
248
|
+
pc.size = nearestPaper(w, h);
|
|
249
|
+
}
|
|
250
|
+
const mar = sect.child('pgMar');
|
|
251
|
+
if (mar) {
|
|
252
|
+
const m = { top: 25.4, right: 25.4, bottom: 25.4, left: 25.4 };
|
|
253
|
+
let v = attrIntOf(mar, 'top');
|
|
254
|
+
if (v > 0) m.top = round1(twipsToMM(v));
|
|
255
|
+
v = attrIntOf(mar, 'right');
|
|
256
|
+
if (v > 0) m.right = round1(twipsToMM(v));
|
|
257
|
+
v = attrIntOf(mar, 'bottom');
|
|
258
|
+
if (v > 0) m.bottom = round1(twipsToMM(v));
|
|
259
|
+
v = attrIntOf(mar, 'left');
|
|
260
|
+
if (v > 0) m.left = round1(twipsToMM(v));
|
|
261
|
+
pc.margins = m;
|
|
262
|
+
// 页眉页脚距纸张边缘:Word 的默认值(720 twips)不回写,免得每份文档都挂一对冗余字段
|
|
263
|
+
v = attrIntOf(mar, 'header');
|
|
264
|
+
if (v > 0 && v !== 720) pc.headerTop = round1(twipsToMM(v));
|
|
265
|
+
v = attrIntOf(mar, 'footer');
|
|
266
|
+
if (v > 0 && v !== 720) pc.footerBottom = round1(twipsToMM(v));
|
|
267
|
+
}
|
|
268
|
+
if (sect.child('titlePg')) {
|
|
269
|
+
// 「首页不同」但没给首页部件:编辑器的口径是「除首页外每页显示」
|
|
270
|
+
hfMode = HF_MODE.EXCEPT_FIRST;
|
|
271
|
+
}
|
|
272
|
+
const cols = sect.child('cols');
|
|
273
|
+
if (cols) {
|
|
274
|
+
const n = attrIntOf(cols, 'num');
|
|
275
|
+
if (n > 1) {
|
|
276
|
+
pc.columns = n;
|
|
277
|
+
const sp = attrIntOf(cols, 'space');
|
|
278
|
+
if (sp > 0) pc.colGap = round1(twipsToMM(sp));
|
|
279
|
+
pc.colSeparator = cols.attr('sep') === '1';
|
|
280
|
+
// 每列自定义宽度(w:col 子元素):渲染按等宽近似,定义原样往返
|
|
281
|
+
const defs = cols.children('col').map((c) => ({ w: attrIntOf(c, 'w'), space: attrIntOf(c, 'space') }));
|
|
282
|
+
if (defs.some((c) => c.w > 0 || c.space > 0)) pc.colWidths = defs;
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
return [pc, hfMode];
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** 一节的节属性读数(type 缺省 = nextPage;分栏数供跨栏判定) */
|
|
289
|
+
sectionConfOf(sect) {
|
|
290
|
+
const [page, hfMode] = this.pageConfOf(sect);
|
|
291
|
+
const type = sect.child('type');
|
|
292
|
+
return { type: type ? type.attr('val') : '', page, hfMode };
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** collectSections 全部节(文档序:内嵌 sectPr 逐节 + 末节收尾);跨栏连续节剔除并记入 emitSecAt
|
|
296
|
+
* [设计] 跨栏连续节(与相邻节仅分栏数不同的 continuous 节)沿用既有 spanAll 机制,
|
|
297
|
+
* 不作为多节边界输出——否则「跨栏标题」会被渲染/写回成一次多余的节切换 */
|
|
298
|
+
collectSections(body) {
|
|
299
|
+
const kids = flattenSdt(body.kids);
|
|
300
|
+
const at = [];
|
|
301
|
+
kids.forEach((n, i) => {
|
|
302
|
+
if (n.name !== 'p') return;
|
|
303
|
+
const sect = n.find('pPr', 'sectPr');
|
|
304
|
+
if (sect) at.push({ i, sect });
|
|
305
|
+
});
|
|
306
|
+
const lastSect = body.child('sectPr');
|
|
307
|
+
// [坑] 每节的页眉/页脚/页码/水印必须在此读进节配置(sectionHf 归还 conf):
|
|
308
|
+
// 否则打开一份带页眉页码的 .docx 时这些外观全读不回来,保存自检也会因模型与读回不一致而拒存
|
|
309
|
+
// [设计] 按文档序逐节读、把上一节传进去:Word 里没有 headerReference/footerReference 的节
|
|
310
|
+
// 继承上一节的页眉页脚,不继承会让「链接到前一节」的普通多节文档整段页眉页脚消失。
|
|
311
|
+
const all = [];
|
|
312
|
+
const readSection = (sect) => {
|
|
313
|
+
all.push(this.sectionHf(this.sectionConfOf(sect), sect, all[all.length - 1]));
|
|
314
|
+
};
|
|
315
|
+
for (const { sect } of at) readSection(sect);
|
|
316
|
+
if (lastSect) readSection(lastSect);
|
|
317
|
+
const emit = new Set();
|
|
318
|
+
const kept = [];
|
|
319
|
+
all.forEach((conf, idx) => {
|
|
320
|
+
if (isInlineSection(conf, all[idx + 1])) return;
|
|
321
|
+
kept.push(conf);
|
|
322
|
+
if (idx < at.length) emit.add(at[idx].i);
|
|
323
|
+
});
|
|
324
|
+
this.emitSecAt = emit;
|
|
325
|
+
return kept;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** markSpanSections 找出段落内嵌的 sectPr(分节符):多栏文档里属于单栏节的块就是跨栏块 */
|
|
329
|
+
markSpanSections(body) {
|
|
330
|
+
let pending = [];
|
|
331
|
+
// 与渲染侧同一份展开序列(内容控件视作透明容器),两边索引必须一致才能对上 spanAt/dropAt
|
|
332
|
+
flattenSdt(body.kids).forEach((n, i) => {
|
|
333
|
+
const name = n.name;
|
|
334
|
+
if (name !== 'p' && name !== 'tbl') return;
|
|
335
|
+
if (name === 'p') {
|
|
336
|
+
const sect = n.find('pPr', 'sectPr');
|
|
337
|
+
if (sect) {
|
|
338
|
+
if (attrIntOf(sect.child('cols'), 'num') <= 1) {
|
|
339
|
+
for (const j of pending) this.spanAt.add(j);
|
|
340
|
+
this.spanAt.add(i);
|
|
341
|
+
}
|
|
342
|
+
if (this.renderRunsHtml(n).trim() === '') this.dropAt.add(i); // 纯分节段落
|
|
343
|
+
pending = [];
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
pending.push(i);
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/* ---------- 页眉页脚 ---------- */
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* 把一节 sectPr 的页眉/页脚/页码/水印读进该节配置(部件按引用查,不扫目录)
|
|
355
|
+
* [设计] 走引用而不是扫 word/header*:奇偶各一份时,只有引用上的 type 能区分哪份是偶数页,
|
|
356
|
+
* 扫目录会把偶数页那份当成奇数页(部件按名排序 header1 在前,正好也是错的那一侧)。
|
|
357
|
+
*/
|
|
358
|
+
sectionHf(conf, sect, prev) {
|
|
359
|
+
/** 本节是否有该类页眉页脚引用(没有 = 继承上一节) */
|
|
360
|
+
const has = (tag, typ) => this.hfPartName(sect, tag, typ) !== '';
|
|
361
|
+
const inheritPrev = (key, fallback) => {
|
|
362
|
+
if (prev && prev[key] !== undefined) conf[key] = prev[key];
|
|
363
|
+
else if (fallback !== undefined) conf[key] = fallback;
|
|
364
|
+
};
|
|
365
|
+
|
|
366
|
+
if (has('headerReference', 'default')) {
|
|
367
|
+
conf.header = normalizeHf(this.hfHtml(sect, 'headerReference', 'default'));
|
|
368
|
+
conf.watermark = this.watermark(sect, 'headerReference', 'default');
|
|
369
|
+
} else {
|
|
370
|
+
inheritPrev('header', '');
|
|
371
|
+
// 水印是页眉里的图形,随页眉一起继承;本节有自己的页眉就不再继承上一节的水印
|
|
372
|
+
inheritPrev('watermark', null);
|
|
373
|
+
if (conf.watermark) conf.watermark = { ...conf.watermark };
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
if (has('footerReference', 'default')) {
|
|
377
|
+
conf.footer = normalizeHf(this.hfHtml(sect, 'footerReference', 'default'));
|
|
378
|
+
conf.pageNumbers = this.hfFooter(sect, 'footerReference', 'default');
|
|
379
|
+
} else {
|
|
380
|
+
inheritPrev('footer', '');
|
|
381
|
+
inheritPrev('pageNumbers', null);
|
|
382
|
+
if (conf.pageNumbers) conf.pageNumbers = { ...conf.pageNumbers };
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
const even = this.hasEvenOddHeaders();
|
|
386
|
+
const first = conf.hfMode === HF_MODE.EXCEPT_FIRST;
|
|
387
|
+
conf.hfMode = even && first ? HF_MODE.ODD_EVEN_FIRST
|
|
388
|
+
: even ? HF_MODE.ODD_EVEN
|
|
389
|
+
: first ? HF_MODE.EXCEPT_FIRST
|
|
390
|
+
: HF_MODE.ALL;
|
|
391
|
+
|
|
392
|
+
if (even) {
|
|
393
|
+
if (has('headerReference', 'even')) conf.headerEven = normalizeHf(this.hfHtml(sect, 'headerReference', 'even'));
|
|
394
|
+
else inheritPrev('headerEven', '');
|
|
395
|
+
if (has('footerReference', 'even')) conf.footerEven = normalizeHf(this.hfHtml(sect, 'footerReference', 'even'));
|
|
396
|
+
else inheritPrev('footerEven', '');
|
|
397
|
+
const evenNum = has('footerReference', 'even') ? this.hfFooter(sect, 'footerReference', 'even') : null;
|
|
398
|
+
if (!conf.pageNumbers && evenNum) conf.pageNumbers = evenNum;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
// 「首页不同」的页眉页脚独立成对:缺引用同样继承上一节;首页没有内容就是空白页眉页脚
|
|
402
|
+
// [坑] 首页部件不走 normalizeHf:默认/偶数页的「只有 PAGE 域」由 pageNumbers 承载,
|
|
403
|
+
// 但首页页码没有独立字段,剥掉域占位会让「首页只有页码」保存后凭空消失
|
|
404
|
+
if (first) {
|
|
405
|
+
if (has('headerReference', 'first')) conf.headerFirst = this.hfHtml(sect, 'headerReference', 'first');
|
|
406
|
+
else inheritPrev('headerFirst', '');
|
|
407
|
+
if (has('footerReference', 'first')) conf.footerFirst = this.hfHtml(sect, 'footerReference', 'first');
|
|
408
|
+
else inheritPrev('footerFirst', '');
|
|
409
|
+
const firstNum = has('footerReference', 'first') ? this.hfFooter(sect, 'footerReference', 'first') : null;
|
|
410
|
+
if (!conf.pageNumbers && firstNum) conf.pageNumbers = firstNum;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
// 编号格式与起始页码挂在节上(页脚里的 PAGE 域只说明「有页码」)。
|
|
414
|
+
// [坑] 只有 pgNumType、没有 PAGE 域时不能把页码打开,否则会凭设置凭空显示出一串页码。
|
|
415
|
+
const num = pgNumOf(sect);
|
|
416
|
+
if (num) {
|
|
417
|
+
if (!conf.pageNumbers) conf.pageNumbers = { enabled: false, ...num };
|
|
418
|
+
else Object.assign(conf.pageNumbers, num);
|
|
419
|
+
}
|
|
420
|
+
return conf;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/** 按引用类型与 r:id 找到部件路径(关系 target 是相对部件所在目录的路径) */
|
|
424
|
+
hfPartName(sect, tag, typ) {
|
|
425
|
+
for (const ref of sect.children(tag)) {
|
|
426
|
+
if (ref.attr('type') !== typ) continue;
|
|
427
|
+
const rel = this.docRel.get(ref.attrNS(REL_NS, 'id'));
|
|
428
|
+
if (!rel) continue;
|
|
429
|
+
const t = (rel.target || '').trim().replace(/^\.\//, '');
|
|
430
|
+
if (t.startsWith('/')) return t.slice(1);
|
|
431
|
+
return `word/${t}`;
|
|
432
|
+
}
|
|
433
|
+
return '';
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
/** 取指定引用的页眉/页脚受限 HTML(富文本:格式 + 域占位;见 hfHtmlOf) */
|
|
437
|
+
hfHtml(sect, tag, typ) {
|
|
438
|
+
const name = this.hfPartName(sect, tag, typ);
|
|
439
|
+
if (!name) return '';
|
|
440
|
+
const raw = this.pkg.part(name);
|
|
441
|
+
if (!raw) return '';
|
|
442
|
+
try {
|
|
443
|
+
// 页眉页脚里的超链接,r:id 指向页眉页脚部件自己的 .rels,不是 document.xml 的
|
|
444
|
+
return hfHtmlOf({ docRel: this.pkg.rels(name) }, parseNode(raw));
|
|
445
|
+
} catch {
|
|
446
|
+
return '';
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/**
|
|
451
|
+
* 从页眉部件的 VML 里取回水印
|
|
452
|
+
* [设计] 水印只认 v:textpath 的 string:Word 的水印就是页眉里那张旋转文字图,
|
|
453
|
+
* 没有别的地方记这个数据,不回读就等于保存一次把水印静默丢掉。
|
|
454
|
+
*/
|
|
455
|
+
watermark(sect, tag, typ) {
|
|
456
|
+
const name = this.hfPartName(sect, tag, typ);
|
|
457
|
+
if (!name) return null;
|
|
458
|
+
const raw = this.pkg.part(name);
|
|
459
|
+
if (!raw) return null;
|
|
460
|
+
let tree;
|
|
461
|
+
try {
|
|
462
|
+
tree = parseNode(raw);
|
|
463
|
+
} catch {
|
|
464
|
+
return null;
|
|
465
|
+
}
|
|
466
|
+
let text = null;
|
|
467
|
+
const find = (n) => {
|
|
468
|
+
if (text) return;
|
|
469
|
+
if (n.name === 'textpath' && n.attr('string') !== '') {
|
|
470
|
+
text = n;
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
473
|
+
for (const k of n.kids) find(k);
|
|
474
|
+
};
|
|
475
|
+
find(tree);
|
|
476
|
+
if (!text) return null;
|
|
477
|
+
const wm = { data: text.attr('string') };
|
|
478
|
+
const size = attrOfStyle(text.attr('style'), 'font-size');
|
|
479
|
+
if (size > 0) wm.size = size;
|
|
480
|
+
// 颜色在 shape 的 fillcolor 上,透明度在 v:fill 的 opacity 上(都在同一个 shape 里)
|
|
481
|
+
const findShape = (n) => {
|
|
482
|
+
if (n.attr('fillcolor') !== '') return n;
|
|
483
|
+
for (const k of n.kids) {
|
|
484
|
+
const hit = findShape(k);
|
|
485
|
+
if (hit) return hit;
|
|
486
|
+
}
|
|
487
|
+
return null;
|
|
488
|
+
};
|
|
489
|
+
const shape = findShape(tree);
|
|
490
|
+
if (shape) {
|
|
491
|
+
// 颜色按合法十六进制收敛:文件里的任意字符串不能直接进模型(写出端会把它拼进 XML 属性)
|
|
492
|
+
const fill = hexColor(shape.attr('fillcolor'), '');
|
|
493
|
+
if (fill) wm.color = `#${fill}`;
|
|
494
|
+
// [坑] 解析不出就别写 0:前端用「缺省值 + 覆盖」合并文档模型,写 0 会把默认透明度顶成全透明
|
|
495
|
+
const fillNode = shape.child('fill');
|
|
496
|
+
if (fillNode) {
|
|
497
|
+
const v = attrFloat(fillNode, 'opacity');
|
|
498
|
+
if (v > 0) wm.opacity = v;
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
return wm;
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/** 页脚的页码设置(PAGE 域即开关,段落对齐即页码位置);没有 PAGE 域返回 null */
|
|
505
|
+
hfFooter(sect, tag, typ) {
|
|
506
|
+
const name = this.hfPartName(sect, tag, typ);
|
|
507
|
+
if (!name) return null;
|
|
508
|
+
const raw = this.pkg.part(name);
|
|
509
|
+
if (!raw) return null;
|
|
510
|
+
let tree;
|
|
511
|
+
try {
|
|
512
|
+
tree = parseNode(raw);
|
|
513
|
+
} catch {
|
|
514
|
+
return null;
|
|
515
|
+
}
|
|
516
|
+
let hasPage = false;
|
|
517
|
+
const walk = (n) => {
|
|
518
|
+
for (const k of n.kids) {
|
|
519
|
+
// 按域码精确比对:'NUMPAGES'.includes('PAGE') 会误判(旧口径的坑)
|
|
520
|
+
if (k.name === 'instrText' && (k.text.trim().toUpperCase().split(/\s+/)[0] || '') === 'PAGE') hasPage = true;
|
|
521
|
+
// 简单域形式:<w:fldSimple w:instr=" PAGE ">
|
|
522
|
+
if (k.name === 'fldSimple' && (k.attr('instr').trim().toUpperCase().split(/\s+/)[0] || '') === 'PAGE') hasPage = true;
|
|
523
|
+
walk(k);
|
|
524
|
+
}
|
|
525
|
+
};
|
|
526
|
+
walk(tree);
|
|
527
|
+
return hasPage ? { enabled: true, align: hfAlign(tree) } : null;
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/** settings.xml 里声明了奇偶页不同(只挂 even 引用而没声明,Word 会忽略偶数页部件) */
|
|
531
|
+
hasEvenOddHeaders() {
|
|
532
|
+
const raw = this.pkg.part(PART_SETTINGS);
|
|
533
|
+
if (!raw) return false;
|
|
534
|
+
try {
|
|
535
|
+
return parseNode(raw).child('evenAndOddHeaders') !== null;
|
|
536
|
+
} catch {
|
|
537
|
+
return false;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/* ---------- 正文(实现见 render.js;方法名与 Go 逐条对应) ---------- */
|
|
542
|
+
|
|
543
|
+
blocksHtml(parent, top) {
|
|
544
|
+
return renderBlocks(this, parent, top);
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
renderRunsHtml(p) {
|
|
548
|
+
return renderRuns(this, p);
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
/**
|
|
554
|
+
* 把 .docx 字节解析成 Document(读方向总入口)
|
|
555
|
+
* @param {Uint8Array|ArrayBuffer} data
|
|
556
|
+
* @returns {Promise<import('./docx.js').Document>}
|
|
557
|
+
*/
|
|
558
|
+
export async function readDocument(data) {
|
|
559
|
+
const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
|
|
560
|
+
if (bytes.length > 8 && bytes[0] === 0xd0 && bytes[1] === 0xcf) {
|
|
561
|
+
throw new Error('旧版二进制 .doc 不支持,请先另存为 .docx');
|
|
562
|
+
}
|
|
563
|
+
let pkg;
|
|
564
|
+
try {
|
|
565
|
+
pkg = await openOpc(bytes);
|
|
566
|
+
} catch {
|
|
567
|
+
throw new Error('不是有效的 docx 文件');
|
|
568
|
+
}
|
|
569
|
+
const raw = pkg.part(PART_DOCUMENT);
|
|
570
|
+
if (!raw) throw new Error('docx 缺少 word/document.xml');
|
|
571
|
+
let tree;
|
|
572
|
+
try {
|
|
573
|
+
tree = parseNode(raw);
|
|
574
|
+
} catch (err) {
|
|
575
|
+
throw new Error(`无法解析 document.xml: ${err.message}`);
|
|
576
|
+
}
|
|
577
|
+
const body = tree.child('body');
|
|
578
|
+
if (!body) throw new Error('docx 缺少正文');
|
|
579
|
+
|
|
580
|
+
const rd = new DocxReader(pkg);
|
|
581
|
+
const doc = {};
|
|
582
|
+
// 全部节(按文档序,末节收尾):正文渲染与写回都以这个序列为基准
|
|
583
|
+
doc.sections = rd.collectSections(body);
|
|
584
|
+
const base = doc.sections[doc.sections.length - 1];
|
|
585
|
+
// 脚注/尾注的显示序号按各自序列的出现位置(readNotes 的返回顺序 = 文档顺序)
|
|
586
|
+
const footnotes = readNotes(pkg, PART_FOOTNOTES, 'footnote');
|
|
587
|
+
const endnotes = readNotes(pkg, PART_ENDNOTES, 'endnote');
|
|
588
|
+
footnotes.forEach((n, i) => rd.noteOrdFn.set(n.id, i + 1));
|
|
589
|
+
endnotes.forEach((n, i) => rd.noteOrdEn.set(n.id, i + 1));
|
|
590
|
+
// Word 把跨栏标题写成独立的单栏节,回读时映射成 col-span-all 块
|
|
591
|
+
if (base && base.page && base.page.columns > 1) rd.markSpanSections(body);
|
|
592
|
+
doc.html = rd.blocksHtml(body, true);
|
|
593
|
+
doc.comments = parseComments(pkg);
|
|
594
|
+
doc.footnotes = footnotes;
|
|
595
|
+
doc.endnotes = endnotes;
|
|
596
|
+
doc.props = readProps(pkg);
|
|
597
|
+
doc.defaultTabStop = rd.tabStop;
|
|
598
|
+
doc.compressPunctuation = rd.compressPunct;
|
|
599
|
+
doc.carry = collectCarry(pkg);
|
|
600
|
+
doc.losses = collectLosses(pkg, body);
|
|
601
|
+
return doc;
|
|
602
|
+
}
|
|
603
|
+
|