/
delta-to-word.html
596 lines (581 loc) · 19.7 KB
/
delta-to-word.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>delta-to-word</title>
<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet" />
<style>
body,
html {
background-color: #eee;
font-size: 14px;
}
.editor-container {
margin: 0 auto;
width: 700px;
background-color: #fff;
}
.editor-container > .ql-toolbar {
border: unset;
border-bottom: 1px solid #eee;
}
#editor {
background-color: #fff;
border: unset;
}
.export {
position: fixed;
top: 20px;
right: 20px;
padding: 10px;
color: #fff;
background-color: #165dff;
border-radius: 3px;
cursor: pointer;
user-select: none;
}
</style>
</head>
<body>
<div id="root">
<div class="editor-container">
<div id="editor"></div>
</div>
</div>
<div class="export" onClick="exportWord()">导出Word</div>
<script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
<script>
const dom = document.getElementById("editor");
const editor = new Quill(dom, {
modules: {
toolbar: [
[{ header: [1, 2, false] }],
["bold", "italic", "underline"],
["image", "code-block"],
],
},
placeholder: "Enter Text...",
theme: "snow",
});
window.editor = editor;
editor.setContents([
{ insert: "标题" },
{
insert: "\n",
attributes: { header: 1 },
},
{ insert: "首行" },
{
insert: "加粗",
attributes: { bold: true },
},
{ insert: "、" },
{
insert: "斜体",
attributes: { italic: true },
},
{ insert: "、" },
{
insert: "下划线",
attributes: { underline: true },
},
{ insert: "、" },
{
insert: "组合",
attributes: { underline: true, italic: true, bold: true },
},
{ insert: "\n" },
{ insert: "\n" },
]);
</script>
<script>
const Delta = Quill.import("delta");
const opt = Object.prototype.toString;
const isString = value => {
return opt.call(value) === "[object String]";
};
const CHARTS = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm0123456789";
const getUniqueId = (len = 10) => {
const chars = new Array(len - 1).fill("");
return (
CHARTS[Math.floor(Math.random() * 52)] +
chars.map(() => CHARTS[Math.floor(Math.random() * CHARTS.length)]).join("")
);
};
// 常量
const ROOT_ZONE = "ROOT";
const CODE_BLOCK_KEY = "code-block";
/** 转换为`DeltaSet` */
const transformToDeltaSet = () => {
const delta = editor.getContents();
// 构造`Delta`实例
// 将`Delta`转换为`Line`的数据表达
const group = [];
delta.eachLine((line, attributes) => {
group.push({ attrs: attributes || {}, ops: line.ops });
});
// 用于对齐`Word`的数据表达
// 同时为了方便处理嵌套关系 将数据结构拍平
class DeltaSet {
deltas = {};
get(zoneId) {
return this.deltas[zoneId] || null;
}
push(id, line) {
if (!this.deltas[id]) this.deltas[id] = [];
this.deltas[id].push(line);
}
}
const deltaSet = new DeltaSet();
// 标记当前正在处理的的`ZoneId`
// 实际情况下可能会存在多层嵌套 此时需要用`stack`来处理
let currentZone = ROOT_ZONE;
// 标记当前处理的类型 如果存在多种类型时会用得到
let currentMode = "NORMAL";
// 用于判断当前`Line`是否为`CodeBlock`
const isCodeBlockLine = line => line && !!line.attrs[CODE_BLOCK_KEY];
// 遍历`Line`的数据表达 构造`DeltaSet`
for (let i = 0; i < group.length; ++i) {
const prev = group[i - 1];
const current = group[i];
const next = group[i + 1];
// 代码块结构的起始
if (!isCodeBlockLine(prev) && isCodeBlockLine(current)) {
const newZoneId = getUniqueId();
// 存在嵌套关系 构造新的索引
const codeBlockLine = {
attrs: {},
ops: [{ insert: " ", attributes: { [CODE_BLOCK_KEY]: "true", zoneId: newZoneId } }],
};
// 需要在当前`Zone`加入指向新`Zone`的索引`Line`
deltaSet.push(currentZone, codeBlockLine);
currentZone = newZoneId;
currentMode = "CODEBLOCK";
}
// 将`Line`置入当前要处理的`Zone`
deltaSet.push(currentZone, group[i]);
// 代码块结构的结束
if (currentMode === "CODEBLOCK" && isCodeBlockLine(current) && !isCodeBlockLine(next)) {
currentZone = ROOT_ZONE;
currentMode = "NORMAL";
}
}
// `DeltaSet`实例
console.log(deltaSet);
return deltaSet;
};
/** 导出`Word` */
const exportWord = () => {
if (!window.docx || !window.saveAs) {
alert("需要等待模块加载完成");
return;
}
const {
BorderStyle,
Document,
Table,
Footer,
Header,
ImageRun,
LineRuleType,
NumberFormat,
Packer,
PageNumber,
Paragraph,
sectionPageSizeDefaults,
SimpleField,
StyleLevel,
Tab,
TableCell,
TableLayoutType,
TableOfContents,
TableRow,
TabStopPosition,
TabStopType,
TextRun,
WidthType,
} = window.docx;
const deltaSet = transformToDeltaSet();
/** 基准全局配置 */
const PAGE_SIZE = {
WIDTH: sectionPageSizeDefaults.WIDTH - 1440 * 2,
HEIGHT: sectionPageSizeDefaults.HEIGHT - 1440 * 2,
};
const DEFAULT_FORMAT_TYPE = {
H1: "H1",
H2: "H2",
CONTENT: "Content",
IMAGE: "Image",
HF: "HF",
};
const DEFAULT_LINE_SPACING_FORMAT = {
before: 10 * 20, // 6 PT
after: 10 * 20, // 6 PT
lineRule: LineRuleType.EXACT,
};
const BORDER_NODE = { style: BorderStyle.NONE, size: 1, color: "#000000" };
const NO_BORDER = {
top: BORDER_NODE,
bottom: BORDER_NODE,
left: BORDER_NODE,
right: BORDER_NODE,
};
const DEFAULT_FONT_FORMAT = { ascii: "Times New Roman", eastAsia: "宋体" };
const DEFAULT_TEXT_FORMAT = {
size: 24 /** 12 PT */,
color: "#000000",
font: DEFAULT_FONT_FORMAT,
};
const PRESET_SCHEME_LIST = [
{
id: DEFAULT_FORMAT_TYPE.CONTENT,
name: DEFAULT_FORMAT_TYPE.CONTENT,
quickFormat: true,
paragraph: {
spacing: DEFAULT_LINE_SPACING_FORMAT,
},
},
{
id: DEFAULT_FORMAT_TYPE.H1,
name: DEFAULT_FORMAT_TYPE.H1,
basedOn: "Heading1",
next: DEFAULT_FORMAT_TYPE.CONTENT,
quickFormat: true,
paragraph: {
spacing: DEFAULT_LINE_SPACING_FORMAT,
},
run: {
...DEFAULT_TEXT_FORMAT,
size: 36,
bold: true,
italics: false,
font: { ...DEFAULT_FONT_FORMAT, eastAsia: "黑体" },
},
},
{
id: DEFAULT_FORMAT_TYPE.H2,
name: DEFAULT_FORMAT_TYPE.H2,
basedOn: "Heading2",
next: DEFAULT_FORMAT_TYPE.CONTENT,
quickFormat: true,
paragraph: {
spacing: DEFAULT_LINE_SPACING_FORMAT,
},
run: {
...DEFAULT_TEXT_FORMAT,
size: 32,
bold: true,
italics: false,
font: { ...DEFAULT_FONT_FORMAT, eastAsia: "黑体" },
},
},
{
id: DEFAULT_FORMAT_TYPE.IMAGE,
name: DEFAULT_FORMAT_TYPE.IMAGE,
quickFormat: true,
next: DEFAULT_FORMAT_TYPE.CONTENT,
paragraph: {
spacing: {
...DEFAULT_LINE_SPACING_FORMAT,
line: undefined,
},
},
},
{
id: DEFAULT_FORMAT_TYPE.HF,
name: DEFAULT_FORMAT_TYPE.HF,
quickFormat: true,
run: { size: 18, color: "#1d2129" },
},
];
/** 单位转换 */
const daxToCM = dax => (dax / 20 / 72) * 2.54;
const cmToPixel = cm => cm * 10 * 3.7795275591;
const daxToPixel = dax => Math.ceil(cmToPixel(daxToCM(dax)));
/** `Word`转换调度 */
const LEAF_PLUGINS = [];
const LINE_PLUGINS = [];
const parseZoneContent = async (zoneId, options) => {
const { defaultZoneTag = { width: PAGE_SIZE.WIDTH } } = options;
const lines = deltaSet.get(zoneId);
if (!lines) return null;
const target = [];
for (let i = 0; i < lines.length; ++i) {
const prevLine = lines[i - 1] || null;
const currentLine = lines[i];
const nextLine = lines[i + 1] || null;
// 不能影响外部传递的`Tag`
const tag = { ...defaultZoneTag };
// 处理节点内容
const ops = currentLine.ops;
const leaves = [];
for (let k = 0; k < ops.length; ++k) {
const prevOp = ops[k - 1] || null;
const currentOp = ops[k];
const nextOp = ops[k + 1] || null;
const hit = LEAF_PLUGINS.find(leafPlugin => leafPlugin.match(currentOp));
if (hit) {
const result = await hit.processor({
prev: prevOp,
current: currentOp,
next: nextOp,
tag: tag,
});
result && leaves.push(result);
}
}
// 处理行内容
const hit = LINE_PLUGINS.find(linePlugin => linePlugin.match(currentLine));
if (hit) {
const result = await hit.processor({
prev: prevLine,
current: currentLine,
next: nextLine,
tag: tag,
leaves: leaves,
});
result && target.push(result);
}
}
return target;
};
/** 注册插件 */
const makeZoneBlock = async (config = {}) => {
const { table, row, cell, children } = config;
const tableCell = new TableCell({
width: { size: "100%", type: WidthType.PERCENTAGE },
borders: NO_BORDER,
...cell,
children: children || [],
});
const tableRow = new TableRow({
...row,
children: [tableCell],
});
return new Table({
width: { size: "100%", type: WidthType.PERCENTAGE },
layout: TableLayoutType.FIXED,
style: DEFAULT_FORMAT_TYPE.CONTENT,
...table,
rows: [tableRow],
});
};
const ImagePlugin = {
key: "IMAGE",
match: op => !!(op.insert && op.insert.image),
processor: async options => {
const { current, tag } = options;
const src = current.insert && current.insert.image;
if (!src) return null;
tag.paragraphFormat = DEFAULT_FORMAT_TYPE.IMAGE;
const base64 = src.split(",")[1];
return new Promise(resolve => {
const img = new Image();
img.onload = () => {
const width = img.naturalWidth || 100;
const height = img.naturalHeight || 100;
const scale = height / width;
const targetWidth = Math.min(daxToPixel(tag.width), width);
const targetHeight = targetWidth * scale;
const config = {
data: src,
transformation: { width: targetWidth, height: targetHeight },
};
resolve(new ImageRun(config));
};
img.onerror = () => resolve(null);
img.src = src;
});
},
};
LEAF_PLUGINS.push(ImagePlugin);
const CodeBlockPlugin = {
key: "CODEBLOCK",
match: op => !!(op.attributes && op.attributes[CODE_BLOCK_KEY]),
processor: async options => {
const { current, tag } = options;
const zoneId = current.attributes?.zoneId;
const zone = zoneId && deltaSet.get(zoneId);
if (!zone) return null;
const MARGIN = 10 * 20;
const content = await parseZoneContent(zoneId, {
defaultZoneTag: {
...tag,
isInZone: true,
isInCodeBlock: true,
fontSize: 20,
width: options.tag.width - MARGIN * 2,
spacing: { ...DEFAULT_LINE_SPACING_FORMAT, after: 6 * 20, before: 6 * 20 },
},
});
const border = { size: 1, style: BorderStyle.SINGLE, color: "#e5e6eb" };
const background = { fill: "#f2f3f5" };
const block = makeZoneBlock({
table: { width: { size: tag.width, type: WidthType.DXA } },
cell: {
margins: {
top: MARGIN / 2,
bottom: MARGIN / 2,
left: MARGIN,
right: MARGIN,
marginUnitType: WidthType.DXA,
},
borders: { top: border, bottom: border, left: border, right: border },
shading: background,
},
children: content || [],
});
return block;
},
};
LEAF_PLUGINS.push(CodeBlockPlugin);
const TextPlugin = {
key: "TEXT",
match: () => true,
processor: async options => {
const { current, tag } = options;
if (!isString(current.insert)) return null;
const config = {};
config.text = current.insert;
const attrs = current.attributes || {};
if (attrs.bold) config.bold = true;
if (attrs.italic) config.italics = true;
if (attrs.underline) config.underline = {};
if (tag.fontSize) config.size = tag.fontSize;
if (tag.fontColor) config.color = tag.fontColor;
return new TextRun(config);
},
};
LEAF_PLUGINS.push(TextPlugin);
const HeadingPlugin = {
key: "HEADING",
match: line => !!(line.attrs && line.attrs.header),
processor: async options => {
const { current, leaves } = options;
const attrs = current.attrs;
const level = Number(attrs.header);
const config = {};
switch (level) {
case 1:
config.style = DEFAULT_FORMAT_TYPE.H1;
break;
case 2:
config.style = DEFAULT_FORMAT_TYPE.H2;
break;
}
config.children = leaves;
return new Paragraph(config);
},
};
LINE_PLUGINS.push(HeadingPlugin);
const ParagraphPlugin = {
key: "PARAGRAPH",
match: () => true,
processor: async options => {
const { leaves, tag } = options;
const config = {};
const isBlockNode = leaves.some(leaf => leaf instanceof Table);
config.style = tag.paragraphFormat || DEFAULT_FORMAT_TYPE.CONTENT;
if (!isBlockNode) {
if (tag.spacing) config.spacing = tag.spacing;
config.children = leaves;
return new Paragraph(config);
} else {
if (leaves.length === 1 && leaves[0] instanceof Table) {
// 单个`Zone`不需要包裹 通常是独立的块元素
return leaves[0];
} else {
// 需要包裹组合嵌套`BlockTable`
return makeZoneBlock({ children: leaves });
}
}
},
};
LINE_PLUGINS.push(ParagraphPlugin);
/** 组装`Office Open XML` */
const HeaderSection = new Header({
children: [
new Paragraph({
style: DEFAULT_FORMAT_TYPE.HF,
tabStops: [{ type: TabStopType.RIGHT, position: TabStopPosition.MAX }],
spacing: { before: 8 * 0.5 * 20 },
border: { bottom: { size: 6, style: BorderStyle.SINGLE, color: "#1d2129" } },
children: [
new TextRun("页眉"),
new TextRun({
children: [
new Tab(),
new SimpleField(`STYLEREF "${DEFAULT_FORMAT_TYPE.H1}" \\* MERGEFORMAT`),
],
}),
],
}),
],
});
const FooterSection = new Footer({
children: [
new Paragraph({
style: DEFAULT_FORMAT_TYPE.HF,
tabStops: [{ type: TabStopType.RIGHT, position: TabStopPosition.MAX }],
spacing: { after: 10 * 0.5 * 20 },
border: { top: { size: 6, style: BorderStyle.SINGLE, color: "#1d2129" } },
children: [
new TextRun("页脚"),
new TextRun({
children: [new Tab(), PageNumber.CURRENT],
}),
],
}),
],
});
const main = async () => {
const doc = new Document({
sections: [
{
properties: {
page: {
pageNumbers: { start: 1, formatType: NumberFormat.UPPER_ROMAN },
},
},
children: [
new Paragraph({ text: "目录", style: DEFAULT_FORMAT_TYPE.H1 }),
new TableOfContents("Table Of Contents", {
hyperlink: true,
headingStyleRange: "1-2",
stylesWithLevels: [
new StyleLevel(DEFAULT_FORMAT_TYPE.H1, 1),
new StyleLevel(DEFAULT_FORMAT_TYPE.H2, 2),
],
}),
],
},
{
properties: {
page: {
pageNumbers: { start: 1, formatType: NumberFormat.DECIMAL },
},
},
headers: { default: HeaderSection },
footers: { default: FooterSection },
children: (await parseZoneContent(ROOT_ZONE, {})) || [],
},
],
styles: {
paragraphStyles: PRESET_SCHEME_LIST,
default: { document: { run: DEFAULT_TEXT_FORMAT } },
},
});
// 生成`.docx`文件
docx.Packer.toBlob(doc).then(blob => {
console.log(blob);
saveAs(blob, "word.docx");
});
};
main();
};
</script>
<script defer async src="https://unpkg.com/docx@7.1.0/build/index.js"></script>
<script defer async src="https://unpkg.com/file-saver@1.3.8/FileSaver.min.js"></script>
</body>
</html>