markdown-to-word 0.2.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 +21 -14
- package/build/converter.js +21 -10
- package/build/converter.js.map +1 -1
- package/build/docx-code-blocks.js +8 -2
- package/build/docx-code-blocks.js.map +1 -1
- package/build/docx-font-preset.js +8 -3
- 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.js +12 -2
- package/build/font-presets.js.map +1 -1
- package/build/markdown-parser.js +27 -3
- package/build/markdown-parser.js.map +1 -1
- package/build/xml-part.js +2 -1
- package/build/xml-part.js.map +1 -1
- package/package.json +10 -2
package/README.md
CHANGED
|
@@ -17,18 +17,20 @@ The document is named after its first heading, which also becomes its title.
|
|
|
17
17
|
|
|
18
18
|
## What converts
|
|
19
19
|
|
|
20
|
-
| Markdown
|
|
21
|
-
|
|
|
22
|
-
| `#` to `######` headings
|
|
23
|
-
| `**bold**`, `*italic*`, `~~strikethrough~~`
|
|
24
|
-
| Bulleted and numbered lists, nested
|
|
25
|
-
| `- [x]` task lists
|
|
26
|
-
| Tables
|
|
27
|
-
| `[links](https://example.com)`
|
|
28
|
-
| `` `inline code` `` and fenced code blocks
|
|
29
|
-
| `> block quotes`
|
|
30
|
-
| `---` horizontal rules
|
|
31
|
-
|
|
|
20
|
+
| Markdown | In Word |
|
|
21
|
+
| ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
|
|
22
|
+
| `#` to `######` headings | Heading 1–6 styles |
|
|
23
|
+
| `**bold**`, `*italic*`, `~~strikethrough~~` | The same formatting |
|
|
24
|
+
| Bulleted and numbered lists, nested | Word lists |
|
|
25
|
+
| `- [x]` task lists | ☒ (done) and ☐ (to do) items, since Word can't show checkboxes from HTML |
|
|
26
|
+
| Tables | Thin borders, a bold header row that repeats on each page, and the column alignment from the Markdown |
|
|
27
|
+
| `[links](https://example.com)` | Clickable hyperlinks |
|
|
28
|
+
| `` `inline code` `` and fenced code blocks | Monospace; code blocks keep their line breaks |
|
|
29
|
+
| `> block quotes` | Left-aligned paragraphs, indented one step per level of nesting |
|
|
30
|
+
| `---` horizontal rules | A line across the page |
|
|
31
|
+
| `[^1]` footnotes | Superscript numbers, with the notes as a numbered list after a line at the end of the document (not Word footnotes) |
|
|
32
|
+
| `` | Embedded, when the browser can fetch them; otherwise the alt text, linked to the image (see [Limitations](#limitations)) |
|
|
33
|
+
| `<kbd>`, `<mark>`, `<abbr>` and other inline HTML | The text, with `<kbd>` in the code font and `<mark>` highlighted |
|
|
32
34
|
|
|
33
35
|
As on GitHub, a single newline inside a paragraph is joined into the same line, so hard-wrapped files convert to normal paragraphs. End a line with two spaces or a backslash to force a line break.
|
|
34
36
|
|
|
@@ -84,7 +86,12 @@ Conversion happens entirely in your browser: your Markdown and the Word document
|
|
|
84
86
|
|
|
85
87
|
## Limitations
|
|
86
88
|
|
|
87
|
-
- Images are embedded only when the browser can fetch them: `data:` URIs, and web URLs whose server allows cross-origin requests (most image hosts and CDNs do).
|
|
89
|
+
- Images are embedded only when the browser can fetch them: `data:` URIs, and web URLs whose server allows cross-origin requests (most image hosts and CDNs do). Any other image, including a local file path, becomes its alt text, linked to the image's URL when it has one.
|
|
90
|
+
- Footnotes come out as a numbered list of notes at the end of the document, not as Word footnotes at the foot of each page.
|
|
91
|
+
- Math stays as the literal text: `$x^2$` comes out as `$x^2$`, not an equation.
|
|
92
|
+
- Emoji shortcodes such as `:tada:` aren't converted; paste the emoji itself instead.
|
|
93
|
+
- Links to headings in the same document (`[see below](#usage)`) don't jump anywhere in Word.
|
|
94
|
+
- `<details>` sections are flattened: the summary and the hidden content both show, as ordinary paragraphs.
|
|
88
95
|
- Complex raw HTML inside Markdown may not convert cleanly, and advanced Word features (comments, tracked changes, page layout) aren't produced.
|
|
89
96
|
- Very large documents can be slow, since everything runs in the browser. Files are limited to 5 MB.
|
|
90
97
|
- The site works in current versions of Chrome, Edge, Firefox, and Safari. The end-to-end tests run in Chrome.
|
|
@@ -115,7 +122,7 @@ The converter needs the DOM's `DOMParser` and `XMLSerializer`. Browsers have the
|
|
|
115
122
|
|
|
116
123
|
The package also exports `parseMarkdownToHtml`, `extractTitle`, the `FONT_PRESETS` (see [Optional Font Presets](#optional-font-presets)), and their TypeScript types. `parseMarkdownToHtml` passes raw HTML through unsanitized, so sanitize its output (for example with [DOMPurify](https://github.com/cure53/DOMPurify)) before putting it in a page.
|
|
117
124
|
|
|
118
|
-
On a server, treat Markdown from users as untrusted: the converter downloads each remote image (``) to embed it, so the request comes from your server. Strip or allowlist image URLs first if the server can reach internal addresses.
|
|
125
|
+
On a server, treat Markdown from users as untrusted: the converter downloads each remote image (``) to embed it, so the request comes from your server (up to 100 distinct `http(s)` URLs per document, 10 MB each, 4 at a time). Strip or allowlist image URLs first if the server can reach internal addresses.
|
|
119
126
|
|
|
120
127
|
## Development
|
|
121
128
|
|
package/build/converter.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import './buffer-global.js';
|
|
3
3
|
import HTMLtoDOCX from '@turbodocx/html-to-docx';
|
|
4
4
|
import { prepareHtmlForDocx } from './docx-html.js';
|
|
5
|
+
import { embedImages } from './docx-images.js';
|
|
5
6
|
import { mmToTwips } from './font-presets.js';
|
|
6
7
|
import { parseMarkdownToHtml, extractTitle } from './markdown-parser.js';
|
|
7
8
|
/**
|
|
@@ -9,7 +10,11 @@ import { parseMarkdownToHtml, extractTitle } from './markdown-parser.js';
|
|
|
9
10
|
*/
|
|
10
11
|
export async function convertMarkdownToWord(markdown, options = {}) {
|
|
11
12
|
try {
|
|
12
|
-
|
|
13
|
+
let html = parseMarkdownToHtml(markdown);
|
|
14
|
+
if (html.includes('<img')) {
|
|
15
|
+
// Before generation, so a failed image can keep its alt text.
|
|
16
|
+
html = await embedImages(html);
|
|
17
|
+
}
|
|
13
18
|
const documentOptions = {
|
|
14
19
|
// The generator's default border size is 0, so tables had no grid lines.
|
|
15
20
|
// A thin light gray rule (size in eighths of a point) matches how
|
|
@@ -46,7 +51,9 @@ export async function convertMarkdownToWord(markdown, options = {}) {
|
|
|
46
51
|
// HTMLtoDOCX returns Blob in browser, Buffer/ArrayBuffer in Node.js
|
|
47
52
|
const generated = result instanceof Blob ? result : new Blob([result]);
|
|
48
53
|
// The patches rewrite the .docx zip with JSZip. html-to-docx bundles its own
|
|
49
|
-
// copy, so ours is a second one
|
|
54
|
+
// copy, so ours is a second one, in the patch chunks. The structure patch
|
|
55
|
+
// runs on every document, so it always loads; the others only when they
|
|
56
|
+
// apply.
|
|
50
57
|
// Code blocks are broken in the generator output itself, so they are fixed
|
|
51
58
|
// whether or not a font preset is requested.
|
|
52
59
|
let wordDocument = generated;
|
|
@@ -57,13 +64,13 @@ export async function convertMarkdownToWord(markdown, options = {}) {
|
|
|
57
64
|
return formatCodeBlocks(document, codeBlocks);
|
|
58
65
|
});
|
|
59
66
|
}
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
}
|
|
67
|
+
// Every document: the generator writes <w:sectPr> first in the body, and
|
|
68
|
+
// the schema wants it last.
|
|
69
|
+
const structure = documentStructure(html);
|
|
70
|
+
wordDocument = await patchOrKeep(wordDocument, 'structure', async (document) => {
|
|
71
|
+
const { patchStructure } = await import('./docx-structure.js');
|
|
72
|
+
return patchStructure(document, structure);
|
|
73
|
+
});
|
|
67
74
|
const { fontPreset } = options;
|
|
68
75
|
if (fontPreset) {
|
|
69
76
|
wordDocument = await patchOrKeep(wordDocument, 'font preset', async (document) => {
|
|
@@ -85,12 +92,16 @@ function codeBlockTexts(html) {
|
|
|
85
92
|
}
|
|
86
93
|
/** The rules and table header rows in `html`, for the structure patch. */
|
|
87
94
|
function documentStructure(html) {
|
|
95
|
+
if (!html.includes('<hr') && !html.includes('<table')) {
|
|
96
|
+
return { rules: 0, headerRows: [] };
|
|
97
|
+
}
|
|
88
98
|
const dom = new DOMParser().parseFromString(html, 'text/html');
|
|
89
99
|
return {
|
|
90
100
|
rules: dom.querySelectorAll('hr').length,
|
|
91
101
|
headerRows: Array.from(dom.querySelectorAll('table'), (table) => {
|
|
92
102
|
const firstRow = table.querySelector('tr');
|
|
93
|
-
return Boolean(table.tHead) ||
|
|
103
|
+
return (Boolean(table.tHead) ||
|
|
104
|
+
Boolean(firstRow && firstRow.querySelector('td') === null));
|
|
94
105
|
}),
|
|
95
106
|
};
|
|
96
107
|
}
|
package/build/converter.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"converter.js","sourceRoot":"","sources":["../src/converter.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,OAAO,oBAAoB,CAAC;AAC5B,OAAO,UAAU,MAAM,yBAAyB,CAAC;AACjD,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAEpD,OAAO,EAAE,SAAS,EAAmB,MAAM,mBAAmB,CAAC;AAC/D,OAAO,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAiBzE;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,qBAAqB,CACzC,QAAgB,EAChB,UAA6B,EAAE;IAE/B,IAAI,CAAC;QACH,MAAM,IAAI,GAAG,mBAAmB,CAAC,QAAQ,CAAC,CAAC;QAE3C,MAAM,eAAe,GAA+B;YAClD,yEAAyE;YACzE,kEAAkE;YAClE,uBAAuB;YACvB,KAAK,EAAE,EAAE,aAAa,EAAE,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,QAAQ,EAAE,EAAE;SACzE,CAAC;QAEF,MAAM,KAAK,GAAG,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AkB,EAClB,IAAY,EACZ,KAA4C;IAE5C,IAAI,CAAC;QACH,OAAO,MAAM,KAAK,CAAC,YAAY,CAAC,CAAC;IACnC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CAAC,eAAe,IAAI,yCAAyC,EAAE,KAAK,CAAC,CAAC;QAClF,OAAO,YAAY,CAAC;IACtB,CAAC;AACH,CAAC","sourcesContent":["// Must come first: it sets the global Buffer html-to-docx needs for images.\nimport './buffer-global.js';\nimport HTMLtoDOCX from '@turbodocx/html-to-docx';\nimport { prepareHtmlForDocx } from './docx-html.js';\nimport type { DocumentStructure } from './docx-structure.js';\nimport { mmToTwips, type FontPreset } from './font-presets.js';\nimport { parseMarkdownToHtml, extractTitle } from './markdown-parser.js';\n\nexport interface ConversionOptions {\n /** Page margins in inches. Overrides the margins of `fontPreset.page`. */\n pageMargins?: {\n top: number;\n right: number;\n bottom: number;\n left: number;\n };\n /**\n * Rewrites the document fonts, and the page layout if the preset has one.\n * Omit to keep the default styling.\n */\n fontPreset?: FontPreset;\n}\n\n/**\n * Convert markdown text to a Word document blob using HTML as an intermediary format\n */\nexport async function convertMarkdownToWord(\n markdown: string,\n options: ConversionOptions = {}\n): Promise<Blob> {\n try {\n const html = parseMarkdownToHtml(markdown);\n\n const documentOptions: HTMLtoDOCX.DocumentOptions = {\n // The generator's default border size is 0, so tables had no grid lines.\n // A thin light gray rule (size in eighths of a point) matches how\n // GitHub draws tables.\n table: { borderOptions: { size: 4, stroke: 'single', color: 'BFBFBF' } },\n };\n\n const title = extractTitle(markdown);\n if (title) {\n documentOptions.title = title;\n }\n\n const page = options.fontPreset?.page;\n if (page) {\n documentOptions.pageSize = {\n width: mmToTwips(page.widthMm),\n height: mmToTwips(page.heightMm),\n };\n documentOptions.margins = {\n top: mmToTwips(page.marginsMm.top),\n right: mmToTwips(page.marginsMm.right),\n bottom: mmToTwips(page.marginsMm.bottom),\n left: mmToTwips(page.marginsMm.left),\n };\n }\n\n if (options.pageMargins) {\n // Convert inches to twips (1 inch = 1440 twips)\n documentOptions.margins = {\n top: options.pageMargins.top * 1440,\n right: options.pageMargins.right * 1440,\n bottom: options.pageMargins.bottom * 1440,\n left: options.pageMargins.left * 1440,\n };\n }\n\n const result = await HTMLtoDOCX(prepareHtmlForDocx(html), null, documentOptions);\n\n // HTMLtoDOCX returns Blob in browser, Buffer/ArrayBuffer in Node.js\n const generated =\n result instanceof Blob ? result : new Blob([result as BlobPart]);\n\n // The patches rewrite the .docx zip with JSZip. html-to-docx bundles its own\n // copy, so ours is a second one; load it only when a patch actually applies.\n\n // Code blocks are broken in the generator output itself, so they are fixed\n // whether or not a font preset is requested.\n let wordDocument = generated;\n if (html.includes('<pre')) {\n const codeBlocks = codeBlockTexts(html);\n wordDocument = await patchOrKeep(wordDocument, 'code block', async (document) => {\n const { formatCodeBlocks } = await import('./docx-code-blocks.js');\n return formatCodeBlocks(document, codeBlocks);\n });\n }\n\n if (html.includes('<hr') || html.includes('<table')) {\n const structure = documentStructure(html);\n wordDocument = await patchOrKeep(wordDocument, 'structure', async (document) => {\n const { patchStructure } = await import('./docx-structure.js');\n return patchStructure(document, structure);\n });\n }\n\n const { fontPreset } = options;\n if (fontPreset) {\n wordDocument = await patchOrKeep(wordDocument, 'font preset', async (document) => {\n const { applyFontPreset } = await import('./docx-font-preset.js');\n return applyFontPreset(document, fontPreset);\n });\n }\n\n return wordDocument;\n } catch (error) {\n console.error('Word document generation error:', error);\n throw new Error('Failed to generate Word document', { cause: error });\n }\n}\n\n/** The text of each `<pre>` in `html`, in document order. */\nfunction codeBlockTexts(html: string): string[] {\n const dom = new DOMParser().parseFromString(html, 'text/html');\n return Array.from(dom.querySelectorAll('pre'), (pre) => pre.textContent ?? '');\n}\n\n/** The rules and table header rows in `html`, for the structure patch. */\nfunction documentStructure(html: string): DocumentStructure {\n const dom = new DOMParser().parseFromString(html, 'text/html');\n return {\n rules: dom.querySelectorAll('hr').length,\n headerRows: Array.from(dom.querySelectorAll('table'), (table) => {\n const firstRow = table.querySelector('tr');\n return Boolean(table.tHead) || Boolean(firstRow && firstRow.querySelector('td') === null);\n }),\n };\n}\n\n/**\n * The patches polish a document html-to-docx already produced, so a failure in\n * one (including its chunk failing to load) keeps the unpatched document\n * rather than failing the whole conversion.\n */\nasync function patchOrKeep(\n wordDocument: Blob,\n name: string,\n patch: (wordDocument: Blob) => Promise<Blob>\n): Promise<Blob> {\n try {\n return await patch(wordDocument);\n } catch (error) {\n console.warn(`Skipped the ${name} patch; keeping the unpatched document:`, error);\n return wordDocument;\n }\n}"]}
|
|
1
|
+
{"version":3,"file":"converter.js","sourceRoot":"","sources":["../src/converter.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,OAAO,oBAAoB,CAAC;AAC5B,OAAO,UAAU,MAAM,yBAAyB,CAAC;AACjD,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACpD,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAE/C,OAAO,EAAE,SAAS,EAAmB,MAAM,mBAAmB,CAAC;AAC/D,OAAO,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAiBzE;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,qBAAqB,CACzC,QAAgB,EAChB,UAA6B,EAAE;IAE/B,IAAI,CAAC;QACH,IAAI,IAAI,GAAG,mBAAmB,CAAC,QAAQ,CAAC,CAAC;QACzC,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;YAC1B,8DAA8D;YAC9D,IAAI,GAAG,MAAM,WAAW,CAAC,IAAI,CAAC,CAAC;QACjC,CAAC;QAED,MAAM,eAAe,GAA+B;YAClD,yEAAyE;YACzE,kEAAkE;YAClE,uBAAuB;YACvB,KAAK,EAAE,EAAE,aAAa,EAAE,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,QAAQ,EAAE,EAA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BACpB,OAAO,CAAC,QAAQ,IAAI,QAAQ,CAAC,aAAa,CAAC,IAAI,CAAC,KAAK,IAAI,CAAC,CAC3D,CAAC;QACJ,CAAC,CAAC;KACH,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,KAAK,UAAU,WAAW,CACxB,YAAkB,EAClB,IAAY,EACZ,KAA4C;IAE5C,IAAI,CAAC;QACH,OAAO,MAAM,KAAK,CAAC,YAAY,CAAC,CAAC;IACnC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CACV,eAAe,IAAI,yCAAyC,EAC5D,KAAK,CACN,CAAC;QACF,OAAO,YAAY,CAAC;IACtB,CAAC;AACH,CAAC","sourcesContent":["// Must come first: it sets the global Buffer html-to-docx needs for images.\nimport './buffer-global.js';\nimport HTMLtoDOCX from '@turbodocx/html-to-docx';\nimport { prepareHtmlForDocx } from './docx-html.js';\nimport { embedImages } from './docx-images.js';\nimport type { DocumentStructure } from './docx-structure.js';\nimport { mmToTwips, type FontPreset } from './font-presets.js';\nimport { parseMarkdownToHtml, extractTitle } from './markdown-parser.js';\n\nexport interface ConversionOptions {\n /** Page margins in inches. Overrides the margins of `fontPreset.page`. */\n pageMargins?: {\n top: number;\n right: number;\n bottom: number;\n left: number;\n };\n /**\n * Rewrites the document fonts, and the page layout if the preset has one.\n * Omit to keep the default styling.\n */\n fontPreset?: FontPreset;\n}\n\n/**\n * Convert markdown text to a Word document blob using HTML as an intermediary format\n */\nexport async function convertMarkdownToWord(\n markdown: string,\n options: ConversionOptions = {}\n): Promise<Blob> {\n try {\n let html = parseMarkdownToHtml(markdown);\n if (html.includes('<img')) {\n // Before generation, so a failed image can keep its alt text.\n html = await embedImages(html);\n }\n\n const documentOptions: HTMLtoDOCX.DocumentOptions = {\n // The generator's default border size is 0, so tables had no grid lines.\n // A thin light gray rule (size in eighths of a point) matches how\n // GitHub draws tables.\n table: { borderOptions: { size: 4, stroke: 'single', color: 'BFBFBF' } },\n };\n\n const title = extractTitle(markdown);\n if (title) {\n documentOptions.title = title;\n }\n\n const page = options.fontPreset?.page;\n if (page) {\n documentOptions.pageSize = {\n width: mmToTwips(page.widthMm),\n height: mmToTwips(page.heightMm),\n };\n documentOptions.margins = {\n top: mmToTwips(page.marginsMm.top),\n right: mmToTwips(page.marginsMm.right),\n bottom: mmToTwips(page.marginsMm.bottom),\n left: mmToTwips(page.marginsMm.left),\n };\n }\n\n if (options.pageMargins) {\n // Convert inches to twips (1 inch = 1440 twips)\n documentOptions.margins = {\n top: options.pageMargins.top * 1440,\n right: options.pageMargins.right * 1440,\n bottom: options.pageMargins.bottom * 1440,\n left: options.pageMargins.left * 1440,\n };\n }\n\n const result = await HTMLtoDOCX(\n prepareHtmlForDocx(html),\n null,\n documentOptions\n );\n\n // HTMLtoDOCX returns Blob in browser, Buffer/ArrayBuffer in Node.js\n const generated =\n result instanceof Blob ? result : new Blob([result as BlobPart]);\n\n // The patches rewrite the .docx zip with JSZip. html-to-docx bundles its own\n // copy, so ours is a second one, in the patch chunks. The structure patch\n // runs on every document, so it always loads; the others only when they\n // apply.\n\n // Code blocks are broken in the generator output itself, so they are fixed\n // whether or not a font preset is requested.\n let wordDocument = generated;\n if (html.includes('<pre')) {\n const codeBlocks = codeBlockTexts(html);\n wordDocument = await patchOrKeep(\n wordDocument,\n 'code block',\n async (document) => {\n const { formatCodeBlocks } = await import('./docx-code-blocks.js');\n return formatCodeBlocks(document, codeBlocks);\n }\n );\n }\n\n // Every document: the generator writes <w:sectPr> first in the body, and\n // the schema wants it last.\n const structure = documentStructure(html);\n wordDocument = await patchOrKeep(\n wordDocument,\n 'structure',\n async (document) => {\n const { patchStructure } = await import('./docx-structure.js');\n return patchStructure(document, structure);\n }\n );\n\n const { fontPreset } = options;\n if (fontPreset) {\n wordDocument = await patchOrKeep(\n wordDocument,\n 'font preset',\n async (document) => {\n const { applyFontPreset } = await import('./docx-font-preset.js');\n return applyFontPreset(document, fontPreset);\n }\n );\n }\n\n return wordDocument;\n } catch (error) {\n console.error('Word document generation error:', error);\n throw new Error('Failed to generate Word document', { cause: error });\n }\n}\n\n/** The text of each `<pre>` in `html`, in document order. */\nfunction codeBlockTexts(html: string): string[] {\n const dom = new DOMParser().parseFromString(html, 'text/html');\n return Array.from(\n dom.querySelectorAll('pre'),\n (pre) => pre.textContent ?? ''\n );\n}\n\n/** The rules and table header rows in `html`, for the structure patch. */\nfunction documentStructure(html: string): DocumentStructure {\n if (!html.includes('<hr') && !html.includes('<table')) {\n return { rules: 0, headerRows: [] };\n }\n const dom = new DOMParser().parseFromString(html, 'text/html');\n return {\n rules: dom.querySelectorAll('hr').length,\n headerRows: Array.from(dom.querySelectorAll('table'), (table) => {\n const firstRow = table.querySelector('tr');\n return (\n Boolean(table.tHead) ||\n Boolean(firstRow && firstRow.querySelector('td') === null)\n );\n }),\n };\n}\n\n/**\n * The patches polish a document html-to-docx already produced, so a failure in\n * one (including its chunk failing to load) keeps the unpatched document\n * rather than failing the whole conversion.\n */\nasync function patchOrKeep(\n wordDocument: Blob,\n name: string,\n patch: (wordDocument: Blob) => Promise<Blob>\n): Promise<Blob> {\n try {\n return await patch(wordDocument);\n } catch (error) {\n console.warn(\n `Skipped the ${name} patch; keeping the unpatched document:`,\n error\n );\n return wordDocument;\n }\n}\n"]}
|
|
@@ -3,7 +3,12 @@ import { CODE_FONT } from './docx-html.js';
|
|
|
3
3
|
import { keepXmlDeclaration, paragraphProperty, WORDPROCESSING_NS as W_NS, XML_NS, } from './xml-part.js';
|
|
4
4
|
export { CODE_FONT };
|
|
5
5
|
/** Theme slots WinWord prefers over explicitly named fonts. */
|
|
6
|
-
const THEME_FONT_ATTRIBUTES = [
|
|
6
|
+
const THEME_FONT_ATTRIBUTES = [
|
|
7
|
+
'asciiTheme',
|
|
8
|
+
'eastAsiaTheme',
|
|
9
|
+
'hAnsiTheme',
|
|
10
|
+
'cstheme',
|
|
11
|
+
];
|
|
7
12
|
/**
|
|
8
13
|
* Makes code blocks survive in Word, regardless of the font preset:
|
|
9
14
|
*
|
|
@@ -54,7 +59,8 @@ export function formatDocumentXml(documentXml, codeBlocks) {
|
|
|
54
59
|
if (pending.length === 0) {
|
|
55
60
|
break;
|
|
56
61
|
}
|
|
57
|
-
if (compact(paragraphText(paragraph)) === pending[0] &&
|
|
62
|
+
if (compact(paragraphText(paragraph)) === pending[0] &&
|
|
63
|
+
hasExplicitFonts(paragraph)) {
|
|
58
64
|
pending.shift();
|
|
59
65
|
setCodeFont(paragraph);
|
|
60
66
|
changed = true;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"docx-code-blocks.js","sourceRoot":"","sources":["../src/docx-code-blocks.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EACL,kBAAkB,EAClB,iBAAiB,EACjB,iBAAiB,IAAI,IAAI,EACzB,MAAM,GACP,MAAM,eAAe,CAAC;AAEvB,OAAO,EAAE,SAAS,EAAE,CAAC;AAErB,+DAA+D;AAC/D,MAAM,qBAAqB,GAAG,CAAC,YAAY,EAAE,eAAe,EAAE,YAAY,EAAE,SAAS,CAAC,CAAC;AAEvF;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,CAAC,KAAK,UAAU,gBAAgB,CAAC,YAAkB,EAAE,UAAoB;IAC7E,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC,SAAS,CAAC,MAAM,YAAY,CAAC,WAAW,EAAE,CAAC,CAAC;IACpE,MAAM,aAAa,GAAG,GAAG,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC;IACpD,IAAI,CAAC,aAAa,EAAE,CAAC;QACnB,MAAM,IAAI,KAAK,CAAC,mEAAmE,CAAC,CAAC;IACvF,CAAC;IAED,MAAM,WAAW,GAAG,MAAM,aAAa,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IACxD,MAAM,SAAS,GAAG,iBAAiB,CA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AW,GAAG,QAAQ,CAAC,eAAe,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;YAC1D,WAAW,CAAC,cAAc,CAAC,MAAM,EAAE,WAAW,EAAE,UAAU,CAAC,CAAC;YAC5D,WAAW,CAAC,WAAW,GAAG,IAAI,CAAC;YAC/B,GAAG,CAAC,YAAY,CAAC,WAAW,EAAE,IAAI,CAAC,CAAC;QACtC,CAAC;IACH,CAAC;IAED,GAAG,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;IACtB,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import JSZip from 'jszip';\nimport { CODE_FONT } from './docx-html.js';\nimport {\n keepXmlDeclaration,\n paragraphProperty,\n WORDPROCESSING_NS as W_NS,\n XML_NS,\n} from './xml-part.js';\n\nexport { CODE_FONT };\n\n/** Theme slots WinWord prefers over explicitly named fonts. */\nconst THEME_FONT_ATTRIBUTES = ['asciiTheme', 'eastAsiaTheme', 'hAnsiTheme', 'cstheme'];\n\n/**\n * Makes code blocks survive in Word, regardless of the font preset:\n *\n * - Line breaks: the generator keeps the source newlines of a `<pre>` as bare\n * `LF` inside `<w:t>`, which WinWord renders as whitespace; they become\n * `<w:br/>` here. Everywhere else the generator emits `<w:br/>` itself, so a\n * bare `LF` is the bug's own signature and needs no other marker.\n * - Typeface: the generator sets only `w:ascii`/`w:hAnsi`, so Chinese comments\n * fell through to the body font. Code paragraphs are found by their text,\n * matched in order against `codeBlocks`, and get the monospace face in all\n * three slots. Keying on the generator's hardcoded code font instead would\n * also catch any inline `font-family` that names the same font.\n * - Indent: the same paragraphs get an explicit zero first-line indent, so a\n * preset that indents body text (the 公文 one) leaves the first code line\n * aligned with the rest.\n *\n * @param codeBlocks The text content of each `<pre>` in the source HTML, in\n * document order.\n */\nexport async function formatCodeBlocks(wordDocument: Blob, codeBlocks: string[]): Promise<Blob> {\n const zip = await JSZip.loadAsync(await wordDocument.arrayBuffer());\n const documentEntry = zip.file('word/document.xml');\n if (!documentEntry) {\n throw new Error('Cannot format code blocks: document contains no word/document.xml');\n }\n\n const documentXml = await documentEntry.async('string');\n const formatted = formatDocumentXml(documentXml, codeBlocks);\n if (formatted === documentXml) {\n return wordDocument;\n }\n\n zip.file('word/document.xml', formatted);\n const patched = await zip.generateAsync({ type: 'arraybuffer' });\n return new Blob([patched], { type: wordDocument.type });\n}\n\n/** Exported for testing. */\nexport function formatDocumentXml(documentXml: string, codeBlocks: string[]): string {\n const dom = new DOMParser().parseFromString(documentXml, 'application/xml');\n let changed = false;\n\n // The generator emits one paragraph per <pre>, in source order, so a single\n // forward pass pairs each code block with the next paragraph of equal text.\n // Whitespace is ignored because the generator may trim or collapse it. A\n // plain paragraph can repeat a code block's text, so a match also needs every\n // run to name a font, as the generator does for <pre> but not for body text.\n // Inline code names CODE_FONT itself (see prepareHtmlForDocx), which the\n // generator never uses for <pre>, so those runs don't count.\n const pending = codeBlocks.map(compact).filter((text) => text !== '');\n for (const paragraph of Array.from(dom.getElementsByTagNameNS(W_NS, 'p'))) {\n if (pending.length === 0) {\n break;\n }\n if (compact(paragraphText(paragraph)) === pending[0] && hasExplicitFonts(paragraph)) {\n pending.shift();\n setCodeFont(paragraph);\n changed = true;\n }\n }\n\n for (const text of Array.from(dom.getElementsByTagNameNS(W_NS, 't'))) {\n changed = expandLineBreaks(text) || changed;\n }\n\n if (!changed) {\n return documentXml;\n }\n return keepXmlDeclaration(documentXml, new XMLSerializer().serializeToString(dom));\n}\n\nfunction compact(text: string): string {\n return text.replace(/\\s+/g, '');\n}\n\nfunction paragraphText(paragraph: Element): string {\n return Array.from(paragraph.getElementsByTagNameNS(W_NS, 't'))\n .map((text) => text.textContent ?? '')\n .join('');\n}\n\nfunction hasExplicitFonts(paragraph: Element): boolean {\n return textRuns(paragraph).every((run) => {\n const rFonts = firstChild(run, 'rPr')?.getElementsByTagNameNS(W_NS, 'rFonts')[0];\n const font = rFonts?.getAttributeNS(W_NS, 'ascii');\n return Boolean(font) && font !== CODE_FONT;\n });\n}\n\nfunction textRuns(paragraph: Element): Element[] {\n return Array.from(paragraph.getElementsByTagNameNS(W_NS, 'r')).filter(\n (run) => run.getElementsByTagNameNS(W_NS, 't').length > 0\n );\n}\n\nfunction setCodeFont(paragraph: Element): void {\n const document = paragraph.ownerDocument;\n\n let pPr = firstChild(paragraph, 'pPr');\n if (!pPr) {\n pPr = paragraph.insertBefore(document.createElementNS(W_NS, 'w:pPr'), paragraph.firstChild);\n }\n paragraphProperty(pPr, 'ind').setAttributeNS(W_NS, 'w:firstLine', '0');\n\n for (const run of textRuns(paragraph)) {\n let rPr = firstChild(run, 'rPr');\n if (!rPr) {\n rPr = run.insertBefore(document.createElementNS(W_NS, 'w:rPr'), run.firstChild);\n }\n\n // <w:rFonts> comes first in <w:rPr>.\n let rFonts = firstChild(rPr, 'rFonts');\n if (!rFonts) {\n rFonts = rPr.insertBefore(document.createElementNS(W_NS, 'w:rFonts'), rPr.firstChild);\n }\n\n for (const attribute of THEME_FONT_ATTRIBUTES) {\n rFonts.removeAttributeNS(W_NS, attribute);\n }\n for (const attribute of ['ascii', 'hAnsi', 'eastAsia'] as const) {\n rFonts.setAttributeNS(W_NS, `w:${attribute}`, CODE_FONT);\n }\n }\n}\n\nfunction firstChild(parent: Element, localName: string): Element | undefined {\n return Array.from(parent.children).find(\n (child) => child.namespaceURI === W_NS && child.localName === localName\n );\n}\n\n/**\n * Replaces one `<w:t>a\\nb</w:t>` with `<w:t>a</w:t><w:br/><w:t>b</w:t>`.\n * Returns whether anything changed.\n */\nfunction expandLineBreaks(text: Element): boolean {\n const lines = (text.textContent ?? '').split('\\n');\n if (lines.length < 2) {\n return false;\n }\n\n const document = text.ownerDocument;\n const run = text.parentNode as Element;\n\n for (const [index, line] of lines.entries()) {\n if (index > 0) {\n run.insertBefore(document.createElementNS(W_NS, 'w:br'), text);\n }\n if (line !== '') {\n const textElement = document.createElementNS(W_NS, 'w:t');\n textElement.setAttributeNS(XML_NS, 'xml:space', 'preserve');\n textElement.textContent = line;\n run.insertBefore(textElement, text);\n }\n }\n\n run.removeChild(text);\n return true;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"docx-code-blocks.js","sourceRoot":"","sources":["../src/docx-code-blocks.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EACL,kBAAkB,EAClB,iBAAiB,EACjB,iBAAiB,IAAI,IAAI,EACzB,MAAM,GACP,MAAM,eAAe,CAAC;AAEvB,OAAO,EAAE,SAAS,EAAE,CAAC;AAErB,+DAA+D;AAC/D,MAAM,qBAAqB,GAAG;IAC5B,YAAY;IACZ,eAAe;IACf,YAAY;IACZ,SAAS;CACV,CAAC;AAEF;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,CAAC,KAAK,UAAU,gBAAgB,CACpC,YAAkB,EAClB,UAAoB;IAEpB,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC,SAAS,CAAC,MAAM,YAAY,CAAC,WAAW,EAAE,CAAC,CAAC;IACpE,MAAM,aAAa,GAAG,GAAG,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC;IACpD,IAAI,CAAC,aAAa,EAAE,CAAC;QACnB,MAAM,IAAI,KAAK,CACb,mEAAmE,CACpE,CAAC;IACJ,CAAC;IAED,MAAM,WAAW,GAAG,MAAM,aAAa,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IACxD,MAAM,SAAS,GAAG,iBAAiB,CAAC,WAAW,EAAE,UAAU,CAAC,CAAC;IAC7D,IAAI,SAAS,KAAK,WAAW,EAAE,CAAC;QAC9B,OAAO,YAAY,CAAC;IACtB,CAAC;IAED,GAAG,CAAC,IAAI,CAAC,mBAAmB,EAAE,SAAS,CAAC,CAAC;IACzC,MAAM,OAAO,GAAG,MAAM,GAAG,CAAC,aAAa,CAAC,EAAE,IAAI,EAAE,aAAa,EAAE,CAAC,CAAC;IACjE,OAAO,IAAI,IAAI,C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I,CAAC,CAAC;IACtB,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import JSZip from 'jszip';\nimport { CODE_FONT } from './docx-html.js';\nimport {\n keepXmlDeclaration,\n paragraphProperty,\n WORDPROCESSING_NS as W_NS,\n XML_NS,\n} from './xml-part.js';\n\nexport { CODE_FONT };\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 * Makes code blocks survive in Word, regardless of the font preset:\n *\n * - Line breaks: the generator keeps the source newlines of a `<pre>` as bare\n * `LF` inside `<w:t>`, which WinWord renders as whitespace; they become\n * `<w:br/>` here. Everywhere else the generator emits `<w:br/>` itself, so a\n * bare `LF` is the bug's own signature and needs no other marker.\n * - Typeface: the generator sets only `w:ascii`/`w:hAnsi`, so Chinese comments\n * fell through to the body font. Code paragraphs are found by their text,\n * matched in order against `codeBlocks`, and get the monospace face in all\n * three slots. Keying on the generator's hardcoded code font instead would\n * also catch any inline `font-family` that names the same font.\n * - Indent: the same paragraphs get an explicit zero first-line indent, so a\n * preset that indents body text (the 公文 one) leaves the first code line\n * aligned with the rest.\n *\n * @param codeBlocks The text content of each `<pre>` in the source HTML, in\n * document order.\n */\nexport async function formatCodeBlocks(\n wordDocument: Blob,\n codeBlocks: string[]\n): Promise<Blob> {\n const zip = await JSZip.loadAsync(await wordDocument.arrayBuffer());\n const documentEntry = zip.file('word/document.xml');\n if (!documentEntry) {\n throw new Error(\n 'Cannot format code blocks: document contains no word/document.xml'\n );\n }\n\n const documentXml = await documentEntry.async('string');\n const formatted = formatDocumentXml(documentXml, codeBlocks);\n if (formatted === documentXml) {\n return wordDocument;\n }\n\n zip.file('word/document.xml', formatted);\n const patched = await zip.generateAsync({ type: 'arraybuffer' });\n return new Blob([patched], { type: wordDocument.type });\n}\n\n/** Exported for testing. */\nexport function formatDocumentXml(\n documentXml: string,\n codeBlocks: string[]\n): string {\n const dom = new DOMParser().parseFromString(documentXml, 'application/xml');\n let changed = false;\n\n // The generator emits one paragraph per <pre>, in source order, so a single\n // forward pass pairs each code block with the next paragraph of equal text.\n // Whitespace is ignored because the generator may trim or collapse it. A\n // plain paragraph can repeat a code block's text, so a match also needs every\n // run to name a font, as the generator does for <pre> but not for body text.\n // Inline code names CODE_FONT itself (see prepareHtmlForDocx), which the\n // generator never uses for <pre>, so those runs don't count.\n const pending = codeBlocks.map(compact).filter((text) => text !== '');\n for (const paragraph of Array.from(dom.getElementsByTagNameNS(W_NS, 'p'))) {\n if (pending.length === 0) {\n break;\n }\n if (\n compact(paragraphText(paragraph)) === pending[0] &&\n hasExplicitFonts(paragraph)\n ) {\n pending.shift();\n setCodeFont(paragraph);\n changed = true;\n }\n }\n\n for (const text of Array.from(dom.getElementsByTagNameNS(W_NS, 't'))) {\n changed = expandLineBreaks(text) || changed;\n }\n\n if (!changed) {\n return documentXml;\n }\n return keepXmlDeclaration(\n documentXml,\n new XMLSerializer().serializeToString(dom)\n );\n}\n\nfunction compact(text: string): string {\n return text.replace(/\\s+/g, '');\n}\n\nfunction paragraphText(paragraph: Element): string {\n return Array.from(paragraph.getElementsByTagNameNS(W_NS, 't'))\n .map((text) => text.textContent ?? '')\n .join('');\n}\n\nfunction hasExplicitFonts(paragraph: Element): boolean {\n return textRuns(paragraph).every((run) => {\n const rFonts = firstChild(run, 'rPr')?.getElementsByTagNameNS(\n W_NS,\n 'rFonts'\n )[0];\n const font = rFonts?.getAttributeNS(W_NS, 'ascii');\n return Boolean(font) && font !== CODE_FONT;\n });\n}\n\nfunction textRuns(paragraph: Element): Element[] {\n return Array.from(paragraph.getElementsByTagNameNS(W_NS, 'r')).filter(\n (run) => run.getElementsByTagNameNS(W_NS, 't').length > 0\n );\n}\n\nfunction setCodeFont(paragraph: Element): void {\n const document = paragraph.ownerDocument;\n\n let pPr = firstChild(paragraph, 'pPr');\n if (!pPr) {\n pPr = paragraph.insertBefore(\n document.createElementNS(W_NS, 'w:pPr'),\n paragraph.firstChild\n );\n }\n paragraphProperty(pPr, 'ind').setAttributeNS(W_NS, 'w:firstLine', '0');\n\n for (const run of textRuns(paragraph)) {\n let rPr = firstChild(run, 'rPr');\n if (!rPr) {\n rPr = run.insertBefore(\n document.createElementNS(W_NS, 'w:rPr'),\n run.firstChild\n );\n }\n\n // <w:rFonts> comes first in <w:rPr>.\n let rFonts = firstChild(rPr, 'rFonts');\n if (!rFonts) {\n rFonts = rPr.insertBefore(\n document.createElementNS(W_NS, 'w:rFonts'),\n rPr.firstChild\n );\n }\n\n for (const attribute of THEME_FONT_ATTRIBUTES) {\n rFonts.removeAttributeNS(W_NS, attribute);\n }\n for (const attribute of ['ascii', 'hAnsi', 'eastAsia'] as const) {\n rFonts.setAttributeNS(W_NS, `w:${attribute}`, CODE_FONT);\n }\n }\n}\n\nfunction firstChild(parent: Element, localName: string): Element | undefined {\n return Array.from(parent.children).find(\n (child) => child.namespaceURI === W_NS && child.localName === localName\n );\n}\n\n/**\n * Replaces one `<w:t>a\\nb</w:t>` with `<w:t>a</w:t><w:br/><w:t>b</w:t>`.\n * Returns whether anything changed.\n */\nfunction expandLineBreaks(text: Element): boolean {\n const lines = (text.textContent ?? '').split('\\n');\n if (lines.length < 2) {\n return false;\n }\n\n const document = text.ownerDocument;\n const run = text.parentNode as Element;\n\n for (const [index, line] of lines.entries()) {\n if (index > 0) {\n run.insertBefore(document.createElementNS(W_NS, 'w:br'), text);\n }\n if (line !== '') {\n const textElement = document.createElementNS(W_NS, 'w:t');\n textElement.setAttributeNS(XML_NS, 'xml:space', 'preserve');\n textElement.textContent = line;\n run.insertBefore(textElement, text);\n }\n }\n\n run.removeChild(text);\n return true;\n}\n"]}
|
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
import JSZip from 'jszip';
|
|
2
|
-
import { keepXmlDeclaration, paragraphProperty, 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.
|
|
@@ -139,7 +144,7 @@ export function patchDocumentXml(documentXml, preset) {
|
|
|
139
144
|
* itself sets up with GB/T 9704 margins, this reproduces its linePitch="579"
|
|
140
145
|
* and charSpace="-834".
|
|
141
146
|
*/
|
|
142
|
-
function measureGrid(sectPr, { linesPerPage, charsPerLine }, bodySizePt) {
|
|
147
|
+
function measureGrid(sectPr, { linesPerPage, charsPerLine, }, bodySizePt) {
|
|
143
148
|
const pgSz = children(sectPr).find((child) => child.localName === 'pgSz');
|
|
144
149
|
const pgMar = children(sectPr).find((child) => child.localName === 'pgMar');
|
|
145
150
|
const twips = (element, attribute) => {
|
|
@@ -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,EAAE,iBAAiB,IAAI,IAAI,EAAE,MAAM,eAAe,CAAC;AAEjG,+DAA+D;AAC/D,MAAM,qBAAqB,GAAG,CAAC,YAAY,EAAE,eAAe,EAAE,YAAY,EAAE,SAAS,CAAC,CAAC;AAEvF;;;GAGG;AACH,MAAM,cAAc,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;AAiBrD;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,KA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AAC,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, ParagraphStyle } from './font-presets.js';\nimport { keepXmlDeclaration, paragraphProperty, 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 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(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 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('Cannot apply font preset: document contains no word/document.xml');\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(paragraphPropertiesOf(docDefaults), 'widowControl').setAttributeNS(\n W_NS,\n 'w:val',\n '0'\n );\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(style.getAttributeNS(W_NS, 'styleId') ?? '');\n if (heading) {\n applyLevelStyle(style, preset.headings[Number(heading[1]) - 1], preset.paragraph, layout);\n }\n }\n\n return keepXmlDeclaration(stylesXml, new XMLSerializer().serializeToString(dom));\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(\"Cannot apply font preset: lineSpacing 'grid' needs page.grid\");\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(dom.getElementsByTagNameNS(W_NS, 'sectPr'))) {\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 = 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(documentXml, new XMLSerializer().serializeToString(dom)),\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 { linesPerPage, charsPerLine }: { 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(`Cannot apply font preset: section has no page ${attribute}`);\n }\n return value;\n };\n\n const textHeight = twips(pgSz, 'h') - twips(pgMar, 'top') - twips(pgMar, 'bottom');\n const textWidth = 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((child) => child.localName === 'printerSettings');\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(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 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((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,MAA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K,SAAS,EAAE,CAAC,CAAC;IAC7E,OAAO,QAAQ,KAAK,OAAO;QACzB,CAAC,CAAC,MAAM,CAAC,YAAY,CAAC,OAAO,EAAE,MAAM,CAAC,UAAU,CAAC;QACjD,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;AAClC,CAAC;AAED,SAAS,cAAc,CAAC,GAAa,EAAE,SAAiB;IACtD,MAAM,OAAO,GAAG,GAAG,CAAC,sBAAsB,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/D,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;;;;;;;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K,CAAC;YAC9C,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC;QAChC,CAAC;QACD,IAAI,IAAI,CAAC,SAAS,KAAK,IAAI,IAAI,IAAI,CAAC,WAAW,EAAE,IAAI,EAAE,EAAE,CAAC;YACxD,MAAM,MAAM,GAAG,GAAG,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;YAC3C,MAAM,CAAC,MAAM,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC;YAC9C,IAAI,CAAC,MAAM,CAAC,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":[],"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,qDAAqD;AACrD,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAEhC,4DAA4D;AAC5D,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC;AAE5E;;;;GAIG;AACH,MAAM,cAAc,GAAqD;IACvE,GAAG,EAAE,MAAM;IACX,IAAI,EAAE,MAAM;IACZ,EAAE,EAAE,MAAM;IACV,GAAG,EAAE,IAAI;IACT,IAAI,EAAE,IAAI;IACV,GAAG,EAAE,IAAI;IACT,CAAC,EAAE,OAAO;IACV,IAAI,EAAE,MAAM;IACZ,OAAO,EAAE,MAAM;IACf,GAAG,EAAE,MAAM;IACX,GAAG,EAAE,MAAM;IACX,GAAG,EAAE,MAAM;IACX,IAAI,EAAE,MAAM;IACZ,IAAI,EAAE,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C,KAAK,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;QAChC,CAAC;aAAM,IAAI,gBAAgB,CAAC,GAAG,CAAC,KAAK,CAAC,SAAS,CAAC,EAAE,CAAC;YACjD,MAAM,KAAK,GAAG,kBAAkB,CAAC;YACjC,MAAM,MAAM,GAAG,MAAM;gBACnB,CAAC,CAAC,KAAK;gBACP,CAAC,CAAC,gBAAgB,KAAK,GAAG,mBAAmB,OAAO,KAAK,EAAE,CAAC;YAC9D,MAAM,KAAK,GAAG,KAAK,CAAC,YAAY,CAAC,iBAAiB,CAAC,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>;
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { Buffer } from 'buffer';
|
|
2
|
+
/** html-to-docx's own limit for one image (imageProcessing.maxImageSize). */
|
|
3
|
+
export const MAX_IMAGE_BYTES = 10 * 1024 * 1024;
|
|
4
|
+
/**
|
|
5
|
+
* The most distinct image URLs fetched for one document: html-to-docx keeps
|
|
6
|
+
* at most this many in its image cache (imageProcessing.maxCacheEntries). The
|
|
7
|
+
* rest keep their alt text.
|
|
8
|
+
*/
|
|
9
|
+
export const MAX_IMAGES = 100;
|
|
10
|
+
/**
|
|
11
|
+
* How many downloads run at once. html-to-docx fetched one at a time; a few
|
|
12
|
+
* in parallel is faster without opening a connection per image.
|
|
13
|
+
*/
|
|
14
|
+
export const CONCURRENCY = 4;
|
|
15
|
+
/** Per attempt; the second attempt waits twice as long, as html-to-docx's do. */
|
|
16
|
+
const TIMEOUT_MS = 5000;
|
|
17
|
+
const ATTEMPTS = 2;
|
|
18
|
+
/**
|
|
19
|
+
* The URLs html-to-docx downloads (its `isValidUrl`, without the `g` flag
|
|
20
|
+
* that makes `test()` stateful), anchored so the whole `src` is the URL.
|
|
21
|
+
* Requiring both means this module never fetches what it wouldn't.
|
|
22
|
+
*/
|
|
23
|
+
const GENERATOR_URL = /http(s)?:\/\/(\w+:?\w*@)?(\S+)(:\d+)?((?<=\.)\w+)+(\/([\w#!:.?+=&%@!\-/])*)?/i;
|
|
24
|
+
const WEB_URL = /^https?:\/\//i;
|
|
25
|
+
/** Leading bytes of the image formats Word embeds, for servers that don't say. */
|
|
26
|
+
const SIGNATURES = [
|
|
27
|
+
['image/png', [0x89, 0x50, 0x4e, 0x47]],
|
|
28
|
+
['image/jpeg', [0xff, 0xd8, 0xff]],
|
|
29
|
+
['image/gif', [0x47, 0x49, 0x46, 0x38]],
|
|
30
|
+
['image/bmp', [0x42, 0x4d]],
|
|
31
|
+
];
|
|
32
|
+
/**
|
|
33
|
+
* Downloads each web image in `html` and swaps its `src` for a `data:` URI,
|
|
34
|
+
* which html-to-docx embeds without downloading it again. An image that can't
|
|
35
|
+
* be fetched becomes its alt text, linked to its URL, where html-to-docx would
|
|
36
|
+
* drop it without a trace. Other sources it can't embed either, such as a
|
|
37
|
+
* relative path, keep their alt text too.
|
|
38
|
+
*
|
|
39
|
+
* Each URL is fetched once, however many times it appears: at most
|
|
40
|
+
* MAX_IMAGES of them, CONCURRENCY at a time.
|
|
41
|
+
*/
|
|
42
|
+
export async function embedImages(html) {
|
|
43
|
+
const dom = new DOMParser().parseFromString(html, 'text/html');
|
|
44
|
+
const images = Array.from(dom.querySelectorAll('img'));
|
|
45
|
+
if (images.length === 0)
|
|
46
|
+
return html;
|
|
47
|
+
const urls = new Set();
|
|
48
|
+
for (const image of images) {
|
|
49
|
+
const src = image.getAttribute('src') ?? '';
|
|
50
|
+
if (isFetchable(src) && urls.size < MAX_IMAGES)
|
|
51
|
+
urls.add(src);
|
|
52
|
+
}
|
|
53
|
+
const queue = Array.from(urls);
|
|
54
|
+
const downloads = new Map();
|
|
55
|
+
const worker = async () => {
|
|
56
|
+
for (let url = queue.shift(); url !== undefined; url = queue.shift()) {
|
|
57
|
+
downloads.set(url, await fetchImage(url));
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
await Promise.all(Array.from({ length: Math.min(CONCURRENCY, queue.length) }, worker));
|
|
61
|
+
for (const image of images) {
|
|
62
|
+
const src = image.getAttribute('src') ?? '';
|
|
63
|
+
if (src.startsWith('data:'))
|
|
64
|
+
continue;
|
|
65
|
+
const dataUri = downloads.get(src);
|
|
66
|
+
if (dataUri) {
|
|
67
|
+
image.setAttribute('src', dataUri);
|
|
68
|
+
}
|
|
69
|
+
else {
|
|
70
|
+
replaceWithAltText(image, src);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return dom.body.innerHTML;
|
|
74
|
+
}
|
|
75
|
+
function isFetchable(src) {
|
|
76
|
+
return WEB_URL.test(src) && GENERATOR_URL.test(src);
|
|
77
|
+
}
|
|
78
|
+
/** The image at `url` as a `data:` URI, or null if it can't be fetched. */
|
|
79
|
+
async function fetchImage(url) {
|
|
80
|
+
for (let attempt = 1; attempt <= ATTEMPTS; attempt++) {
|
|
81
|
+
const tooLarge = new AbortController();
|
|
82
|
+
try {
|
|
83
|
+
const response = await fetch(url, {
|
|
84
|
+
signal: AbortSignal.any([
|
|
85
|
+
tooLarge.signal,
|
|
86
|
+
AbortSignal.timeout(TIMEOUT_MS * attempt),
|
|
87
|
+
]),
|
|
88
|
+
});
|
|
89
|
+
// Not found, forbidden or too large won't change on a retry.
|
|
90
|
+
if (!response.ok)
|
|
91
|
+
return null;
|
|
92
|
+
if (Number(response.headers.get('content-length')) > MAX_IMAGE_BYTES) {
|
|
93
|
+
tooLarge.abort();
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
const bytes = await readBody(response, tooLarge);
|
|
97
|
+
if (!bytes || bytes.length === 0)
|
|
98
|
+
return null;
|
|
99
|
+
const type = imageType(response.headers.get('content-type'), bytes);
|
|
100
|
+
if (!type)
|
|
101
|
+
return null;
|
|
102
|
+
return `data:${type};base64,${Buffer.from(bytes).toString('base64')}`;
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
if (tooLarge.signal.aborted)
|
|
106
|
+
return null;
|
|
107
|
+
// Offline, blocked by CORS or the CSP, or timed out: try once more.
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* The response body, read a chunk at a time so a server that sends more than
|
|
114
|
+
* MAX_IMAGE_BYTES (whatever its Content-Length said) is cut off there rather
|
|
115
|
+
* than held in memory. Null if it was too large.
|
|
116
|
+
*/
|
|
117
|
+
async function readBody(response, tooLarge) {
|
|
118
|
+
if (!response.body) {
|
|
119
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
120
|
+
return bytes.length > MAX_IMAGE_BYTES ? null : bytes;
|
|
121
|
+
}
|
|
122
|
+
const reader = response.body.getReader();
|
|
123
|
+
const chunks = [];
|
|
124
|
+
let total = 0;
|
|
125
|
+
for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {
|
|
126
|
+
total += chunk.value.length;
|
|
127
|
+
if (total > MAX_IMAGE_BYTES) {
|
|
128
|
+
tooLarge.abort();
|
|
129
|
+
await reader.cancel().catch(() => { });
|
|
130
|
+
return null;
|
|
131
|
+
}
|
|
132
|
+
chunks.push(chunk.value);
|
|
133
|
+
}
|
|
134
|
+
const bytes = new Uint8Array(total);
|
|
135
|
+
let offset = 0;
|
|
136
|
+
for (const chunk of chunks) {
|
|
137
|
+
bytes.set(chunk, offset);
|
|
138
|
+
offset += chunk.length;
|
|
139
|
+
}
|
|
140
|
+
return bytes;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* The image's media type: the server's, if it says it's an image, or else
|
|
144
|
+
* read from the file's first bytes. Null for anything else (an error page
|
|
145
|
+
* served with 200, say), which html-to-docx would fail to measure and drop.
|
|
146
|
+
*/
|
|
147
|
+
function imageType(contentType, bytes) {
|
|
148
|
+
const declared = contentType?.split(';')[0].trim().toLowerCase();
|
|
149
|
+
if (declared?.startsWith('image/'))
|
|
150
|
+
return declared;
|
|
151
|
+
const match = SIGNATURES.find(([, signature]) => signature.every((byte, index) => bytes[index] === byte));
|
|
152
|
+
return match?.[0] ?? null;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Puts the image's alt text where it was, as a link to `src` when that's a web
|
|
156
|
+
* URL and the image isn't already inside a link. With no alt text, the URL
|
|
157
|
+
* itself is the text.
|
|
158
|
+
*/
|
|
159
|
+
function replaceWithAltText(image, src) {
|
|
160
|
+
const document = image.ownerDocument;
|
|
161
|
+
const isWebUrl = WEB_URL.test(src);
|
|
162
|
+
const text = image.getAttribute('alt')?.trim() || (isWebUrl ? src : '');
|
|
163
|
+
if (!text) {
|
|
164
|
+
image.remove();
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
if (!isWebUrl || image.closest('a')) {
|
|
168
|
+
image.replaceWith(document.createTextNode(text));
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
const link = document.createElement('a');
|
|
172
|
+
link.setAttribute('href', src);
|
|
173
|
+
link.textContent = text;
|
|
174
|
+
image.replaceWith(link);
|
|
175
|
+
}
|
|
176
|
+
//# sourceMappingURL=docx-images.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"docx-images.js","sourceRoot":"","sources":["../src/docx-images.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,6EAA6E;AAC7E,MAAM,CAAC,MAAM,eAAe,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAEhD;;;;GAIG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,GAAG,CAAC;AAE9B;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,CAAC;AAE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AAC;IAC/B,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;IACxB,KAAK,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;AAC1B,CAAC","sourcesContent":["import { Buffer } from 'buffer';\n\n/** html-to-docx's own limit for one image (imageProcessing.maxImageSize). */\nexport const MAX_IMAGE_BYTES = 10 * 1024 * 1024;\n\n/**\n * The most distinct image URLs fetched for one document: html-to-docx keeps\n * at most this many in its image cache (imageProcessing.maxCacheEntries). The\n * rest keep their alt text.\n */\nexport const MAX_IMAGES = 100;\n\n/**\n * How many downloads run at once. html-to-docx fetched one at a time; a few\n * in parallel is faster without opening a connection per image.\n */\nexport const CONCURRENCY = 4;\n\n/** Per attempt; the second attempt waits twice as long, as html-to-docx's do. */\nconst TIMEOUT_MS = 5000;\nconst ATTEMPTS = 2;\n\n/**\n * The URLs html-to-docx downloads (its `isValidUrl`, without the `g` flag\n * that makes `test()` stateful), anchored so the whole `src` is the URL.\n * Requiring both means this module never fetches what it wouldn't.\n */\nconst GENERATOR_URL =\n /http(s)?:\\/\\/(\\w+:?\\w*@)?(\\S+)(:\\d+)?((?<=\\.)\\w+)+(\\/([\\w#!:.?+=&%@!\\-/])*)?/i;\nconst WEB_URL = /^https?:\\/\\//i;\n\n/** Leading bytes of the image formats Word embeds, for servers that don't say. */\nconst SIGNATURES: [string, number[]][] = [\n ['image/png', [0x89, 0x50, 0x4e, 0x47]],\n ['image/jpeg', [0xff, 0xd8, 0xff]],\n ['image/gif', [0x47, 0x49, 0x46, 0x38]],\n ['image/bmp', [0x42, 0x4d]],\n];\n\n/**\n * Downloads each web image in `html` and swaps its `src` for a `data:` URI,\n * which html-to-docx embeds without downloading it again. An image that can't\n * be fetched becomes its alt text, linked to its URL, where html-to-docx would\n * drop it without a trace. Other sources it can't embed either, such as a\n * relative path, keep their alt text too.\n *\n * Each URL is fetched once, however many times it appears: at most\n * MAX_IMAGES of them, CONCURRENCY at a time.\n */\nexport async function embedImages(html: string): Promise<string> {\n const dom = new DOMParser().parseFromString(html, 'text/html');\n const images = Array.from(dom.querySelectorAll('img'));\n if (images.length === 0) return html;\n\n const urls = new Set<string>();\n for (const image of images) {\n const src = image.getAttribute('src') ?? '';\n if (isFetchable(src) && urls.size < MAX_IMAGES) urls.add(src);\n }\n\n const queue = Array.from(urls);\n const downloads = new Map<string, string | null>();\n const worker = async (): Promise<void> => {\n for (let url = queue.shift(); url !== undefined; url = queue.shift()) {\n downloads.set(url, await fetchImage(url));\n }\n };\n await Promise.all(\n Array.from({ length: Math.min(CONCURRENCY, queue.length) }, worker)\n );\n\n for (const image of images) {\n const src = image.getAttribute('src') ?? '';\n if (src.startsWith('data:')) continue;\n const dataUri = downloads.get(src);\n if (dataUri) {\n image.setAttribute('src', dataUri);\n } else {\n replaceWithAltText(image, src);\n }\n }\n\n return dom.body.innerHTML;\n}\n\nfunction isFetchable(src: string): boolean {\n return WEB_URL.test(src) && GENERATOR_URL.test(src);\n}\n\n/** The image at `url` as a `data:` URI, or null if it can't be fetched. */\nasync function fetchImage(url: string): Promise<string | null> {\n for (let attempt = 1; attempt <= ATTEMPTS; attempt++) {\n const tooLarge = new AbortController();\n try {\n const response = await fetch(url, {\n signal: AbortSignal.any([\n tooLarge.signal,\n AbortSignal.timeout(TIMEOUT_MS * attempt),\n ]),\n });\n // Not found, forbidden or too large won't change on a retry.\n if (!response.ok) return null;\n if (Number(response.headers.get('content-length')) > MAX_IMAGE_BYTES) {\n tooLarge.abort();\n return null;\n }\n const bytes = await readBody(response, tooLarge);\n if (!bytes || bytes.length === 0) return null;\n const type = imageType(response.headers.get('content-type'), bytes);\n if (!type) return null;\n return `data:${type};base64,${Buffer.from(bytes).toString('base64')}`;\n } catch {\n if (tooLarge.signal.aborted) return null;\n // Offline, blocked by CORS or the CSP, or timed out: try once more.\n }\n }\n return null;\n}\n\n/**\n * The response body, read a chunk at a time so a server that sends more than\n * MAX_IMAGE_BYTES (whatever its Content-Length said) is cut off there rather\n * than held in memory. Null if it was too large.\n */\nasync function readBody(\n response: Response,\n tooLarge: AbortController\n): Promise<Uint8Array | null> {\n if (!response.body) {\n const bytes = new Uint8Array(await response.arrayBuffer());\n return bytes.length > MAX_IMAGE_BYTES ? null : bytes;\n }\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (\n let chunk = await reader.read();\n !chunk.done;\n chunk = await reader.read()\n ) {\n total += chunk.value.length;\n if (total > MAX_IMAGE_BYTES) {\n tooLarge.abort();\n await reader.cancel().catch(() => {});\n return null;\n }\n chunks.push(chunk.value);\n }\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.length;\n }\n return bytes;\n}\n\n/**\n * The image's media type: the server's, if it says it's an image, or else\n * read from the file's first bytes. Null for anything else (an error page\n * served with 200, say), which html-to-docx would fail to measure and drop.\n */\nfunction imageType(\n contentType: string | null,\n bytes: Uint8Array\n): string | null {\n const declared = contentType?.split(';')[0].trim().toLowerCase();\n if (declared?.startsWith('image/')) return declared;\n const match = SIGNATURES.find(([, signature]) =>\n signature.every((byte, index) => bytes[index] === byte)\n );\n return match?.[0] ?? null;\n}\n\n/**\n * Puts the image's alt text where it was, as a link to `src` when that's a web\n * URL and the image isn't already inside a link. With no alt text, the URL\n * itself is the text.\n */\nfunction replaceWithAltText(image: HTMLImageElement, src: string): void {\n const document = image.ownerDocument;\n const isWebUrl = WEB_URL.test(src);\n const text = image.getAttribute('alt')?.trim() || (isWebUrl ? src : '');\n if (!text) {\n image.remove();\n return;\n }\n if (!isWebUrl || image.closest('a')) {\n image.replaceWith(document.createTextNode(text));\n return;\n }\n const link = document.createElement('a');\n link.setAttribute('href', src);\n link.textContent = text;\n image.replaceWith(link);\n}\n"]}
|
|
@@ -16,6 +16,9 @@ export interface DocumentStructure {
|
|
|
16
16
|
* it at the top of each page the table spans.
|
|
17
17
|
* - Table grids: the generator writes a second `<w:tblGrid>` between rows,
|
|
18
18
|
* which the schema doesn't allow; only the first is kept.
|
|
19
|
+
* - Section properties: the generator writes the body's `<w:sectPr>` (page
|
|
20
|
+
* size and margins) as its first child. The schema requires it last, and
|
|
21
|
+
* strict readers ignore it elsewhere, so it's moved to the end.
|
|
19
22
|
*/
|
|
20
23
|
export declare function patchStructure(wordDocument: Blob, structure: DocumentStructure): Promise<Blob>;
|
|
21
24
|
/** Exported for testing. */
|
package/build/docx-structure.js
CHANGED
|
@@ -12,6 +12,9 @@ import { keepXmlDeclaration, WORDPROCESSING_NS as W_NS } from './xml-part.js';
|
|
|
12
12
|
* it at the top of each page the table spans.
|
|
13
13
|
* - Table grids: the generator writes a second `<w:tblGrid>` between rows,
|
|
14
14
|
* which the schema doesn't allow; only the first is kept.
|
|
15
|
+
* - Section properties: the generator writes the body's `<w:sectPr>` (page
|
|
16
|
+
* size and margins) as its first child. The schema requires it last, and
|
|
17
|
+
* strict readers ignore it elsewhere, so it's moved to the end.
|
|
15
18
|
*/
|
|
16
19
|
export async function patchStructure(wordDocument, structure) {
|
|
17
20
|
const zip = await JSZip.loadAsync(await wordDocument.arrayBuffer());
|
|
@@ -56,6 +59,12 @@ export function patchDocumentXml(documentXml, structure) {
|
|
|
56
59
|
changed = true;
|
|
57
60
|
}
|
|
58
61
|
}
|
|
62
|
+
const body = dom.getElementsByTagNameNS(W_NS, 'body')[0];
|
|
63
|
+
const sectPr = body && children(body, 'sectPr')[0];
|
|
64
|
+
if (sectPr && body.lastElementChild !== sectPr) {
|
|
65
|
+
body.appendChild(sectPr);
|
|
66
|
+
changed = true;
|
|
67
|
+
}
|
|
59
68
|
if (!changed) {
|
|
60
69
|
return documentXml;
|
|
61
70
|
}
|
|
@@ -66,7 +75,7 @@ function isRulePlaceholder(paragraph) {
|
|
|
66
75
|
.map((t) => t.textContent ?? '')
|
|
67
76
|
.join('');
|
|
68
77
|
const jc = children(children(paragraph, 'pPr')[0] ?? paragraph, 'jc')[0];
|
|
69
|
-
return text.trim() === RULE_TEXT && jc?.getAttributeNS(W_NS, 'val') === 'center';
|
|
78
|
+
return (text.trim() === RULE_TEXT && jc?.getAttributeNS(W_NS, 'val') === 'center');
|
|
70
79
|
}
|
|
71
80
|
/** Replaces the paragraph's content with nothing but a bottom border. */
|
|
72
81
|
function drawRule(paragraph) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"docx-structure.js","sourceRoot":"","sources":["../src/docx-structure.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,IAAI,IAAI,EAAE,MAAM,eAAe,CAAC;AAU9E
|
|
1
|
+
{"version":3,"file":"docx-structure.js","sourceRoot":"","sources":["../src/docx-structure.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,IAAI,IAAI,EAAE,MAAM,eAAe,CAAC;AAU9E;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAClC,YAAkB,EAClB,SAA4B;IAE5B,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC,SAAS,CAAC,MAAM,YAAY,CAAC,WAAW,EAAE,CAAC,CAAC;IACpE,MAAM,aAAa,GAAG,GAAG,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC;IACpD,IAAI,CAAC,aAAa,EAAE,CAAC;QACnB,MAAM,IAAI,KAAK,CACb,gEAAgE,CACjE,CAAC;IACJ,CAAC;IAED,MAAM,WAAW,GAAG,MAAM,aAAa,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IACxD,MAAM,OAAO,GAAG,gBAAgB,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC;IACzD,IAAI,OAAO,KAAK,WAAW,EAAE,CAAC;QAC5B,OAAO,YAAY,CAAC;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AC,eAAe,CAAC,IAAI,EAAE,QAAQ,CAAC,EACxC,GAAG,CAAC,UAAU,CACf,CAAC;IACJ,CAAC;IACD,IAAI,QAAQ,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC7C,6EAA6E;QAC7E,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,eAAe,CAAC,IAAI,EAAE,aAAa,CAAC,CAAC,CAAC;IAClE,CAAC;AACH,CAAC;AAED,SAAS,QAAQ,CAAC,MAAe,EAAE,SAAiB;IAClD,OAAO,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,MAAM,CACvC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,YAAY,KAAK,IAAI,IAAI,KAAK,CAAC,SAAS,KAAK,SAAS,CACxE,CAAC;AACJ,CAAC","sourcesContent":["import JSZip from 'jszip';\nimport { RULE_TEXT } from './docx-html.js';\nimport { keepXmlDeclaration, WORDPROCESSING_NS as W_NS } from './xml-part.js';\n\n/** What the source HTML says about the document's rules and tables. */\nexport interface DocumentStructure {\n /** How many `<hr>` the HTML has. */\n rules: number;\n /** For each `<table>` in document order, whether its first row is a header. */\n headerRows: boolean[];\n}\n\n/**\n * Restores structure the generator drops or gets wrong:\n *\n * - Horizontal rules: each centered RULE_TEXT paragraph that stands in for an\n * `<hr>` (see prepareHtmlForDocx) becomes an empty paragraph with a bottom\n * border. They're matched in order against the number of `<hr>`, so a\n * paragraph that only happens to say `* * *` is left alone once they run out.\n * - Header rows: a table's header row gets `<w:tblHeader/>`, so Word repeats\n * it at the top of each page the table spans.\n * - Table grids: the generator writes a second `<w:tblGrid>` between rows,\n * which the schema doesn't allow; only the first is kept.\n * - Section properties: the generator writes the body's `<w:sectPr>` (page\n * size and margins) as its first child. The schema requires it last, and\n * strict readers ignore it elsewhere, so it's moved to the end.\n */\nexport async function patchStructure(\n wordDocument: Blob,\n structure: DocumentStructure\n): Promise<Blob> {\n const zip = await JSZip.loadAsync(await wordDocument.arrayBuffer());\n const documentEntry = zip.file('word/document.xml');\n if (!documentEntry) {\n throw new Error(\n 'Cannot patch structure: document contains no word/document.xml'\n );\n }\n\n const documentXml = await documentEntry.async('string');\n const patched = patchDocumentXml(documentXml, structure);\n if (patched === documentXml) {\n return wordDocument;\n }\n\n zip.file('word/document.xml', patched);\n return new Blob([await zip.generateAsync({ type: 'arraybuffer' })], {\n type: wordDocument.type,\n });\n}\n\n/** Exported for testing. */\nexport function patchDocumentXml(\n documentXml: string,\n structure: DocumentStructure\n): string {\n const dom = new DOMParser().parseFromString(documentXml, 'application/xml');\n let changed = false;\n\n let rulesLeft = structure.rules;\n for (const paragraph of Array.from(dom.getElementsByTagNameNS(W_NS, 'p'))) {\n if (rulesLeft === 0) break;\n if (isRulePlaceholder(paragraph)) {\n drawRule(paragraph);\n rulesLeft--;\n changed = true;\n }\n }\n\n const tables = Array.from(dom.getElementsByTagNameNS(W_NS, 'tbl'));\n for (const [index, table] of tables.entries()) {\n const grids = children(table, 'tblGrid');\n for (const extra of grids.slice(1)) {\n extra.remove();\n changed = true;\n }\n\n const firstRow = children(table, 'tr')[0];\n if (structure.headerRows[index] && firstRow) {\n markHeaderRow(firstRow);\n changed = true;\n }\n }\n\n const body = dom.getElementsByTagNameNS(W_NS, 'body')[0];\n const sectPr = body && children(body, 'sectPr')[0];\n if (sectPr && body.lastElementChild !== sectPr) {\n body.appendChild(sectPr);\n changed = true;\n }\n\n if (!changed) {\n return documentXml;\n }\n return keepXmlDeclaration(\n documentXml,\n new XMLSerializer().serializeToString(dom)\n );\n}\n\nfunction isRulePlaceholder(paragraph: Element): boolean {\n const text = Array.from(paragraph.getElementsByTagNameNS(W_NS, 't'))\n .map((t) => t.textContent ?? '')\n .join('');\n const jc = children(children(paragraph, 'pPr')[0] ?? paragraph, 'jc')[0];\n return (\n text.trim() === RULE_TEXT && jc?.getAttributeNS(W_NS, 'val') === 'center'\n );\n}\n\n/** Replaces the paragraph's content with nothing but a bottom border. */\nfunction drawRule(paragraph: Element): void {\n const document = paragraph.ownerDocument;\n while (paragraph.firstChild) {\n paragraph.removeChild(paragraph.firstChild);\n }\n\n const pPr = paragraph.appendChild(document.createElementNS(W_NS, 'w:pPr'));\n const pBdr = pPr.appendChild(document.createElementNS(W_NS, 'w:pBdr'));\n const bottom = pBdr.appendChild(document.createElementNS(W_NS, 'w:bottom'));\n bottom.setAttributeNS(W_NS, 'w:val', 'single');\n bottom.setAttributeNS(W_NS, 'w:sz', '6');\n bottom.setAttributeNS(W_NS, 'w:space', '1');\n bottom.setAttributeNS(W_NS, 'w:color', 'auto');\n}\n\nfunction markHeaderRow(row: Element): void {\n const document = row.ownerDocument;\n let trPr = children(row, 'trPr')[0];\n if (!trPr) {\n trPr = row.insertBefore(\n document.createElementNS(W_NS, 'w:trPr'),\n row.firstChild\n );\n }\n if (children(trPr, 'tblHeader').length === 0) {\n // The generator writes at most cantSplit here, which comes before tblHeader.\n trPr.appendChild(document.createElementNS(W_NS, 'w:tblHeader'));\n }\n}\n\nfunction children(parent: Element, localName: string): Element[] {\n return Array.from(parent.children).filter(\n (child) => child.namespaceURI === W_NS && child.localName === localName\n );\n}\n"]}
|
package/build/font-presets.js
CHANGED
|
@@ -25,7 +25,12 @@ const SIZE_SAN = 16;
|
|
|
25
25
|
* practice.
|
|
26
26
|
*/
|
|
27
27
|
export const CHINESE_OFFICIAL_DOC_FONTS = {
|
|
28
|
-
body: {
|
|
28
|
+
body: {
|
|
29
|
+
latin: LATIN_FONT,
|
|
30
|
+
eastAsia: BODY_FONT,
|
|
31
|
+
sizePt: SIZE_SAN,
|
|
32
|
+
bold: false,
|
|
33
|
+
},
|
|
29
34
|
headings: [
|
|
30
35
|
{
|
|
31
36
|
latin: LATIN_FONT,
|
|
@@ -40,7 +45,12 @@ export const CHINESE_OFFICIAL_DOC_FONTS = {
|
|
|
40
45
|
{ latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: false },
|
|
41
46
|
{ latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: false },
|
|
42
47
|
],
|
|
43
|
-
paragraph: {
|
|
48
|
+
paragraph: {
|
|
49
|
+
beforePt: 0,
|
|
50
|
+
afterPt: 0,
|
|
51
|
+
lineSpacing: 'grid',
|
|
52
|
+
firstLineIndentChars: 2,
|
|
53
|
+
},
|
|
44
54
|
page: {
|
|
45
55
|
widthMm: 210,
|
|
46
56
|
heightMm: 297,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"font-presets.js","sourceRoot":"","sources":["../src/font-presets.ts"],"names":[],"mappings":"AA6DA,MAAM,UAAU,GAAG,iBAAiB,CAAC;AACrC,MAAM,SAAS,GAAG,IAAI,CAAC;AAEvB,2BAA2B;AAC3B,MAAM,OAAO,GAAG,EAAE,CAAC;AACnB,2BAA2B;AAC3B,MAAM,QAAQ,GAAG,EAAE,CAAC;AAEpB;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAe;IACpD,IAAI,EAAE,
|
|
1
|
+
{"version":3,"file":"font-presets.js","sourceRoot":"","sources":["../src/font-presets.ts"],"names":[],"mappings":"AA6DA,MAAM,UAAU,GAAG,iBAAiB,CAAC;AACrC,MAAM,SAAS,GAAG,IAAI,CAAC;AAEvB,2BAA2B;AAC3B,MAAM,OAAO,GAAG,EAAE,CAAC;AACnB,2BAA2B;AAC3B,MAAM,QAAQ,GAAG,EAAE,CAAC;AAEpB;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAe;IACpD,IAAI,EAAE;QACJ,KAAK,EAAE,UAAU;QACjB,QAAQ,EAAE,SAAS;QACnB,MAAM,EAAE,QAAQ;QAChB,IAAI,EAAE,KAAK;KACZ;IACD,QAAQ,EAAE;QACR;YACE,KAAK,EAAE,UAAU;YACjB,QAAQ,EAAE,SAAS;YACnB,MAAM,EAAE,OAAO;YACf,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YAAY,GAA+B;IACtD,kBAAkB,EAAE,0BAA0B;CAC/C,CAAC;AAEF;;;;GAIG;AACH,MAAM,UAAU,eAAe,CAAC,IAAY;IAC1C,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,EAAE,MAAM,IAAI,CAAC,CAAC;IACnD,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,kBAAkB,CAAC,EAAE,MAAM,IAAI,CAAC,CAAC;IACxD,MAAM,IAAI,GACR,IAAI,CAAC,KAAK,CAAC,4CAA4C,CAAC,EAAE,MAAM,IAAI,CAAC,CAAC;IAExE,OAAO,GAAG,IAAI,EAAE,IAAI,GAAG,GAAG,OAAO,IAAI,GAAG,IAAI,IAAI,GAAG,GAAG,GAAG,EAAE,CAAC;AAC9D,CAAC","sourcesContent":["/**\n * Typography for one level of a document.\n *\n * Word selects a typeface per character class: Latin letters and digits are\n * rendered from the `w:ascii`/`w:hAnsi` run-property slots, Chinese characters\n * from `w:eastAsia`. Naming both fonts per level is therefore enough to keep\n * Chinese text in a Chinese face and Latin text in a Latin one.\n */\nexport interface LevelStyle {\n /** Typeface for Latin letters, digits and punctuation. */\n latin: string;\n /** Typeface for Chinese characters. */\n eastAsia: string;\n /** Font size in points. Chinese named sizes: size 2 (二号) = 22pt, size 3 (三号) = 16pt. */\n sizePt: number;\n bold: boolean;\n /** Centers the paragraph, without the first-line indent. */\n centered?: boolean;\n}\n\n/**\n * Word line spacing rule:\n *\n * - `single`: single line spacing.\n * - `grid`: exact line spacing at the line pitch of the page's document grid,\n * with widow control off, so every full page holds `page.grid.linesPerPage`\n * lines. Needs `page.grid`.\n */\nexport type LineSpacing = 'single' | 'grid';\n\nexport interface ParagraphStyle {\n /** Paragraph spacing before and after, in points. */\n beforePt: number;\n afterPt: number;\n lineSpacing: LineSpacing;\n /** First-line indent, in characters of the body font size. */\n firstLineIndentChars?: number;\n}\n\n/** Paper and text block, in millimeters. */\nexport interface PageLayout {\n widthMm: number;\n heightMm: number;\n marginsMm: { top: number; right: number; bottom: number; left: number };\n /** Word's document grid (文档网格): a fixed number of lines and characters. */\n grid?: { linesPerPage: number; charsPerLine: number };\n}\n\nexport interface FontPreset {\n body: LevelStyle;\n /** Six entries, applied to the `Heading1` - `Heading6` styles. */\n headings: LevelStyle[];\n /** Shared by the body text and every heading level. */\n paragraph: ParagraphStyle;\n /**\n * Page size and margins. Margins passed to `convertMarkdownToWord` as\n * `pageMargins` take precedence.\n */\n page?: PageLayout;\n}\n\nconst LATIN_FONT = 'Times New Roman';\nconst BODY_FONT = '仿宋';\n\n/** Chinese size 2 (二号). */\nconst SIZE_ER = 22;\n/** Chinese size 3 (三号). */\nconst SIZE_SAN = 16;\n\n/**\n * Chinese official documents (公文), after GB/T 9704-2012 《党政机关公文格式》:\n *\n * - Body: FangSong (仿宋), size 3\n * - Heading 1 (the title): FZXiaoBiaoSong (方正小标宋简体), size 2, centered (7.3.1)\n * - Heading 2: SimHei (黑体), size 3\n * - Heading 3: KaiTi (楷体), size 3\n * - Heading 4: FangSong, size 3, bold. The standard sets levels 3 and 4 in\n * plain 仿宋, but a bolded fourth level is how these documents are made.\n * - Heading 5 and below: FangSong, size 3, not bold.\n * - A4 paper with a 37mm top and 28mm left margin around a 156 × 225mm text\n * block (5.1, 5.2.1)\n * - 22 lines of 28 characters per page (5.2.3), as a document grid with exact\n * line spacing at its pitch\n * - Paragraphs indented two characters (7.3.3), headings below the title too\n *\n * Every level uses Times New Roman for Latin text and no space before or after\n * paragraphs. The standard names no Latin font; Times New Roman is common\n * practice.\n */\nexport const CHINESE_OFFICIAL_DOC_FONTS: FontPreset = {\n body: {\n latin: LATIN_FONT,\n eastAsia: BODY_FONT,\n sizePt: SIZE_SAN,\n bold: false,\n },\n headings: [\n {\n latin: LATIN_FONT,\n eastAsia: '方正小标宋简体',\n sizePt: SIZE_ER,\n bold: false,\n centered: true,\n },\n { latin: LATIN_FONT, eastAsia: '黑体', sizePt: SIZE_SAN, bold: false },\n { latin: LATIN_FONT, eastAsia: '楷体', sizePt: SIZE_SAN, bold: false },\n { latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: true },\n { latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: false },\n { latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: false },\n ],\n paragraph: {\n beforePt: 0,\n afterPt: 0,\n lineSpacing: 'grid',\n firstLineIndentChars: 2,\n },\n page: {\n widthMm: 210,\n heightMm: 297,\n // 297 - 37 - 225 = 35 at the bottom, 210 - 28 - 156 = 26 on the right.\n marginsMm: { top: 37, right: 26, bottom: 35, left: 28 },\n grid: { linesPerPage: 22, charsPerLine: 28 },\n },\n};\n\n/** Twips (1/20 point) per millimeter. */\nconst TWIPS_PER_MM = 1440 / 25.4;\n\nexport function mmToTwips(mm: number): number {\n return Math.round(mm * TWIPS_PER_MM);\n}\n\n/** The presets offered in the UI, keyed by the value of their `<option>`. */\nexport const FONT_PRESETS: Record<string, FontPreset> = {\n 'chinese-official': CHINESE_OFFICIAL_DOC_FONTS,\n};\n\n/**\n * Whether most of the letters in `text` are Chinese characters, used to suggest\n * the Chinese preset. Kana means Japanese, which also uses Han characters, so\n * text with a meaningful share of kana does not count.\n */\nexport function isMostlyChinese(text: string): boolean {\n const letters = text.match(/\\p{L}/gu)?.length ?? 0;\n const han = text.match(/\\p{Script=Han}/gu)?.length ?? 0;\n const kana =\n text.match(/[\\p{Script=Hiragana}\\p{Script=Katakana}]/gu)?.length ?? 0;\n\n return han >= 10 && han / letters >= 0.5 && kana < han / 10;\n}\n"]}
|
package/build/markdown-parser.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import DOMPurify from 'dompurify';
|
|
2
2
|
import { Marked } from 'marked';
|
|
3
|
+
import markedFootnote from 'marked-footnote';
|
|
3
4
|
// Our own instance, not marked's shared default: as an npm package, configuring
|
|
4
5
|
// that one would change how the consumer's own copy of marked renders.
|
|
5
6
|
// GitHub Flavored Markdown as GitHub renders .md files: tables and task lists,
|
|
@@ -11,11 +12,28 @@ marked.use({
|
|
|
11
12
|
renderer: {
|
|
12
13
|
code({ text, lang }) {
|
|
13
14
|
const language = lang?.match(/^\S*/)?.[0];
|
|
14
|
-
const className = language
|
|
15
|
+
const className = language
|
|
16
|
+
? ` class="language-${escapeHtml(language)}"`
|
|
17
|
+
: '';
|
|
15
18
|
return `<pre><code${className}>${escapeHtml(text)}</code></pre>\n`;
|
|
16
19
|
},
|
|
17
20
|
},
|
|
18
21
|
});
|
|
22
|
+
// GitHub's `[^1]` footnotes: numbered superscript references, and the notes in
|
|
23
|
+
// a list after a rule at the end, much as GitHub shows them. prepareHtmlForDocx
|
|
24
|
+
// drops the parts that only work on a web page (the in-page links).
|
|
25
|
+
marked.use(markedFootnote({ footnoteDivider: true }));
|
|
26
|
+
/**
|
|
27
|
+
* extractTitle only lexes, and marked-footnote resets its per-document state
|
|
28
|
+
* while rendering, so lexing with `marked` would number the next document's
|
|
29
|
+
* footnotes wrong or throw. Titles get their own instance without it.
|
|
30
|
+
*/
|
|
31
|
+
const titleLexer = new Marked({ gfm: true });
|
|
32
|
+
/**
|
|
33
|
+
* A `[^label]` footnote reference, which titleLexer leaves as text, or reads
|
|
34
|
+
* as a reference-style link when the note is defined.
|
|
35
|
+
*/
|
|
36
|
+
const FOOTNOTE_REFERENCE = /\[\^[^\]\s]+\]/g;
|
|
19
37
|
/**
|
|
20
38
|
* Parse markdown text and return HTML
|
|
21
39
|
*/
|
|
@@ -43,10 +61,12 @@ export function renderPreviewHtml(markdown) {
|
|
|
43
61
|
* Returns null if no H1 heading is found.
|
|
44
62
|
*/
|
|
45
63
|
export function extractTitle(markdown) {
|
|
46
|
-
const tokens =
|
|
64
|
+
const tokens = titleLexer.lexer(markdown);
|
|
47
65
|
for (const token of tokens) {
|
|
48
66
|
if (token.type === 'heading' && token.depth === 1) {
|
|
49
|
-
return plainText(token.tokens ?? [])
|
|
67
|
+
return plainText(token.tokens ?? [])
|
|
68
|
+
.replace(FOOTNOTE_REFERENCE, '')
|
|
69
|
+
.trim();
|
|
50
70
|
}
|
|
51
71
|
}
|
|
52
72
|
return null;
|
|
@@ -55,6 +75,10 @@ export function extractTitle(markdown) {
|
|
|
55
75
|
function plainText(tokens) {
|
|
56
76
|
return tokens
|
|
57
77
|
.map((token) => {
|
|
78
|
+
if (token.type === 'link' &&
|
|
79
|
+
token.raw.match(FOOTNOTE_REFERENCE)?.[0] === token.raw) {
|
|
80
|
+
return '';
|
|
81
|
+
}
|
|
58
82
|
if ('tokens' in token && token.tokens)
|
|
59
83
|
return plainText(token.tokens);
|
|
60
84
|
if (token.type === 'br')
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"markdown-parser.js","sourceRoot":"","sources":["../src/markdown-parser.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,MAAM,EAAc,MAAM,QAAQ,CAAC;
|
|
1
|
+
{"version":3,"file":"markdown-parser.js","sourceRoot":"","sources":["../src/markdown-parser.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,MAAM,EAAc,MAAM,QAAQ,CAAC;AAC5C,OAAO,cAAc,MAAM,iBAAiB,CAAC;AAE7C,gFAAgF;AAChF,uEAAuE;AACvE,+EAA+E;AAC/E,wEAAwE;AACxE,MAAM,MAAM,GAAG,IAAI,MAAM,CAAC,EAAE,GAAG,EAAE,IAAI,EAAE,CAAC,CAAC;AAEzC,+EAA+E;AAC/E,oEAAoE;AACpE,MAAM,CAAC,GAAG,CAAC;IACT,QAAQ,EAAE;QACR,IAAI,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE;YACjB,MAAM,QAAQ,GAAG,IAAI,EAAE,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;YAC1C,MAAM,SAAS,GAAG,QAAQ;gBACxB,CAAC,C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GAAG,EAAE,MAAM;IACX,GAAG,EAAE,QAAQ;IACb,GAAG,EAAE,OAAO;CACb,CAAC;AAEF,sFAAsF;AACtF,SAAS,UAAU,CAAC,IAAY;IAC9B,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC;AAChE,CAAC","sourcesContent":["import DOMPurify from 'dompurify';\nimport { Marked, type Token } from 'marked';\nimport markedFootnote from 'marked-footnote';\n\n// Our own instance, not marked's shared default: as an npm package, configuring\n// that one would change how the consumer's own copy of marked renders.\n// GitHub Flavored Markdown as GitHub renders .md files: tables and task lists,\n// and a single newline inside a paragraph is a space, not a line break.\nconst marked = new Marked({ gfm: true });\n\n// marked's default code renderer keeps the block's trailing newline, which the\n// .docx code block patch would turn into a blank last line in Word.\nmarked.use({\n renderer: {\n code({ text, lang }) {\n const language = lang?.match(/^\\S*/)?.[0];\n const className = language\n ? ` class=\"language-${escapeHtml(language)}\"`\n : '';\n return `<pre><code${className}>${escapeHtml(text)}</code></pre>\\n`;\n },\n },\n});\n\n// GitHub's `[^1]` footnotes: numbered superscript references, and the notes in\n// a list after a rule at the end, much as GitHub shows them. prepareHtmlForDocx\n// drops the parts that only work on a web page (the in-page links).\nmarked.use(markedFootnote({ footnoteDivider: true }));\n\n/**\n * extractTitle only lexes, and marked-footnote resets its per-document state\n * while rendering, so lexing with `marked` would number the next document's\n * footnotes wrong or throw. Titles get their own instance without it.\n */\nconst titleLexer = new Marked({ gfm: true });\n\n/**\n * A `[^label]` footnote reference, which titleLexer leaves as text, or reads\n * as a reference-style link when the note is defined.\n */\nconst FOOTNOTE_REFERENCE = /\\[\\^[^\\]\\s]+\\]/g;\n\n/**\n * Parse markdown text and return HTML\n */\nexport function parseMarkdownToHtml(markdown: string): string {\n try {\n return marked.parse(markdown) as string;\n } catch (error) {\n console.error('Markdown parsing error:', error);\n throw new Error('Failed to parse markdown content', { cause: error });\n }\n}\n\n/**\n * Parse markdown into HTML that is safe to put in the page with innerHTML.\n * marked passes raw HTML through, so a shared .md file could otherwise run\n * script (e.g. `<img src=x onerror=...>`). The .docx path doesn't need this,\n * since html-to-docx never executes the HTML.\n */\nexport function renderPreviewHtml(markdown: string): string {\n return DOMPurify.sanitize(parseMarkdownToHtml(markdown));\n}\n\n/**\n * Extract the first H1 heading from markdown content as plain text, without\n * inline markup, since it becomes the Word document's title.\n * Returns null if no H1 heading is found.\n */\nexport function extractTitle(markdown: string): string | null {\n const tokens = titleLexer.lexer(markdown);\n for (const token of tokens) {\n if (token.type === 'heading' && token.depth === 1) {\n return plainText(token.tokens ?? [])\n .replace(FOOTNOTE_REFERENCE, '')\n .trim();\n }\n }\n return null;\n}\n\n/** The text of inline tokens with their markup (emphasis, links, code) removed. */\nfunction plainText(tokens: Token[]): string {\n return tokens\n .map((token) => {\n if (\n token.type === 'link' &&\n token.raw.match(FOOTNOTE_REFERENCE)?.[0] === token.raw\n ) {\n return '';\n }\n if ('tokens' in token && token.tokens) return plainText(token.tokens);\n if (token.type === 'br') return ' ';\n if (token.type === 'html') return '';\n return 'text' in token ? token.text : '';\n })\n .join('');\n}\n\n/**\n * Convert a string into a URL/filename-safe slug.\n * Lowercases, replaces whitespace and underscores with hyphens,\n * strips characters that are not word characters (\\w), whitespace, or hyphens,\n * and collapses consecutive hyphens. Note that \\w includes [a-zA-Z0-9_] and\n * Unicode letters/digits, so accented characters are preserved.\n */\nexport function slugify(text: string): string {\n return text\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, '')\n .replace(/[\\s_]+/g, '-')\n .replace(/-+/g, '-')\n .replace(/^-+|-+$/g, '');\n}\n\nconst HTML_ESCAPES: Record<string, string> = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n};\n\n/** Escape text for HTML without needing a DOM, so parsing works outside a browser. */\nfunction escapeHtml(text: string): string {\n return text.replace(/[&<>\"']/g, (char) => HTML_ESCAPES[char]);\n}\n"]}
|
package/build/xml-part.js
CHANGED
|
@@ -66,7 +66,8 @@ export function paragraphProperty(pPr, localName) {
|
|
|
66
66
|
if (child.localName === localName) {
|
|
67
67
|
return child;
|
|
68
68
|
}
|
|
69
|
-
if (before === null &&
|
|
69
|
+
if (before === null &&
|
|
70
|
+
PARAGRAPH_PROPERTY_ORDER.indexOf(child.localName) > rank) {
|
|
70
71
|
before = child;
|
|
71
72
|
}
|
|
72
73
|
}
|
package/build/xml-part.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"xml-part.js","sourceRoot":"","sources":["../src/xml-part.ts"],"names":[],"mappings":"AAAA,8DAA8D;AAC9D,MAAM,CAAC,MAAM,iBAAiB,
|
|
1
|
+
{"version":3,"file":"xml-part.js","sourceRoot":"","sources":["../src/xml-part.ts"],"names":[],"mappings":"AAAA,8DAA8D;AAC9D,MAAM,CAAC,MAAM,iBAAiB,GAC5B,8DAA8D,CAAC;AAEjE,4DAA4D;AAC5D,MAAM,CAAC,MAAM,MAAM,GAAG,sCAAsC,CAAC;AAE7D;;;GAGG;AACH,MAAM,UAAU,kBAAkB,CAChC,QAAgB,EAChB,UAAkB;IAElB,MAAM,WAAW,GAAG,sBAAsB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IAC1D,IAAI,WAAW,IAAI,CAAC,UAAU,CAAC,SAAS,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;QAC5D,OAAO,GAAG,WAAW,CAAC,CAAC,CAAC,KAAK,UAAU,EAAE,CAAC;IAC5C,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC;AAED,mEAAmE;AACnE,MAAM,wBAAwB,GAAG;IAC/B,QAAQ;IACR,UAAU;IACV,WAAW;IACX,iBAAiB;IACjB,SAAS;IACT,cAAc;IACd,OAAO;IACP,qBAAqB;IACrB,MAAM;IACN,KAAK;IACL,MAAM;IACN,qBAAqB;IACrB,SAAS;IACT,UAAU;IACV,eAAe;IACf,cAAc;IACd,aAAa;IACb,aAAa;IACb,MAAM;IACN,gBAAgB;IAChB,YAAY;IACZ,SAAS;IACT,KAAK;IACL,mBAAmB;IACnB,eAAe;IACf,iBAAiB;IACjB,IAAI;IACJ,eAAe;IACf,eAAe;IACf,kBAAkB;IAClB,YAAY;IACZ,OAAO;IACP,UAAU;IACV,KAAK;IACL,QAAQ;IACR,WAAW;CACZ,CAAC;AAEF;;;GAGG;AACH,MAAM,UAAU,iBAAiB,CAAC,GAAY,EAAE,SAAiB;IAC/D,MAAM,IAAI,GAAG,wBAAwB,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IACzD,IAAI,MAAM,GAAmB,IAAI,CAAC;IAClC,KAAK,MAAM,KAAK,IAAI,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC7C,IAAI,KAAK,CAAC,YAAY,KAAK,iBAAiB,EAAE,CAAC;YAC7C,SAAS;QACX,CAAC;QACD,IAAI,KAAK,CAAC,SAAS,KAAK,SAAS,EAAE,CAAC;YAClC,OAAO,KAAK,CAAC;QACf,CAAC;QACD,IACE,MAAM,KAAK,IAAI;YACf,wBAAwB,CAAC,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC,GAAG,IAAI,EACxD,CAAC;YACD,MAAM,GAAG,KAAK,CAAC;QACjB,CAAC;IACH,CAAC;IACD,MAAM,OAAO,GAAG,GAAG,CAAC,aAAa,CAAC,eAAe,CAC/C,iBAAiB,EACjB,KAAK,SAAS,EAAE,CACjB,CAAC;IACF,OAAO,GAAG,CAAC,YAAY,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;AAC3C,CAAC","sourcesContent":["/** Namespace of the WordprocessingML parts inside a .docx. */\nexport const WORDPROCESSING_NS =\n 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';\n\n/** Namespace of the `xml:` prefix, used for `xml:space`. */\nexport const XML_NS = 'http://www.w3.org/XML/1998/namespace';\n\n/**\n * `XMLSerializer` drops the XML declaration that OPC parts start with, so it is\n * copied back from the source.\n */\nexport function keepXmlDeclaration(\n original: string,\n serialized: string\n): string {\n const declaration = /^\\s*(<\\?xml[^>]*\\?>)/.exec(original);\n if (declaration && !serialized.trimStart().startsWith('<?')) {\n return `${declaration[1]}\\n${serialized}`;\n }\n return serialized;\n}\n\n/** The children of `<w:pPr>`, in the order the schema requires. */\nconst PARAGRAPH_PROPERTY_ORDER = [\n 'pStyle',\n 'keepNext',\n 'keepLines',\n 'pageBreakBefore',\n 'framePr',\n 'widowControl',\n 'numPr',\n 'suppressLineNumbers',\n 'pBdr',\n 'shd',\n 'tabs',\n 'suppressAutoHyphens',\n 'kinsoku',\n 'wordWrap',\n 'overflowPunct',\n 'topLinePunct',\n 'autoSpaceDE',\n 'autoSpaceDN',\n 'bidi',\n 'adjustRightInd',\n 'snapToGrid',\n 'spacing',\n 'ind',\n 'contextualSpacing',\n 'mirrorIndents',\n 'suppressOverlap',\n 'jc',\n 'textDirection',\n 'textAlignment',\n 'textboxTightWrap',\n 'outlineLvl',\n 'divId',\n 'cnfStyle',\n 'rPr',\n 'sectPr',\n 'pPrChange',\n];\n\n/**\n * The `localName` child of a `<w:pPr>`, created in schema order if missing.\n * WinWord rejects paragraph properties that are out of order.\n */\nexport function paragraphProperty(pPr: Element, localName: string): Element {\n const rank = PARAGRAPH_PROPERTY_ORDER.indexOf(localName);\n let before: Element | null = null;\n for (const child of Array.from(pPr.children)) {\n if (child.namespaceURI !== WORDPROCESSING_NS) {\n continue;\n }\n if (child.localName === localName) {\n return child;\n }\n if (\n before === null &&\n PARAGRAPH_PROPERTY_ORDER.indexOf(child.localName) > rank\n ) {\n before = child;\n }\n }\n const created = pPr.ownerDocument.createElementNS(\n WORDPROCESSING_NS,\n `w:${localName}`\n );\n return pPr.insertBefore(created, before);\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "markdown-to-word",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Convert GitHub Flavored Markdown to Word (.docx) documents in Node or the browser",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "build/main.js",
|
|
@@ -28,8 +28,10 @@
|
|
|
28
28
|
"lint": "eslint .",
|
|
29
29
|
"lint:fix": "eslint --fix .",
|
|
30
30
|
"format": "prettier --write .",
|
|
31
|
+
"format:check": "prettier --check .",
|
|
31
32
|
"typecheck": "astro sync && tsc --noEmit",
|
|
32
33
|
"test": "vitest run",
|
|
34
|
+
"test:coverage": "vitest run --coverage",
|
|
33
35
|
"test:e2e": "playwright test",
|
|
34
36
|
"gen:og": "node scripts/gen-og.mjs",
|
|
35
37
|
"gen:i18n": "node scripts/translate-i18n.mjs",
|
|
@@ -67,7 +69,8 @@
|
|
|
67
69
|
"dompurify": "^3.4.17",
|
|
68
70
|
"jsdom": "^30.1.3",
|
|
69
71
|
"jszip": "^3.10.2",
|
|
70
|
-
"marked": "^18.1.1"
|
|
72
|
+
"marked": "^18.1.1",
|
|
73
|
+
"marked-footnote": "^1.4.0"
|
|
71
74
|
},
|
|
72
75
|
"author": "Ben Balter <ben@balter.com>",
|
|
73
76
|
"license": "MIT",
|
|
@@ -90,5 +93,10 @@
|
|
|
90
93
|
],
|
|
91
94
|
"bugs": {
|
|
92
95
|
"url": "https://github.com/benbalter/markdown-to-word-js/issues"
|
|
96
|
+
},
|
|
97
|
+
"overrides": {
|
|
98
|
+
"@tailwindcss/typography": {
|
|
99
|
+
"postcss-selector-parser": "^7.1.6"
|
|
100
|
+
}
|
|
93
101
|
}
|
|
94
102
|
}
|