markdown-to-word 0.1.0 → 0.3.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 +43 -20
- package/build/converter.d.ts +6 -3
- package/build/converter.js +35 -10
- package/build/converter.js.map +1 -1
- package/build/docx-code-blocks.d.ts +3 -0
- package/build/docx-code-blocks.js +17 -3
- package/build/docx-code-blocks.js.map +1 -1
- package/build/docx-font-preset.d.ts +33 -3
- package/build/docx-font-preset.js +173 -16
- package/build/docx-font-preset.js.map +1 -1
- package/build/docx-html.d.ts +10 -0
- package/build/docx-html.js +106 -1
- package/build/docx-html.js.map +1 -1
- package/build/docx-images.d.ts +24 -0
- package/build/docx-images.js +176 -0
- package/build/docx-images.js.map +1 -0
- package/build/docx-structure.d.ts +3 -0
- package/build/docx-structure.js +10 -1
- package/build/docx-structure.js.map +1 -1
- package/build/font-presets.d.ts +48 -7
- package/build/font-presets.js +46 -10
- package/build/font-presets.js.map +1 -1
- package/build/main.d.ts +1 -1
- package/build/main.js.map +1 -1
- package/build/markdown-parser.js +27 -3
- package/build/markdown-parser.js.map +1 -1
- package/build/xml-part.d.ts +5 -0
- package/build/xml-part.js +61 -0
- package/build/xml-part.js.map +1 -1
- package/package.json +10 -2
|
@@ -1,21 +1,28 @@
|
|
|
1
1
|
import JSZip from 'jszip';
|
|
2
|
-
import { keepXmlDeclaration, WORDPROCESSING_NS as W_NS } from './xml-part.js';
|
|
2
|
+
import { keepXmlDeclaration, paragraphProperty, WORDPROCESSING_NS as W_NS, } from './xml-part.js';
|
|
3
3
|
/** Theme slots WinWord prefers over explicitly named fonts. */
|
|
4
|
-
const THEME_FONT_ATTRIBUTES = [
|
|
4
|
+
const THEME_FONT_ATTRIBUTES = [
|
|
5
|
+
'asciiTheme',
|
|
6
|
+
'eastAsiaTheme',
|
|
7
|
+
'hAnsiTheme',
|
|
8
|
+
'cstheme',
|
|
9
|
+
];
|
|
5
10
|
/**
|
|
6
11
|
* `<w:line>` is ignored while the rule is auto, but WinWord still writes 240
|
|
7
12
|
* twips, so the preset writes the pair Word itself produces.
|
|
8
13
|
*/
|
|
9
|
-
const
|
|
10
|
-
single: { line: '240', rule: 'auto' },
|
|
11
|
-
};
|
|
14
|
+
const SINGLE_SPACING = { line: '240', rule: 'auto' };
|
|
12
15
|
/**
|
|
13
|
-
* Rewrites the fonts, sizes
|
|
16
|
+
* Rewrites the fonts, sizes, paragraph spacing and page grid of an already
|
|
17
|
+
* generated .docx.
|
|
14
18
|
*
|
|
15
19
|
* `html-to-docx` only ever writes `w:ascii`, which WinWord applies to Latin
|
|
16
20
|
* characters and digits; Chinese characters fall back to the theme font. The
|
|
17
21
|
* East Asian slots are set here instead, so this stays out of the way of the
|
|
18
22
|
* default conversion output.
|
|
23
|
+
*
|
|
24
|
+
* The grid is measured from the page the document actually has, so it still
|
|
25
|
+
* fits when `pageMargins` overrode the preset's margins.
|
|
19
26
|
*/
|
|
20
27
|
export async function applyFontPreset(wordDocument, preset) {
|
|
21
28
|
const zip = await JSZip.loadAsync(await wordDocument.arrayBuffer());
|
|
@@ -23,29 +30,169 @@ export async function applyFontPreset(wordDocument, preset) {
|
|
|
23
30
|
if (!stylesEntry) {
|
|
24
31
|
throw new Error('Cannot apply font preset: document contains no word/styles.xml');
|
|
25
32
|
}
|
|
33
|
+
let grid = null;
|
|
34
|
+
const pageGrid = preset.page?.grid;
|
|
35
|
+
if (pageGrid ||
|
|
36
|
+
preset.paragraph.lineSpacing === 'grid' ||
|
|
37
|
+
preset.paragraph.firstLineIndentChars) {
|
|
38
|
+
const documentEntry = zip.file('word/document.xml');
|
|
39
|
+
if (!documentEntry) {
|
|
40
|
+
throw new Error('Cannot apply font preset: document contains no word/document.xml');
|
|
41
|
+
}
|
|
42
|
+
const documentXml = await documentEntry.async('string');
|
|
43
|
+
const patched = patchDocumentXml(documentXml, preset);
|
|
44
|
+
grid = patched.grid;
|
|
45
|
+
zip.file('word/document.xml', patched.xml);
|
|
46
|
+
}
|
|
26
47
|
const stylesXml = await stylesEntry.async('string');
|
|
27
|
-
zip.file('word/styles.xml', patchStylesXml(stylesXml, preset));
|
|
48
|
+
zip.file('word/styles.xml', patchStylesXml(stylesXml, preset, grid));
|
|
28
49
|
const patched = await zip.generateAsync({ type: 'arraybuffer' });
|
|
29
50
|
return new Blob([patched], { type: wordDocument.type });
|
|
30
51
|
}
|
|
31
52
|
/**
|
|
32
53
|
* Applies `preset` to the document default run properties and to the six
|
|
33
|
-
* heading styles of a styles.xml part.
|
|
54
|
+
* heading styles of a styles.xml part. `grid` is the page grid that
|
|
55
|
+
* `patchDocumentXml` set, which `lineSpacing: 'grid'` takes its pitch from.
|
|
34
56
|
*/
|
|
35
|
-
export function patchStylesXml(stylesXml, preset) {
|
|
57
|
+
export function patchStylesXml(stylesXml, preset, grid = null) {
|
|
36
58
|
const dom = new DOMParser().parseFromString(stylesXml, 'application/xml');
|
|
59
|
+
const layout = resolveLayout(preset, grid);
|
|
37
60
|
const docDefaults = requireElement(dom, 'docDefaults');
|
|
38
|
-
applyLevelStyle(docDefaults, preset.body, preset.paragraph);
|
|
61
|
+
applyLevelStyle(docDefaults, preset.body, preset.paragraph, layout);
|
|
62
|
+
if (layout.spacing.rule === 'exact') {
|
|
63
|
+
// Widow control pulls a line onto the next page whenever a paragraph would
|
|
64
|
+
// leave a single line behind, so pages would often hold one line fewer
|
|
65
|
+
// than the grid. Word turns it on unless the document says otherwise.
|
|
66
|
+
paragraphProperty(paragraphPropertiesOf(docDefaults), 'widowControl').setAttributeNS(W_NS, 'w:val', '0');
|
|
67
|
+
}
|
|
39
68
|
const styles = Array.from(dom.getElementsByTagNameNS(W_NS, 'style'));
|
|
40
69
|
for (const style of styles) {
|
|
41
70
|
const heading = /^Heading([1-6])$/.exec(style.getAttributeNS(W_NS, 'styleId') ?? '');
|
|
42
71
|
if (heading) {
|
|
43
|
-
applyLevelStyle(style, preset.headings[Number(heading[1]) - 1], preset.paragraph);
|
|
72
|
+
applyLevelStyle(style, preset.headings[Number(heading[1]) - 1], preset.paragraph, layout);
|
|
44
73
|
}
|
|
45
74
|
}
|
|
46
75
|
return keepXmlDeclaration(stylesXml, new XMLSerializer().serializeToString(dom));
|
|
47
76
|
}
|
|
48
|
-
function
|
|
77
|
+
function resolveLayout(preset, grid) {
|
|
78
|
+
const { lineSpacing, firstLineIndentChars = 0 } = preset.paragraph;
|
|
79
|
+
if (lineSpacing === 'grid' && !grid) {
|
|
80
|
+
throw new Error("Cannot apply font preset: lineSpacing 'grid' needs page.grid");
|
|
81
|
+
}
|
|
82
|
+
return {
|
|
83
|
+
spacing: lineSpacing === 'grid' && grid
|
|
84
|
+
? { line: String(grid.linePitch), rule: 'exact' }
|
|
85
|
+
: SINGLE_SPACING,
|
|
86
|
+
firstLineIndent: Math.round(firstLineIndentChars * preset.body.sizePt * 20),
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Sets the page grid in the section properties of a document.xml part, and
|
|
91
|
+
* fixes up the paragraphs that the style-level layout would break:
|
|
92
|
+
*
|
|
93
|
+
* - The generator gives every paragraph `<w:spacing w:lineRule="auto"/>`.
|
|
94
|
+
* Spacing attributes inherit one at a time, so that lone `auto` combined
|
|
95
|
+
* with the style's exact line height would read as a multiple of 240 twips
|
|
96
|
+
* (about 2.4 lines). It is dropped when the preset uses grid spacing.
|
|
97
|
+
* - Exact line spacing would crop an inline image to one line, so paragraphs
|
|
98
|
+
* with a drawing keep single spacing; the grid then rounds them up to whole
|
|
99
|
+
* lines.
|
|
100
|
+
* - Table cells drop the first-line indent; it only crowds narrow columns.
|
|
101
|
+
*/
|
|
102
|
+
export function patchDocumentXml(documentXml, preset) {
|
|
103
|
+
const dom = new DOMParser().parseFromString(documentXml, 'application/xml');
|
|
104
|
+
let grid = null;
|
|
105
|
+
const pageGrid = preset.page?.grid;
|
|
106
|
+
if (pageGrid) {
|
|
107
|
+
for (const sectPr of Array.from(dom.getElementsByTagNameNS(W_NS, 'sectPr'))) {
|
|
108
|
+
grid = measureGrid(sectPr, pageGrid, preset.body.sizePt);
|
|
109
|
+
setDocGrid(sectPr, grid);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
const gridSpacing = preset.paragraph.lineSpacing === 'grid';
|
|
113
|
+
for (const paragraph of Array.from(dom.getElementsByTagNameNS(W_NS, 'p'))) {
|
|
114
|
+
const pPr = children(paragraph).find((child) => child.localName === 'pPr');
|
|
115
|
+
if (gridSpacing) {
|
|
116
|
+
if (paragraph.getElementsByTagNameNS(W_NS, 'drawing').length > 0) {
|
|
117
|
+
const spacing = paragraphProperty(pPrOf(paragraph), 'spacing');
|
|
118
|
+
spacing.setAttributeNS(W_NS, 'w:line', SINGLE_SPACING.line);
|
|
119
|
+
spacing.setAttributeNS(W_NS, 'w:lineRule', SINGLE_SPACING.rule);
|
|
120
|
+
}
|
|
121
|
+
else {
|
|
122
|
+
const spacing = pPr && children(pPr).find((child) => child.localName === 'spacing');
|
|
123
|
+
if (spacing && !spacing.hasAttributeNS(W_NS, 'line')) {
|
|
124
|
+
spacing.removeAttributeNS(W_NS, 'lineRule');
|
|
125
|
+
if (spacing.attributes.length === 0) {
|
|
126
|
+
spacing.remove();
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
if (preset.paragraph.firstLineIndentChars && isInTableCell(paragraph)) {
|
|
132
|
+
removeFirstLineIndent(pPrOf(paragraph));
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return {
|
|
136
|
+
xml: keepXmlDeclaration(documentXml, new XMLSerializer().serializeToString(dom)),
|
|
137
|
+
grid,
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* The grid for the text block of `sectPr`'s page. Word stores the character
|
|
142
|
+
* pitch as an offset from the body font size. Both pitches are rounded down,
|
|
143
|
+
* as Word does, so the lines and characters always fit: for the page Word
|
|
144
|
+
* itself sets up with GB/T 9704 margins, this reproduces its linePitch="579"
|
|
145
|
+
* and charSpace="-834".
|
|
146
|
+
*/
|
|
147
|
+
function measureGrid(sectPr, { linesPerPage, charsPerLine, }, bodySizePt) {
|
|
148
|
+
const pgSz = children(sectPr).find((child) => child.localName === 'pgSz');
|
|
149
|
+
const pgMar = children(sectPr).find((child) => child.localName === 'pgMar');
|
|
150
|
+
const twips = (element, attribute) => {
|
|
151
|
+
const value = Number(element?.getAttributeNS(W_NS, attribute));
|
|
152
|
+
if (!Number.isFinite(value) || value <= 0) {
|
|
153
|
+
throw new Error(`Cannot apply font preset: section has no page ${attribute}`);
|
|
154
|
+
}
|
|
155
|
+
return value;
|
|
156
|
+
};
|
|
157
|
+
const textHeight = twips(pgSz, 'h') - twips(pgMar, 'top') - twips(pgMar, 'bottom');
|
|
158
|
+
const textWidth = twips(pgSz, 'w') - twips(pgMar, 'left') - twips(pgMar, 'right');
|
|
159
|
+
const charPitchPt = textWidth / 20 / charsPerLine;
|
|
160
|
+
return {
|
|
161
|
+
linePitch: Math.floor(textHeight / linesPerPage),
|
|
162
|
+
charSpace: Math.floor((charPitchPt - bodySizePt) * 4096),
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
function setDocGrid(sectPr, grid) {
|
|
166
|
+
let docGrid = children(sectPr).find((child) => child.localName === 'docGrid');
|
|
167
|
+
if (!docGrid) {
|
|
168
|
+
docGrid = sectPr.ownerDocument.createElementNS(W_NS, 'w:docGrid');
|
|
169
|
+
// <w:docGrid> is the last section property but <w:printerSettings>.
|
|
170
|
+
const printerSettings = children(sectPr).find((child) => child.localName === 'printerSettings');
|
|
171
|
+
sectPr.insertBefore(docGrid, printerSettings ?? null);
|
|
172
|
+
}
|
|
173
|
+
docGrid.setAttributeNS(W_NS, 'w:type', 'linesAndChars');
|
|
174
|
+
docGrid.setAttributeNS(W_NS, 'w:linePitch', String(grid.linePitch));
|
|
175
|
+
docGrid.setAttributeNS(W_NS, 'w:charSpace', String(grid.charSpace));
|
|
176
|
+
}
|
|
177
|
+
function isInTableCell(paragraph) {
|
|
178
|
+
for (let node = paragraph.parentElement; node; node = node.parentElement) {
|
|
179
|
+
if (node.namespaceURI === W_NS && node.localName === 'tc') {
|
|
180
|
+
return true;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
return false;
|
|
184
|
+
}
|
|
185
|
+
function removeFirstLineIndent(pPr) {
|
|
186
|
+
const ind = paragraphProperty(pPr, 'ind');
|
|
187
|
+
if (!ind.hasAttributeNS(W_NS, 'hanging')) {
|
|
188
|
+
ind.setAttributeNS(W_NS, 'w:firstLine', '0');
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
/** A paragraph's `<w:pPr>`, created as its first child if missing. */
|
|
192
|
+
function pPrOf(paragraph) {
|
|
193
|
+
return childOrCreate(paragraph, 'pPr', 'first');
|
|
194
|
+
}
|
|
195
|
+
function applyLevelStyle(scope, style, paragraph, layout) {
|
|
49
196
|
const rPr = runPropertiesOf(scope);
|
|
50
197
|
const rFonts = childOrCreate(rPr, 'rFonts', 'first');
|
|
51
198
|
for (const attribute of THEME_FONT_ATTRIBUTES) {
|
|
@@ -66,12 +213,22 @@ function applyLevelStyle(scope, style, paragraph) {
|
|
|
66
213
|
const size = String(style.sizePt * 2);
|
|
67
214
|
childOrCreate(rPr, 'sz', 'last').setAttributeNS(W_NS, 'w:val', size);
|
|
68
215
|
childOrCreate(rPr, 'szCs', 'last').setAttributeNS(W_NS, 'w:val', size);
|
|
69
|
-
const
|
|
216
|
+
const pPr = paragraphPropertiesOf(scope);
|
|
217
|
+
const spacing = paragraphProperty(pPr, 'spacing');
|
|
70
218
|
spacing.setAttributeNS(W_NS, 'w:before', String(paragraph.beforePt * 20));
|
|
71
219
|
spacing.setAttributeNS(W_NS, 'w:after', String(paragraph.afterPt * 20));
|
|
72
|
-
|
|
73
|
-
spacing.setAttributeNS(W_NS, 'w:
|
|
74
|
-
|
|
220
|
+
spacing.setAttributeNS(W_NS, 'w:line', layout.spacing.line);
|
|
221
|
+
spacing.setAttributeNS(W_NS, 'w:lineRule', layout.spacing.rule);
|
|
222
|
+
if (style.centered) {
|
|
223
|
+
// An indented first line would push a centered title off center.
|
|
224
|
+
if (layout.firstLineIndent) {
|
|
225
|
+
paragraphProperty(pPr, 'ind').setAttributeNS(W_NS, 'w:firstLine', '0');
|
|
226
|
+
}
|
|
227
|
+
paragraphProperty(pPr, 'jc').setAttributeNS(W_NS, 'w:val', 'center');
|
|
228
|
+
}
|
|
229
|
+
else if (layout.firstLineIndent) {
|
|
230
|
+
paragraphProperty(pPr, 'ind').setAttributeNS(W_NS, 'w:firstLine', String(layout.firstLineIndent));
|
|
231
|
+
}
|
|
75
232
|
}
|
|
76
233
|
function runPropertiesOf(parent) {
|
|
77
234
|
const container = parent.localName === 'docDefaults'
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"docx-font-preset.js","sourceRoot":"","sources":["../src/docx-font-preset.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAE1B,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,IAAI,IAAI,EAAE,MAAM,eAAe,CAAC;AAE9E,+DAA+D;AAC/D,MAAM,qBAAqB,GAAG,CAAC,YAAY,EAAE,eAAe,EAAE,YAAY,EAAE,SAAS,CAAC,CAAC;AAEvF;;;GAGG;AACH,MAAM,YAAY,GAAwD;IACxE,MAAM,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE;CACtC,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,YAAkB,EAAE,MAAkB;IAC1E,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC,SAAS,CAAC,MAAM,YAAY,CAAC,WAAW,EAAE,CAAC,CAAC;IACpE,MAAM,WAAW,GAAG,GAAG,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC;IAChD,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,MAAM,IAAI,KA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G,GAAG,CAAC,sBAAsB,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/D,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CAAC,kDAAkD,SAAS,WAAW,CAAC,CAAC;IAC1F,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import JSZip from 'jszip';\nimport type { FontPreset, LevelStyle, LineSpacing, ParagraphStyle } from './font-presets.js';\nimport { keepXmlDeclaration, WORDPROCESSING_NS as W_NS } from './xml-part.js';\n\n/** Theme slots WinWord prefers over explicitly named fonts. */\nconst THEME_FONT_ATTRIBUTES = ['asciiTheme', 'eastAsiaTheme', 'hAnsiTheme', 'cstheme'];\n\n/**\n * `<w:line>` is ignored while the rule is auto, but WinWord still writes 240\n * twips, so the preset writes the pair Word itself produces.\n */\nconst LINE_SPACING: Record<LineSpacing, { line: string; rule: string }> = {\n single: { line: '240', rule: 'auto' },\n};\n\n/**\n * Rewrites the fonts, sizes and paragraph spacing of an already generated .docx.\n *\n * `html-to-docx` only ever writes `w:ascii`, which WinWord applies to Latin\n * characters and digits; Chinese characters fall back to the theme font. The\n * East Asian slots are set here instead, so this stays out of the way of the\n * default conversion output.\n */\nexport async function applyFontPreset(wordDocument: Blob, preset: FontPreset): Promise<Blob> {\n const zip = await JSZip.loadAsync(await wordDocument.arrayBuffer());\n const stylesEntry = zip.file('word/styles.xml');\n if (!stylesEntry) {\n throw new Error('Cannot apply font preset: document contains no word/styles.xml');\n }\n\n const stylesXml = await stylesEntry.async('string');\n zip.file('word/styles.xml', patchStylesXml(stylesXml, preset));\n\n const patched = await zip.generateAsync({ type: 'arraybuffer' });\n return new Blob([patched], { type: wordDocument.type });\n}\n\n/**\n * Applies `preset` to the document default run properties and to the six\n * heading styles of a styles.xml part.\n */\nexport function patchStylesXml(stylesXml: string, preset: FontPreset): string {\n const dom = new DOMParser().parseFromString(stylesXml, 'application/xml');\n\n const docDefaults = requireElement(dom, 'docDefaults');\n applyLevelStyle(docDefaults, preset.body, preset.paragraph);\n\n const styles = Array.from(dom.getElementsByTagNameNS(W_NS, 'style'));\n for (const style of styles) {\n const heading = /^Heading([1-6])$/.exec(style.getAttributeNS(W_NS, 'styleId') ?? '');\n if (heading) {\n applyLevelStyle(style, preset.headings[Number(heading[1]) - 1], preset.paragraph);\n }\n }\n\n return keepXmlDeclaration(stylesXml, new XMLSerializer().serializeToString(dom));\n}\n\nfunction applyLevelStyle(scope: Element, style: LevelStyle, paragraph: ParagraphStyle): void {\n const rPr = runPropertiesOf(scope);\n\n const rFonts = childOrCreate(rPr, 'rFonts', 'first');\n for (const attribute of THEME_FONT_ATTRIBUTES) {\n rFonts.removeAttributeNS(W_NS, attribute);\n }\n rFonts.setAttributeNS(W_NS, 'w:ascii', style.latin);\n rFonts.setAttributeNS(W_NS, 'w:hAnsi', style.latin);\n rFonts.setAttributeNS(W_NS, 'w:eastAsia', style.eastAsia);\n\n for (const child of children(rPr)) {\n if (child.localName === 'b' || child.localName === 'bCs') {\n child.remove();\n }\n }\n if (style.bold) {\n rPr.insertBefore(rPr.ownerDocument.createElementNS(W_NS, 'w:b'), rFonts.nextSibling);\n }\n\n // <w:sz> is measured in half points.\n const size = String(style.sizePt * 2);\n childOrCreate(rPr, 'sz', 'last').setAttributeNS(W_NS, 'w:val', size);\n childOrCreate(rPr, 'szCs', 'last').setAttributeNS(W_NS, 'w:val', size);\n\n const spacing = childOrCreate(paragraphPropertiesOf(scope), 'spacing', 'first');\n spacing.setAttributeNS(W_NS, 'w:before', String(paragraph.beforePt * 20));\n spacing.setAttributeNS(W_NS, 'w:after', String(paragraph.afterPt * 20));\n\n const line = LINE_SPACING[paragraph.lineSpacing];\n spacing.setAttributeNS(W_NS, 'w:line', line.line);\n spacing.setAttributeNS(W_NS, 'w:lineRule', line.rule);\n}\n\nfunction runPropertiesOf(parent: Element): Element {\n const container =\n parent.localName === 'docDefaults'\n ? childOrCreate(parent, 'rPrDefault', 'first')\n : parent;\n // In a <w:style> the run properties go last, after any <w:pPr>.\n return childOrCreate(container, 'rPr', 'last');\n}\n\nfunction paragraphPropertiesOf(parent: Element): Element {\n if (parent.localName === 'docDefaults') {\n const pPrDefault = childOrCreate(parent, 'pPrDefault', 'last');\n return childOrCreate(pPrDefault, 'pPr', 'first');\n }\n\n const existing = children(parent).find((child) => child.localName === 'pPr');\n if (existing) {\n return existing;\n }\n // In a <w:style> the paragraph properties go before the run properties.\n const created = parent.ownerDocument.createElementNS(W_NS, 'w:pPr');\n return parent.insertBefore(created, runPropertiesOf(parent));\n}\n\nfunction children(element: Element): Element[] {\n return Array.from(element.children).filter((child) => child.namespaceURI === W_NS);\n}\n\nfunction childOrCreate(parent: Element, localName: string, position: 'first' | 'last'): Element {\n const existing = children(parent).find((child) => child.localName === localName);\n if (existing) {\n return existing;\n }\n const created = parent.ownerDocument.createElementNS(W_NS, `w:${localName}`);\n return position === 'first'\n ? parent.insertBefore(created, parent.firstChild)\n : parent.appendChild(created);\n}\n\nfunction requireElement(dom: Document, localName: string): Element {\n const element = dom.getElementsByTagNameNS(W_NS, localName)[0];\n if (!element) {\n throw new Error(`Cannot apply font preset: styles.xml has no <w:${localName}> element`);\n }\n return element;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"docx-font-preset.js","sourceRoot":"","sources":["../src/docx-font-preset.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAE1B,OAAO,EACL,kBAAkB,EAClB,iBAAiB,EACjB,iBAAiB,IAAI,IAAI,GAC1B,MAAM,eAAe,CAAC;AAEvB,+DAA+D;AAC/D,MAAM,qBAAqB,GAAG;IAC5B,YAAY;IACZ,eAAe;IACf,YAAY;IACZ,SAAS;CACV,CAAC;AAEF;;;GAGG;AACH,MAAM,cAAc,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;AAiBrD;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,KAAK,U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IAAI,CAAC,OAAO,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CACb,kDAAkD,SAAS,WAAW,CACvE,CAAC;IACJ,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import JSZip from 'jszip';\nimport type { FontPreset, LevelStyle, ParagraphStyle } from './font-presets.js';\nimport {\n keepXmlDeclaration,\n paragraphProperty,\n WORDPROCESSING_NS as W_NS,\n} from './xml-part.js';\n\n/** Theme slots WinWord prefers over explicitly named fonts. */\nconst THEME_FONT_ATTRIBUTES = [\n 'asciiTheme',\n 'eastAsiaTheme',\n 'hAnsiTheme',\n 'cstheme',\n];\n\n/**\n * `<w:line>` is ignored while the rule is auto, but WinWord still writes 240\n * twips, so the preset writes the pair Word itself produces.\n */\nconst SINGLE_SPACING = { line: '240', rule: 'auto' };\n\n/** Word's document grid, in the units of `<w:docGrid>`. */\ninterface Grid {\n /** Line pitch in twips. */\n linePitch: number;\n /** Character pitch relative to the body font size, in 1/4096 point. */\n charSpace: number;\n}\n\n/** What the styles need to know about the paragraphs, resolved once. */\ninterface Layout {\n spacing: { line: string; rule: string };\n /** First-line indent of body paragraphs in twips, or 0 for none. */\n firstLineIndent: number;\n}\n\n/**\n * Rewrites the fonts, sizes, paragraph spacing and page grid of an already\n * generated .docx.\n *\n * `html-to-docx` only ever writes `w:ascii`, which WinWord applies to Latin\n * characters and digits; Chinese characters fall back to the theme font. The\n * East Asian slots are set here instead, so this stays out of the way of the\n * default conversion output.\n *\n * The grid is measured from the page the document actually has, so it still\n * fits when `pageMargins` overrode the preset's margins.\n */\nexport async function applyFontPreset(\n wordDocument: Blob,\n preset: FontPreset\n): Promise<Blob> {\n const zip = await JSZip.loadAsync(await wordDocument.arrayBuffer());\n const stylesEntry = zip.file('word/styles.xml');\n if (!stylesEntry) {\n throw new Error(\n 'Cannot apply font preset: document contains no word/styles.xml'\n );\n }\n\n let grid: Grid | null = null;\n const pageGrid = preset.page?.grid;\n if (\n pageGrid ||\n preset.paragraph.lineSpacing === 'grid' ||\n preset.paragraph.firstLineIndentChars\n ) {\n const documentEntry = zip.file('word/document.xml');\n if (!documentEntry) {\n throw new Error(\n 'Cannot apply font preset: document contains no word/document.xml'\n );\n }\n const documentXml = await documentEntry.async('string');\n const patched = patchDocumentXml(documentXml, preset);\n grid = patched.grid;\n zip.file('word/document.xml', patched.xml);\n }\n\n const stylesXml = await stylesEntry.async('string');\n zip.file('word/styles.xml', patchStylesXml(stylesXml, preset, grid));\n\n const patched = await zip.generateAsync({ type: 'arraybuffer' });\n return new Blob([patched], { type: wordDocument.type });\n}\n\n/**\n * Applies `preset` to the document default run properties and to the six\n * heading styles of a styles.xml part. `grid` is the page grid that\n * `patchDocumentXml` set, which `lineSpacing: 'grid'` takes its pitch from.\n */\nexport function patchStylesXml(\n stylesXml: string,\n preset: FontPreset,\n grid: Grid | null = null\n): string {\n const dom = new DOMParser().parseFromString(stylesXml, 'application/xml');\n const layout = resolveLayout(preset, grid);\n\n const docDefaults = requireElement(dom, 'docDefaults');\n applyLevelStyle(docDefaults, preset.body, preset.paragraph, layout);\n if (layout.spacing.rule === 'exact') {\n // Widow control pulls a line onto the next page whenever a paragraph would\n // leave a single line behind, so pages would often hold one line fewer\n // than the grid. Word turns it on unless the document says otherwise.\n paragraphProperty(\n paragraphPropertiesOf(docDefaults),\n 'widowControl'\n ).setAttributeNS(W_NS, 'w:val', '0');\n }\n\n const styles = Array.from(dom.getElementsByTagNameNS(W_NS, 'style'));\n for (const style of styles) {\n const heading = /^Heading([1-6])$/.exec(\n style.getAttributeNS(W_NS, 'styleId') ?? ''\n );\n if (heading) {\n applyLevelStyle(\n style,\n preset.headings[Number(heading[1]) - 1],\n preset.paragraph,\n layout\n );\n }\n }\n\n return keepXmlDeclaration(\n stylesXml,\n new XMLSerializer().serializeToString(dom)\n );\n}\n\nfunction resolveLayout(preset: FontPreset, grid: Grid | null): Layout {\n const { lineSpacing, firstLineIndentChars = 0 } = preset.paragraph;\n if (lineSpacing === 'grid' && !grid) {\n throw new Error(\n \"Cannot apply font preset: lineSpacing 'grid' needs page.grid\"\n );\n }\n return {\n spacing:\n lineSpacing === 'grid' && grid\n ? { line: String(grid.linePitch), rule: 'exact' }\n : SINGLE_SPACING,\n firstLineIndent: Math.round(firstLineIndentChars * preset.body.sizePt * 20),\n };\n}\n\n/**\n * Sets the page grid in the section properties of a document.xml part, and\n * fixes up the paragraphs that the style-level layout would break:\n *\n * - The generator gives every paragraph `<w:spacing w:lineRule=\"auto\"/>`.\n * Spacing attributes inherit one at a time, so that lone `auto` combined\n * with the style's exact line height would read as a multiple of 240 twips\n * (about 2.4 lines). It is dropped when the preset uses grid spacing.\n * - Exact line spacing would crop an inline image to one line, so paragraphs\n * with a drawing keep single spacing; the grid then rounds them up to whole\n * lines.\n * - Table cells drop the first-line indent; it only crowds narrow columns.\n */\nexport function patchDocumentXml(\n documentXml: string,\n preset: FontPreset\n): { xml: string; grid: Grid | null } {\n const dom = new DOMParser().parseFromString(documentXml, 'application/xml');\n\n let grid: Grid | null = null;\n const pageGrid = preset.page?.grid;\n if (pageGrid) {\n for (const sectPr of Array.from(\n dom.getElementsByTagNameNS(W_NS, 'sectPr')\n )) {\n grid = measureGrid(sectPr, pageGrid, preset.body.sizePt);\n setDocGrid(sectPr, grid);\n }\n }\n\n const gridSpacing = preset.paragraph.lineSpacing === 'grid';\n for (const paragraph of Array.from(dom.getElementsByTagNameNS(W_NS, 'p'))) {\n const pPr = children(paragraph).find((child) => child.localName === 'pPr');\n\n if (gridSpacing) {\n if (paragraph.getElementsByTagNameNS(W_NS, 'drawing').length > 0) {\n const spacing = paragraphProperty(pPrOf(paragraph), 'spacing');\n spacing.setAttributeNS(W_NS, 'w:line', SINGLE_SPACING.line);\n spacing.setAttributeNS(W_NS, 'w:lineRule', SINGLE_SPACING.rule);\n } else {\n const spacing =\n pPr && children(pPr).find((child) => child.localName === 'spacing');\n if (spacing && !spacing.hasAttributeNS(W_NS, 'line')) {\n spacing.removeAttributeNS(W_NS, 'lineRule');\n if (spacing.attributes.length === 0) {\n spacing.remove();\n }\n }\n }\n }\n\n if (preset.paragraph.firstLineIndentChars && isInTableCell(paragraph)) {\n removeFirstLineIndent(pPrOf(paragraph));\n }\n }\n\n return {\n xml: keepXmlDeclaration(\n documentXml,\n new XMLSerializer().serializeToString(dom)\n ),\n grid,\n };\n}\n\n/**\n * The grid for the text block of `sectPr`'s page. Word stores the character\n * pitch as an offset from the body font size. Both pitches are rounded down,\n * as Word does, so the lines and characters always fit: for the page Word\n * itself sets up with GB/T 9704 margins, this reproduces its linePitch=\"579\"\n * and charSpace=\"-834\".\n */\nfunction measureGrid(\n sectPr: Element,\n {\n linesPerPage,\n charsPerLine,\n }: { linesPerPage: number; charsPerLine: number },\n bodySizePt: number\n): Grid {\n const pgSz = children(sectPr).find((child) => child.localName === 'pgSz');\n const pgMar = children(sectPr).find((child) => child.localName === 'pgMar');\n const twips = (element: Element | undefined, attribute: string): number => {\n const value = Number(element?.getAttributeNS(W_NS, attribute));\n if (!Number.isFinite(value) || value <= 0) {\n throw new Error(\n `Cannot apply font preset: section has no page ${attribute}`\n );\n }\n return value;\n };\n\n const textHeight =\n twips(pgSz, 'h') - twips(pgMar, 'top') - twips(pgMar, 'bottom');\n const textWidth =\n twips(pgSz, 'w') - twips(pgMar, 'left') - twips(pgMar, 'right');\n const charPitchPt = textWidth / 20 / charsPerLine;\n\n return {\n linePitch: Math.floor(textHeight / linesPerPage),\n charSpace: Math.floor((charPitchPt - bodySizePt) * 4096),\n };\n}\n\nfunction setDocGrid(sectPr: Element, grid: Grid): void {\n let docGrid = children(sectPr).find((child) => child.localName === 'docGrid');\n if (!docGrid) {\n docGrid = sectPr.ownerDocument.createElementNS(W_NS, 'w:docGrid');\n // <w:docGrid> is the last section property but <w:printerSettings>.\n const printerSettings = children(sectPr).find(\n (child) => child.localName === 'printerSettings'\n );\n sectPr.insertBefore(docGrid, printerSettings ?? null);\n }\n docGrid.setAttributeNS(W_NS, 'w:type', 'linesAndChars');\n docGrid.setAttributeNS(W_NS, 'w:linePitch', String(grid.linePitch));\n docGrid.setAttributeNS(W_NS, 'w:charSpace', String(grid.charSpace));\n}\n\nfunction isInTableCell(paragraph: Element): boolean {\n for (let node = paragraph.parentElement; node; node = node.parentElement) {\n if (node.namespaceURI === W_NS && node.localName === 'tc') {\n return true;\n }\n }\n return false;\n}\n\nfunction removeFirstLineIndent(pPr: Element): void {\n const ind = paragraphProperty(pPr, 'ind');\n if (!ind.hasAttributeNS(W_NS, 'hanging')) {\n ind.setAttributeNS(W_NS, 'w:firstLine', '0');\n }\n}\n\n/** A paragraph's `<w:pPr>`, created as its first child if missing. */\nfunction pPrOf(paragraph: Element): Element {\n return childOrCreate(paragraph, 'pPr', 'first');\n}\n\nfunction applyLevelStyle(\n scope: Element,\n style: LevelStyle,\n paragraph: ParagraphStyle,\n layout: Layout\n): void {\n const rPr = runPropertiesOf(scope);\n\n const rFonts = childOrCreate(rPr, 'rFonts', 'first');\n for (const attribute of THEME_FONT_ATTRIBUTES) {\n rFonts.removeAttributeNS(W_NS, attribute);\n }\n rFonts.setAttributeNS(W_NS, 'w:ascii', style.latin);\n rFonts.setAttributeNS(W_NS, 'w:hAnsi', style.latin);\n rFonts.setAttributeNS(W_NS, 'w:eastAsia', style.eastAsia);\n\n for (const child of children(rPr)) {\n if (child.localName === 'b' || child.localName === 'bCs') {\n child.remove();\n }\n }\n if (style.bold) {\n rPr.insertBefore(\n rPr.ownerDocument.createElementNS(W_NS, 'w:b'),\n rFonts.nextSibling\n );\n }\n\n // <w:sz> is measured in half points.\n const size = String(style.sizePt * 2);\n childOrCreate(rPr, 'sz', 'last').setAttributeNS(W_NS, 'w:val', size);\n childOrCreate(rPr, 'szCs', 'last').setAttributeNS(W_NS, 'w:val', size);\n\n const pPr = paragraphPropertiesOf(scope);\n const spacing = paragraphProperty(pPr, 'spacing');\n spacing.setAttributeNS(W_NS, 'w:before', String(paragraph.beforePt * 20));\n spacing.setAttributeNS(W_NS, 'w:after', String(paragraph.afterPt * 20));\n spacing.setAttributeNS(W_NS, 'w:line', layout.spacing.line);\n spacing.setAttributeNS(W_NS, 'w:lineRule', layout.spacing.rule);\n\n if (style.centered) {\n // An indented first line would push a centered title off center.\n if (layout.firstLineIndent) {\n paragraphProperty(pPr, 'ind').setAttributeNS(W_NS, 'w:firstLine', '0');\n }\n paragraphProperty(pPr, 'jc').setAttributeNS(W_NS, 'w:val', 'center');\n } else if (layout.firstLineIndent) {\n paragraphProperty(pPr, 'ind').setAttributeNS(\n W_NS,\n 'w:firstLine',\n String(layout.firstLineIndent)\n );\n }\n}\n\nfunction runPropertiesOf(parent: Element): Element {\n const container =\n parent.localName === 'docDefaults'\n ? childOrCreate(parent, 'rPrDefault', 'first')\n : parent;\n // In a <w:style> the run properties go last, after any <w:pPr>.\n return childOrCreate(container, 'rPr', 'last');\n}\n\nfunction paragraphPropertiesOf(parent: Element): Element {\n if (parent.localName === 'docDefaults') {\n const pPrDefault = childOrCreate(parent, 'pPrDefault', 'last');\n return childOrCreate(pPrDefault, 'pPr', 'first');\n }\n\n const existing = children(parent).find((child) => child.localName === 'pPr');\n if (existing) {\n return existing;\n }\n // In a <w:style> the paragraph properties go before the run properties.\n const created = parent.ownerDocument.createElementNS(W_NS, 'w:pPr');\n return parent.insertBefore(created, runPropertiesOf(parent));\n}\n\nfunction children(element: Element): Element[] {\n return Array.from(element.children).filter(\n (child) => child.namespaceURI === W_NS\n );\n}\n\nfunction childOrCreate(\n parent: Element,\n localName: string,\n position: 'first' | 'last'\n): Element {\n const existing = children(parent).find(\n (child) => child.localName === localName\n );\n if (existing) {\n return existing;\n }\n const created = parent.ownerDocument.createElementNS(W_NS, `w:${localName}`);\n return position === 'first'\n ? parent.insertBefore(created, parent.firstChild)\n : parent.appendChild(created);\n}\n\nfunction requireElement(dom: Document, localName: string): Element {\n const element = dom.getElementsByTagNameNS(W_NS, localName)[0];\n if (!element) {\n throw new Error(\n `Cannot apply font preset: styles.xml has no <w:${localName}> element`\n );\n }\n return element;\n}\n"]}
|
package/build/docx-html.d.ts
CHANGED
|
@@ -23,6 +23,16 @@ export declare const RULE_TEXT = "* * *";
|
|
|
23
23
|
* the same value as a `text-align` style is honored.
|
|
24
24
|
* - Horizontal rules: `<hr>` is dropped, so it becomes a centered RULE_TEXT
|
|
25
25
|
* paragraph for the structure patch to draw as a rule.
|
|
26
|
+
* - Block quotes: the generator joins everything in a `<blockquote>` into one
|
|
27
|
+
* justified paragraph. Its paragraphs and headings are kept apart instead,
|
|
28
|
+
* left aligned and indented one step per level of nesting.
|
|
29
|
+
* - Inline elements it doesn't know (`<kbd>`, `<abbr>`, `<q>`, ...): their
|
|
30
|
+
* text is dropped, so each is replaced by a span or `<em>` (see
|
|
31
|
+
* UNKNOWN_INLINE). `<mark>` loses its highlight, so it's set as a shading.
|
|
32
|
+
* - Footnotes: the reference and back links point into the page, which a
|
|
33
|
+
* Word reader can't follow, so references keep only their number and the
|
|
34
|
+
* back links (↩) go. So does the footnotes heading, which the page only
|
|
35
|
+
* shows to screen readers.
|
|
26
36
|
*
|
|
27
37
|
* Only the HTML bound for the .docx changes; the preview keeps the original.
|
|
28
38
|
*/
|
package/build/docx-html.js
CHANGED
|
@@ -20,6 +20,38 @@ export const RULE_TEXT = '* * *';
|
|
|
20
20
|
* serialized tags, where the CSP doesn't reach.
|
|
21
21
|
*/
|
|
22
22
|
const STYLE_PLACEHOLDER = 'data-docx-style';
|
|
23
|
+
/** How far each level of block quote is indented. */
|
|
24
|
+
const QUOTE_INDENT_INCHES = 0.5;
|
|
25
|
+
/** Block quote children that become indented paragraphs. */
|
|
26
|
+
const QUOTE_PARAGRAPHS = new Set(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
|
|
27
|
+
/**
|
|
28
|
+
* Inline elements the generator doesn't know, whose text it drops. Each is
|
|
29
|
+
* replaced by what a browser shows: a span (in the code font, for the ones a
|
|
30
|
+
* browser draws in monospace), emphasis, or quotation marks.
|
|
31
|
+
*/
|
|
32
|
+
const UNKNOWN_INLINE = {
|
|
33
|
+
kbd: 'code',
|
|
34
|
+
samp: 'code',
|
|
35
|
+
tt: 'code',
|
|
36
|
+
var: 'em',
|
|
37
|
+
cite: 'em',
|
|
38
|
+
dfn: 'em',
|
|
39
|
+
q: 'quote',
|
|
40
|
+
abbr: 'text',
|
|
41
|
+
acronym: 'text',
|
|
42
|
+
bdi: 'text',
|
|
43
|
+
bdo: 'text',
|
|
44
|
+
big: 'text',
|
|
45
|
+
data: 'text',
|
|
46
|
+
font: 'text',
|
|
47
|
+
label: 'text',
|
|
48
|
+
small: 'text',
|
|
49
|
+
time: 'text',
|
|
50
|
+
};
|
|
51
|
+
/** `Node.TEXT_NODE`, which Node's globals lack. */
|
|
52
|
+
const TEXT_NODE = 3;
|
|
53
|
+
/** The highlight browsers give `<mark>`; the generator drops it. */
|
|
54
|
+
const MARK_COLOR = '#FFFF00';
|
|
23
55
|
/**
|
|
24
56
|
* Adjusts the parser's HTML for html-to-docx, which drops or flattens some of
|
|
25
57
|
* what the browser preview renders:
|
|
@@ -33,13 +65,25 @@ const STYLE_PLACEHOLDER = 'data-docx-style';
|
|
|
33
65
|
* the same value as a `text-align` style is honored.
|
|
34
66
|
* - Horizontal rules: `<hr>` is dropped, so it becomes a centered RULE_TEXT
|
|
35
67
|
* paragraph for the structure patch to draw as a rule.
|
|
68
|
+
* - Block quotes: the generator joins everything in a `<blockquote>` into one
|
|
69
|
+
* justified paragraph. Its paragraphs and headings are kept apart instead,
|
|
70
|
+
* left aligned and indented one step per level of nesting.
|
|
71
|
+
* - Inline elements it doesn't know (`<kbd>`, `<abbr>`, `<q>`, ...): their
|
|
72
|
+
* text is dropped, so each is replaced by a span or `<em>` (see
|
|
73
|
+
* UNKNOWN_INLINE). `<mark>` loses its highlight, so it's set as a shading.
|
|
74
|
+
* - Footnotes: the reference and back links point into the page, which a
|
|
75
|
+
* Word reader can't follow, so references keep only their number and the
|
|
76
|
+
* back links (↩) go. So does the footnotes heading, which the page only
|
|
77
|
+
* shows to screen readers.
|
|
36
78
|
*
|
|
37
79
|
* Only the HTML bound for the .docx changes; the preview keeps the original.
|
|
38
80
|
*/
|
|
39
81
|
export function prepareHtmlForDocx(html) {
|
|
40
82
|
const dom = new DOMParser().parseFromString(html, 'text/html');
|
|
41
83
|
for (const input of Array.from(dom.querySelectorAll('input[type="checkbox"]'))) {
|
|
42
|
-
const box = input.hasAttribute('checked')
|
|
84
|
+
const box = input.hasAttribute('checked')
|
|
85
|
+
? CHECKBOX.checked
|
|
86
|
+
: CHECKBOX.unchecked;
|
|
43
87
|
input.replaceWith(dom.createTextNode(box));
|
|
44
88
|
}
|
|
45
89
|
for (const code of Array.from(dom.querySelectorAll('code'))) {
|
|
@@ -63,6 +107,44 @@ export function prepareHtmlForDocx(html) {
|
|
|
63
107
|
cell.append(strong);
|
|
64
108
|
}
|
|
65
109
|
}
|
|
110
|
+
for (const quote of Array.from(dom.querySelectorAll('blockquote'))) {
|
|
111
|
+
// Outermost first; each one unwraps its nested quotes as it goes.
|
|
112
|
+
if (quote.isConnected)
|
|
113
|
+
unwrapQuote(quote, 1);
|
|
114
|
+
}
|
|
115
|
+
for (const element of Array.from(dom.body.querySelectorAll('*'))) {
|
|
116
|
+
const kind = UNKNOWN_INLINE[element.localName];
|
|
117
|
+
if (!kind || element.closest('pre'))
|
|
118
|
+
continue;
|
|
119
|
+
if (kind === 'quote') {
|
|
120
|
+
element.replaceWith('“', ...Array.from(element.childNodes), '”');
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
const replacement = dom.createElement(kind === 'em' ? 'em' : 'span');
|
|
124
|
+
if (kind === 'code') {
|
|
125
|
+
replacement.setAttribute(STYLE_PLACEHOLDER, `font-family: ${CODE_FONT}`);
|
|
126
|
+
}
|
|
127
|
+
replacement.append(...Array.from(element.childNodes));
|
|
128
|
+
element.replaceWith(replacement);
|
|
129
|
+
}
|
|
130
|
+
for (const mark of Array.from(dom.querySelectorAll('mark'))) {
|
|
131
|
+
const span = dom.createElement('span');
|
|
132
|
+
span.setAttribute(STYLE_PLACEHOLDER, `background-color: ${MARK_COLOR}`);
|
|
133
|
+
span.append(...Array.from(mark.childNodes));
|
|
134
|
+
mark.replaceWith(span);
|
|
135
|
+
}
|
|
136
|
+
for (const reference of Array.from(dom.querySelectorAll('a[data-footnote-ref]'))) {
|
|
137
|
+
reference.replaceWith(...Array.from(reference.childNodes));
|
|
138
|
+
}
|
|
139
|
+
for (const backReference of Array.from(dom.querySelectorAll('a[data-footnote-backref]'))) {
|
|
140
|
+
// The space before it, too, so the note doesn't end in one.
|
|
141
|
+
const before = backReference.previousSibling;
|
|
142
|
+
if (before?.nodeType === TEXT_NODE && before.textContent?.endsWith(' ')) {
|
|
143
|
+
before.textContent = before.textContent.slice(0, -1);
|
|
144
|
+
}
|
|
145
|
+
backReference.remove();
|
|
146
|
+
}
|
|
147
|
+
dom.querySelector('section[data-footnotes] > h2')?.remove();
|
|
66
148
|
for (const rule of Array.from(dom.querySelectorAll('hr'))) {
|
|
67
149
|
const paragraph = dom.createElement('p');
|
|
68
150
|
paragraph.setAttribute(STYLE_PLACEHOLDER, 'text-align: center');
|
|
@@ -72,4 +154,27 @@ export function prepareHtmlForDocx(html) {
|
|
|
72
154
|
// Only inside tags: text can't contain a raw `<`, so it's never touched.
|
|
73
155
|
return dom.body.innerHTML.replace(/<[^>]+>/g, (tag) => tag.replace(` ${STYLE_PLACEHOLDER}=`, ' style='));
|
|
74
156
|
}
|
|
157
|
+
/**
|
|
158
|
+
* Replaces `quote` with its children, indenting its paragraphs and headings
|
|
159
|
+
* `depth` steps. Other blocks (lists, code, tables) keep their own layout, and
|
|
160
|
+
* so does a quote in a list item: the generator indents that paragraph for the
|
|
161
|
+
* list already, and a second indent would be invalid or move the bullet.
|
|
162
|
+
*/
|
|
163
|
+
function unwrapQuote(quote, depth) {
|
|
164
|
+
const inList = quote.closest('li') !== null;
|
|
165
|
+
for (const child of Array.from(quote.children)) {
|
|
166
|
+
if (child.localName === 'blockquote') {
|
|
167
|
+
unwrapQuote(child, depth + 1);
|
|
168
|
+
}
|
|
169
|
+
else if (QUOTE_PARAGRAPHS.has(child.localName)) {
|
|
170
|
+
const align = 'text-align: left';
|
|
171
|
+
const layout = inList
|
|
172
|
+
? align
|
|
173
|
+
: `margin-left: ${depth * QUOTE_INDENT_INCHES}in; ${align}`;
|
|
174
|
+
const style = child.getAttribute(STYLE_PLACEHOLDER);
|
|
175
|
+
child.setAttribute(STYLE_PLACEHOLDER, style ? `${style}; ${layout}` : layout);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
quote.replaceWith(...Array.from(quote.childNodes));
|
|
179
|
+
}
|
|
75
180
|
//# sourceMappingURL=docx-html.js.map
|
package/build/docx-html.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"docx-html.js","sourceRoot":"","sources":["../src/docx-html.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,aAAa,CAAC;AAEvC,+EAA+E;AAC/E,MAAM,QAAQ,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,GAAG,EAAE,CAAC;AAElD;;;;GAIG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,OAAO,CAAC;AAEjC;;;;;;GAMG;AACH,MAAM,iBAAiB,GAAG,iBAAiB,CAAC;AAE5C;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,kBAAkB,CAAC,IAAY;IAC7C,MAAM,GAAG,GAAG,IAAI,SAAS,EAAE,CAAC,eAAe,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC;IAE/D,KAAK,MAAM,KAAK,IAAI,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,gBAAgB,CAAC,wBAAwB,CAAC,CAAC,EAAE,CAAC;QAC/E,MAAM,GAAG,GAAG,KAAK,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,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AC,MAAM,CAAC,CAAC;QACtB,CAAC;IACH,CAAC;IAED,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC;QAC1D,MAAM,SAAS,GAAG,GAAG,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC;QACzC,SAAS,CAAC,YAAY,CAAC,iBAAiB,EAAE,oBAAoB,CAAC,CAAC;QAChE,SAAS,CAAC,WAAW,GAAG,SAAS,CAAC;QAClC,IAAI,CAAC,WAAW,CAAC,SAAS,CAAC,CAAC;IAC9B,CAAC;IAED,yEAAyE;IACzE,OAAO,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,GAAG,EAAE,EAAE,CACpD,GAAG,CAAC,OAAO,CAAC,IAAI,iBAAiB,GAAG,EAAE,SAAS,CAAC,CACjD,CAAC;AACJ,CAAC","sourcesContent":["/**\n * A monospace face that ships with Windows, so Chinese comments stay aligned.\n * Defined here rather than in the code block patch so the main bundle can use\n * it without loading that patch and JSZip.\n */\nexport const CODE_FONT = 'Courier New';\n\n/** What Word shows in place of a task list checkbox, which it can't render. */\nconst CHECKBOX = { checked: '☒', unchecked: '☐' };\n\n/**\n * Stands in for `<hr>`, which the generator drops. The structure patch turns\n * each one into a bordered paragraph; if that patch fails, a centered `* * *`\n * still reads as a section break.\n */\nexport const RULE_TEXT = '* * *';\n\n/**\n * Stands in for `style` while the HTML is a live DOM. The page's CSP applies\n * to DOMParser documents too, and blocks (and reports) `style` attributes set\n * there. (CSSOM is allowed, but it quotes a font name with a space, which the\n * generator would read as part of the name.) Renamed back to `style` in the\n * serialized tags, where the CSP doesn't reach.\n */\nconst STYLE_PLACEHOLDER = 'data-docx-style';\n\n/**\n * Adjusts the parser's HTML for html-to-docx, which drops or flattens some of\n * what the browser preview renders:\n *\n * - Task list checkboxes: `<input>` is dropped, so done and pending items read\n * the same. Each becomes a ☒ or ☐ character.\n * - Inline code: `<code>` keeps the body font. Its text is wrapped in a span\n * naming the code block font, which the generator does carry over.\n * - Table header cells: `<th>` isn't bold, so its content is wrapped in\n * `<strong>`. Column alignment from GFM's `align` attribute is ignored, but\n * the same value as a `text-align` style is honored.\n * - Horizontal rules: `<hr>` is dropped, so it becomes a centered RULE_TEXT\n * paragraph for the structure patch to draw as a rule.\n *\n * Only the HTML bound for the .docx changes; the preview keeps the original.\n */\nexport function prepareHtmlForDocx(html: string): string {\n const dom = new DOMParser().parseFromString(html, 'text/html');\n\n for (const input of Array.from(dom.querySelectorAll('input[type=\"checkbox\"]'))) {\n const box = input.hasAttribute('checked') ? CHECKBOX.checked : CHECKBOX.unchecked;\n input.replaceWith(dom.createTextNode(box));\n }\n\n for (const code of Array.from(dom.querySelectorAll('code'))) {\n if (code.closest('pre')) continue;\n const span = dom.createElement('span');\n // A raw attribute, not `style.fontFamily`: see STYLE_PLACEHOLDER.\n span.setAttribute(STYLE_PLACEHOLDER, `font-family: ${CODE_FONT}`);\n span.append(...Array.from(code.childNodes));\n code.append(span);\n }\n\n for (const cell of Array.from(dom.querySelectorAll('th, td'))) {\n const align = cell.getAttribute('align');\n if (align) {\n (cell as HTMLElement).style.textAlign = align;\n cell.removeAttribute('align');\n }\n if (cell.localName === 'th' && cell.textContent?.trim()) {\n const strong = dom.createElement('strong');\n strong.append(...Array.from(cell.childNodes));\n cell.append(strong);\n }\n }\n\n for (const rule of Array.from(dom.querySelectorAll('hr'))) {\n const paragraph = dom.createElement('p');\n paragraph.setAttribute(STYLE_PLACEHOLDER, 'text-align: center');\n paragraph.textContent = RULE_TEXT;\n rule.replaceWith(paragraph);\n }\n\n // Only inside tags: text can't contain a raw `<`, so it's never touched.\n return dom.body.innerHTML.replace(/<[^>]+>/g, (tag) =>\n tag.replace(` ${STYLE_PLACEHOLDER}=`, ' style='),\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"docx-html.js","sourceRoot":"","sources":["../src/docx-html.ts"],"names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C,CAAC;YACpD,KAAK,CAAC,YAAY,CAChB,iBAAiB,EACjB,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,KAAK,MAAM,EAAE,CAAC,CAAC,CAAC,MAAM,CACvC,CAAC;QACJ,CAAC;IACH,CAAC;IACD,KAAK,CAAC,WAAW,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC;AACrD,CAAC","sourcesContent":["/**\n * A monospace face that ships with Windows, so Chinese comments stay aligned.\n * Defined here rather than in the code block patch so the main bundle can use\n * it without loading that patch and JSZip.\n */\nexport const CODE_FONT = 'Courier New';\n\n/** What Word shows in place of a task list checkbox, which it can't render. */\nconst CHECKBOX = { checked: '☒', unchecked: '☐' };\n\n/**\n * Stands in for `<hr>`, which the generator drops. The structure patch turns\n * each one into a bordered paragraph; if that patch fails, a centered `* * *`\n * still reads as a section break.\n */\nexport const RULE_TEXT = '* * *';\n\n/**\n * Stands in for `style` while the HTML is a live DOM. The page's CSP applies\n * to DOMParser documents too, and blocks (and reports) `style` attributes set\n * there. (CSSOM is allowed, but it quotes a font name with a space, which the\n * generator would read as part of the name.) Renamed back to `style` in the\n * serialized tags, where the CSP doesn't reach.\n */\nconst STYLE_PLACEHOLDER = 'data-docx-style';\n\n/** How far each level of block quote is indented. */\nconst QUOTE_INDENT_INCHES = 0.5;\n\n/** Block quote children that become indented paragraphs. */\nconst QUOTE_PARAGRAPHS = new Set(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']);\n\n/**\n * Inline elements the generator doesn't know, whose text it drops. Each is\n * replaced by what a browser shows: a span (in the code font, for the ones a\n * browser draws in monospace), emphasis, or quotation marks.\n */\nconst UNKNOWN_INLINE: Record<string, 'code' | 'em' | 'quote' | 'text'> = {\n kbd: 'code',\n samp: 'code',\n tt: 'code',\n var: 'em',\n cite: 'em',\n dfn: 'em',\n q: 'quote',\n abbr: 'text',\n acronym: 'text',\n bdi: 'text',\n bdo: 'text',\n big: 'text',\n data: 'text',\n font: 'text',\n label: 'text',\n small: 'text',\n time: 'text',\n};\n\n/** `Node.TEXT_NODE`, which Node's globals lack. */\nconst TEXT_NODE = 3;\n\n/** The highlight browsers give `<mark>`; the generator drops it. */\nconst MARK_COLOR = '#FFFF00';\n\n/**\n * Adjusts the parser's HTML for html-to-docx, which drops or flattens some of\n * what the browser preview renders:\n *\n * - Task list checkboxes: `<input>` is dropped, so done and pending items read\n * the same. Each becomes a ☒ or ☐ character.\n * - Inline code: `<code>` keeps the body font. Its text is wrapped in a span\n * naming the code block font, which the generator does carry over.\n * - Table header cells: `<th>` isn't bold, so its content is wrapped in\n * `<strong>`. Column alignment from GFM's `align` attribute is ignored, but\n * the same value as a `text-align` style is honored.\n * - Horizontal rules: `<hr>` is dropped, so it becomes a centered RULE_TEXT\n * paragraph for the structure patch to draw as a rule.\n * - Block quotes: the generator joins everything in a `<blockquote>` into one\n * justified paragraph. Its paragraphs and headings are kept apart instead,\n * left aligned and indented one step per level of nesting.\n * - Inline elements it doesn't know (`<kbd>`, `<abbr>`, `<q>`, ...): their\n * text is dropped, so each is replaced by a span or `<em>` (see\n * UNKNOWN_INLINE). `<mark>` loses its highlight, so it's set as a shading.\n * - Footnotes: the reference and back links point into the page, which a\n * Word reader can't follow, so references keep only their number and the\n * back links (↩) go. So does the footnotes heading, which the page only\n * shows to screen readers.\n *\n * Only the HTML bound for the .docx changes; the preview keeps the original.\n */\nexport function prepareHtmlForDocx(html: string): string {\n const dom = new DOMParser().parseFromString(html, 'text/html');\n\n for (const input of Array.from(\n dom.querySelectorAll('input[type=\"checkbox\"]')\n )) {\n const box = input.hasAttribute('checked')\n ? CHECKBOX.checked\n : CHECKBOX.unchecked;\n input.replaceWith(dom.createTextNode(box));\n }\n\n for (const code of Array.from(dom.querySelectorAll('code'))) {\n if (code.closest('pre')) continue;\n const span = dom.createElement('span');\n // A raw attribute, not `style.fontFamily`: see STYLE_PLACEHOLDER.\n span.setAttribute(STYLE_PLACEHOLDER, `font-family: ${CODE_FONT}`);\n span.append(...Array.from(code.childNodes));\n code.append(span);\n }\n\n for (const cell of Array.from(dom.querySelectorAll('th, td'))) {\n const align = cell.getAttribute('align');\n if (align) {\n (cell as HTMLElement).style.textAlign = align;\n cell.removeAttribute('align');\n }\n if (cell.localName === 'th' && cell.textContent?.trim()) {\n const strong = dom.createElement('strong');\n strong.append(...Array.from(cell.childNodes));\n cell.append(strong);\n }\n }\n\n for (const quote of Array.from(dom.querySelectorAll('blockquote'))) {\n // Outermost first; each one unwraps its nested quotes as it goes.\n if (quote.isConnected) unwrapQuote(quote, 1);\n }\n\n for (const element of Array.from(dom.body.querySelectorAll('*'))) {\n const kind = UNKNOWN_INLINE[element.localName];\n if (!kind || element.closest('pre')) continue;\n if (kind === 'quote') {\n element.replaceWith('“', ...Array.from(element.childNodes), '”');\n continue;\n }\n const replacement = dom.createElement(kind === 'em' ? 'em' : 'span');\n if (kind === 'code') {\n replacement.setAttribute(STYLE_PLACEHOLDER, `font-family: ${CODE_FONT}`);\n }\n replacement.append(...Array.from(element.childNodes));\n element.replaceWith(replacement);\n }\n\n for (const mark of Array.from(dom.querySelectorAll('mark'))) {\n const span = dom.createElement('span');\n span.setAttribute(STYLE_PLACEHOLDER, `background-color: ${MARK_COLOR}`);\n span.append(...Array.from(mark.childNodes));\n mark.replaceWith(span);\n }\n\n for (const reference of Array.from(\n dom.querySelectorAll('a[data-footnote-ref]')\n )) {\n reference.replaceWith(...Array.from(reference.childNodes));\n }\n for (const backReference of Array.from(\n dom.querySelectorAll('a[data-footnote-backref]')\n )) {\n // The space before it, too, so the note doesn't end in one.\n const before = backReference.previousSibling;\n if (before?.nodeType === TEXT_NODE && before.textContent?.endsWith(' ')) {\n before.textContent = before.textContent.slice(0, -1);\n }\n backReference.remove();\n }\n dom.querySelector('section[data-footnotes] > h2')?.remove();\n\n for (const rule of Array.from(dom.querySelectorAll('hr'))) {\n const paragraph = dom.createElement('p');\n paragraph.setAttribute(STYLE_PLACEHOLDER, 'text-align: center');\n paragraph.textContent = RULE_TEXT;\n rule.replaceWith(paragraph);\n }\n\n // Only inside tags: text can't contain a raw `<`, so it's never touched.\n return dom.body.innerHTML.replace(/<[^>]+>/g, (tag) =>\n tag.replace(` ${STYLE_PLACEHOLDER}=`, ' style=')\n );\n}\n\n/**\n * Replaces `quote` with its children, indenting its paragraphs and headings\n * `depth` steps. Other blocks (lists, code, tables) keep their own layout, and\n * so does a quote in a list item: the generator indents that paragraph for the\n * list already, and a second indent would be invalid or move the bullet.\n */\nfunction unwrapQuote(quote: Element, depth: number): void {\n const inList = quote.closest('li') !== null;\n for (const child of Array.from(quote.children)) {\n if (child.localName === 'blockquote') {\n unwrapQuote(child, depth + 1);\n } else if (QUOTE_PARAGRAPHS.has(child.localName)) {\n const align = 'text-align: left';\n const layout = inList\n ? align\n : `margin-left: ${depth * QUOTE_INDENT_INCHES}in; ${align}`;\n const style = child.getAttribute(STYLE_PLACEHOLDER);\n child.setAttribute(\n STYLE_PLACEHOLDER,\n style ? `${style}; ${layout}` : layout\n );\n }\n }\n quote.replaceWith(...Array.from(quote.childNodes));\n}\n"]}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** html-to-docx's own limit for one image (imageProcessing.maxImageSize). */
|
|
2
|
+
export declare const MAX_IMAGE_BYTES: number;
|
|
3
|
+
/**
|
|
4
|
+
* The most distinct image URLs fetched for one document: html-to-docx keeps
|
|
5
|
+
* at most this many in its image cache (imageProcessing.maxCacheEntries). The
|
|
6
|
+
* rest keep their alt text.
|
|
7
|
+
*/
|
|
8
|
+
export declare const MAX_IMAGES = 100;
|
|
9
|
+
/**
|
|
10
|
+
* How many downloads run at once. html-to-docx fetched one at a time; a few
|
|
11
|
+
* in parallel is faster without opening a connection per image.
|
|
12
|
+
*/
|
|
13
|
+
export declare const CONCURRENCY = 4;
|
|
14
|
+
/**
|
|
15
|
+
* Downloads each web image in `html` and swaps its `src` for a `data:` URI,
|
|
16
|
+
* which html-to-docx embeds without downloading it again. An image that can't
|
|
17
|
+
* be fetched becomes its alt text, linked to its URL, where html-to-docx would
|
|
18
|
+
* drop it without a trace. Other sources it can't embed either, such as a
|
|
19
|
+
* relative path, keep their alt text too.
|
|
20
|
+
*
|
|
21
|
+
* Each URL is fetched once, however many times it appears: at most
|
|
22
|
+
* MAX_IMAGES of them, CONCURRENCY at a time.
|
|
23
|
+
*/
|
|
24
|
+
export declare function embedImages(html: string): Promise<string>;
|