markdown-to-word 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Ben Balter
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,130 @@
1
- # Temporary Holding Version
1
+ # Markdown to Word
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![CI](https://github.com/benbalter/markdown-to-word-js/actions/workflows/ci.yml/badge.svg)](https://github.com/benbalter/markdown-to-word-js/actions/workflows/ci.yml)
4
+
5
+ Convert GitHub Flavored Markdown to a formatted Word (`.docx`) document, entirely in your browser, at **[md2word.app](https://md2word.app)**. Nothing is uploaded.
6
+
7
+ It's the mirror image of [word2md.com](https://word2md.com) ([word-to-markdown-js](https://github.com/benbalter/word-to-markdown-js)), which goes the other way, and the successor to [markdown_to_word](https://github.com/benbalter/markdown_to_word), the original Ruby gem and web demo, first published in 2015 and now archived.
8
+
9
+ ## Usage
10
+
11
+ 1. Go to [md2word.app](https://md2word.app).
12
+ 2. Drop a `.md` file anywhere on the page, choose one, or paste Markdown. AI chat responses (ChatGPT, Claude, and others) are Markdown, so they paste in as-is.
13
+ 3. A dropped file converts right away. For pasted text, click **Convert to Word**, or press Ctrl/⌘+Enter.
14
+ 4. Click **Download .docx**, or **Copy formatted text** to paste straight into Word or Google Docs with the formatting intact.
15
+
16
+ The document is named after its first heading, which also becomes its title.
17
+
18
+ ## What converts
19
+
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` | Indented paragraphs |
30
+ | `---` horizontal rules | A line across the page |
31
+ | `![images](https://example.com/a.png)` | Embedded, when the browser can fetch them (see [Limitations](#limitations)) |
32
+
33
+ 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
+
35
+ ## Optional Font Presets
36
+
37
+ Conversions use Word's standard styling by default. Choosing **Chinese official document (公文)** from the **Style** menu rewrites the generated document so each level gets an East Asian face and a 公文 size alongside Times New Roman:
38
+
39
+ | Level | Font size | Chinese characters | Latin letters and digits |
40
+ | ----------- | ----------- | ------------------ | ------------------------ |
41
+ | Body | 三号 (16pt) | 仿宋 | Times New Roman |
42
+ | Heading 1 | 二号 (22pt) | 方正小标宋简体 | Times New Roman |
43
+ | Heading 2 | 三号 (16pt) | 黑体 | Times New Roman |
44
+ | Heading 3 | 三号 (16pt) | 楷体 | Times New Roman |
45
+ | Heading 4-6 | 三号 (16pt) | 仿宋 (bold) | Times New Roman |
46
+
47
+ The app remembers your choice in this browser, and suggests the preset when the text you paste is mostly Chinese.
48
+
49
+ Word resolves a typeface per character class, so English words and numbers inside a Chinese sentence stay in Times New Roman. The fonts must be installed on the machine that opens the document.
50
+
51
+ Every level also drops to 段前段后 0 行. The preset also pins 单倍行距 (`w:lineRule="auto"`) on the body and heading styles rather than relying on the converter default of 最小值 12 磅.
52
+
53
+ The preset covers fonts, sizes and spacing only. It doesn't yet set A4 paper, the GB/T 9704-2012 margins or the 22-line page, so documents are 公文-styled rather than compliant; see [#106](https://github.com/benbalter/markdown-to-word-js/issues/106).
54
+
55
+ Programmatically:
56
+
57
+ ```ts
58
+ import { convertMarkdownToWord, CHINESE_OFFICIAL_DOC_FONTS } from 'markdown-to-word';
59
+
60
+ const blob = await convertMarkdownToWord(markdown, {
61
+ fontPreset: CHINESE_OFFICIAL_DOC_FONTS,
62
+ });
63
+ ```
64
+
65
+ ## Privacy
66
+
67
+ Conversion happens entirely in your browser: your Markdown and the Word document never leave your device. Images your Markdown links to load from the sites that host them, like on any web page. md2word.app uses cookie-free Cloudflare Web Analytics; a local or self-hosted copy has no analytics. Raw HTML in the preview is sanitized, so a shared file can't run script. See the [privacy policy](https://md2word.app/privacy/).
68
+
69
+ ## Limitations
70
+
71
+ - 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). Other images, images under 1 KB (html-to-docx's minimum), and local file paths are left out.
72
+ - Complex raw HTML inside Markdown may not convert cleanly, and advanced Word features (comments, tracked changes, page layout) aren't produced.
73
+ - Very large documents can be slow, since everything runs in the browser. Files are limited to 5 MB.
74
+ - The site works in current versions of Chrome, Edge, Firefox, and Safari. The end-to-end tests run in Chrome.
75
+
76
+ ## Use it from code
77
+
78
+ The converter is also on npm as [`markdown-to-word`](https://www.npmjs.com/package/markdown-to-word), for Node 22.12+ and for browsers through a bundler (Vite, webpack, esbuild):
79
+
80
+ ```bash
81
+ npm install markdown-to-word
82
+ ```
83
+
84
+ `convertMarkdownToWord` returns the `.docx` as a `Blob`:
85
+
86
+ ```ts
87
+ import { writeFile } from 'node:fs/promises';
88
+ import { convertMarkdownToWord } from 'markdown-to-word';
89
+
90
+ const blob = await convertMarkdownToWord('# Hello\n\nFrom **Markdown**.', {
91
+ pageMargins: { top: 1, right: 1, bottom: 1, left: 1 }, // inches
92
+ });
93
+ await writeFile('hello.docx', Buffer.from(await blob.arrayBuffer()));
94
+ ```
95
+
96
+ In a browser, hand the `Blob` to a download link with `URL.createObjectURL(blob)`.
97
+
98
+ The converter needs the DOM's `DOMParser` and `XMLSerializer`. Browsers have them; in Node, the package sets them as globals from [jsdom](https://github.com/jsdom/jsdom) when they're missing, so there's nothing to set up.
99
+
100
+ 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.
101
+
102
+ On a server, treat Markdown from users as untrusted: the converter downloads each remote image (`![](https://…)`) to embed it, so the request comes from your server. Strip or allowlist image URLs first if the server can reach internal addresses.
103
+
104
+ ## Development
105
+
106
+ Requires Node.js 22.12 or later (`.nvmrc` pins the version CI uses).
107
+
108
+ ```bash
109
+ git clone https://github.com/benbalter/markdown-to-word-js.git
110
+ cd markdown-to-word-js
111
+ npm install
112
+ npm run dev # http://localhost:4321
113
+ npm run build # static site in dist/
114
+ npm test # unit tests; npm run test:e2e for Playwright
115
+ ```
116
+
117
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for the project layout and checks.
118
+
119
+ - **Site:** [Astro](https://astro.build) with [Tailwind CSS](https://tailwindcss.com), sharing word2md.com's design system.
120
+ - **Conversion:** [marked](https://marked.js.org/) turns Markdown into HTML, [@turbodocx/html-to-docx](https://github.com/TurboDocx/html-to-docx) builds the `.docx`, and JSZip patches fix up code blocks, rules, table headers, and font presets.
121
+ - **Translations:** the UI is ready for more languages; see [web/i18n/README.md](web/i18n/README.md).
122
+ - **Hosting:** Cloudflare Workers Static Assets. A push to `main` builds, runs the tests, and deploys; see [docs/cloudflare.md](docs/cloudflare.md).
123
+
124
+ ## Contributing
125
+
126
+ Contributions are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md), and [open an issue](https://github.com/benbalter/markdown-to-word-js/issues) for bugs and feature requests.
127
+
128
+ ## License
129
+
130
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,9 @@
1
+ import { Buffer } from 'buffer';
2
+ // html-to-docx embeds images through Node's global Buffer, which browsers
3
+ // don't have: remote images were skipped and a data: URI image failed the
4
+ // whole conversion. Its README lists the polyfill as required in a browser.
5
+ // This is its own module so importing it first sets the global before
6
+ // html-to-docx loads.
7
+ const globals = globalThis;
8
+ globals.Buffer ??= Buffer;
9
+ //# sourceMappingURL=buffer-global.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"buffer-global.js","sourceRoot":"","sources":["../src/buffer-global.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,0EAA0E;AAC1E,0EAA0E;AAC1E,4EAA4E;AAC5E,sEAAsE;AACtE,sBAAsB;AACtB,MAAM,OAAO,GAAG,UAAkC,CAAC;AACnD,OAAO,CAAC,MAAM,KAAK,MAAM,CAAC","sourcesContent":["import { Buffer } from 'buffer';\n\n// html-to-docx embeds images through Node's global Buffer, which browsers\n// don't have: remote images were skipped and a data: URI image failed the\n// whole conversion. Its README lists the polyfill as required in a browser.\n// This is its own module so importing it first sets the global before\n// html-to-docx loads.\nconst globals = globalThis as { Buffer?: unknown };\nglobals.Buffer ??= Buffer;\n"]}
@@ -0,0 +1,17 @@
1
+ import './buffer-global.js';
2
+ import type { FontPreset } from './font-presets.js';
3
+ export interface ConversionOptions {
4
+ /** Page margins in inches. */
5
+ pageMargins?: {
6
+ top: number;
7
+ right: number;
8
+ bottom: number;
9
+ left: number;
10
+ };
11
+ /** Rewrites the document fonts. Omit to keep the default styling. */
12
+ fontPreset?: FontPreset;
13
+ }
14
+ /**
15
+ * Convert markdown text to a Word document blob using HTML as an intermediary format
16
+ */
17
+ export declare function convertMarkdownToWord(markdown: string, options?: ConversionOptions): Promise<Blob>;
@@ -0,0 +1,97 @@
1
+ // Must come first: it sets the global Buffer html-to-docx needs for images.
2
+ import './buffer-global.js';
3
+ import HTMLtoDOCX from '@turbodocx/html-to-docx';
4
+ import { prepareHtmlForDocx } from './docx-html.js';
5
+ import { parseMarkdownToHtml, extractTitle } from './markdown-parser.js';
6
+ /**
7
+ * Convert markdown text to a Word document blob using HTML as an intermediary format
8
+ */
9
+ export async function convertMarkdownToWord(markdown, options = {}) {
10
+ try {
11
+ const html = parseMarkdownToHtml(markdown);
12
+ const documentOptions = {
13
+ // The generator's default border size is 0, so tables had no grid lines.
14
+ // A thin light gray rule (size in eighths of a point) matches how
15
+ // GitHub draws tables.
16
+ table: { borderOptions: { size: 4, stroke: 'single', color: 'BFBFBF' } },
17
+ };
18
+ const title = extractTitle(markdown);
19
+ if (title) {
20
+ documentOptions.title = title;
21
+ }
22
+ if (options.pageMargins) {
23
+ // Convert inches to twips (1 inch = 1440 twips)
24
+ documentOptions.margins = {
25
+ top: options.pageMargins.top * 1440,
26
+ right: options.pageMargins.right * 1440,
27
+ bottom: options.pageMargins.bottom * 1440,
28
+ left: options.pageMargins.left * 1440,
29
+ };
30
+ }
31
+ const result = await HTMLtoDOCX(prepareHtmlForDocx(html), null, documentOptions);
32
+ // HTMLtoDOCX returns Blob in browser, Buffer/ArrayBuffer in Node.js
33
+ const generated = result instanceof Blob ? result : new Blob([result]);
34
+ // The patches rewrite the .docx zip with JSZip. html-to-docx bundles its own
35
+ // copy, so ours is a second one; load it only when a patch actually applies.
36
+ // Code blocks are broken in the generator output itself, so they are fixed
37
+ // whether or not a font preset is requested.
38
+ let wordDocument = generated;
39
+ if (html.includes('<pre')) {
40
+ const codeBlocks = codeBlockTexts(html);
41
+ wordDocument = await patchOrKeep(wordDocument, 'code block', async (document) => {
42
+ const { formatCodeBlocks } = await import('./docx-code-blocks.js');
43
+ return formatCodeBlocks(document, codeBlocks);
44
+ });
45
+ }
46
+ if (html.includes('<hr') || html.includes('<table')) {
47
+ const structure = documentStructure(html);
48
+ wordDocument = await patchOrKeep(wordDocument, 'structure', async (document) => {
49
+ const { patchStructure } = await import('./docx-structure.js');
50
+ return patchStructure(document, structure);
51
+ });
52
+ }
53
+ const { fontPreset } = options;
54
+ if (fontPreset) {
55
+ wordDocument = await patchOrKeep(wordDocument, 'font preset', async (document) => {
56
+ const { applyFontPreset } = await import('./docx-font-preset.js');
57
+ return applyFontPreset(document, fontPreset);
58
+ });
59
+ }
60
+ return wordDocument;
61
+ }
62
+ catch (error) {
63
+ console.error('Word document generation error:', error);
64
+ throw new Error('Failed to generate Word document', { cause: error });
65
+ }
66
+ }
67
+ /** The text of each `<pre>` in `html`, in document order. */
68
+ function codeBlockTexts(html) {
69
+ const dom = new DOMParser().parseFromString(html, 'text/html');
70
+ return Array.from(dom.querySelectorAll('pre'), (pre) => pre.textContent ?? '');
71
+ }
72
+ /** The rules and table header rows in `html`, for the structure patch. */
73
+ function documentStructure(html) {
74
+ const dom = new DOMParser().parseFromString(html, 'text/html');
75
+ return {
76
+ rules: dom.querySelectorAll('hr').length,
77
+ headerRows: Array.from(dom.querySelectorAll('table'), (table) => {
78
+ const firstRow = table.querySelector('tr');
79
+ return Boolean(table.tHead) || Boolean(firstRow && firstRow.querySelector('td') === null);
80
+ }),
81
+ };
82
+ }
83
+ /**
84
+ * The patches polish a document html-to-docx already produced, so a failure in
85
+ * one (including its chunk failing to load) keeps the unpatched document
86
+ * rather than failing the whole conversion.
87
+ */
88
+ async function patchOrKeep(wordDocument, name, patch) {
89
+ try {
90
+ return await patch(wordDocument);
91
+ }
92
+ catch (error) {
93
+ console.warn(`Skipped the ${name} patch; keeping the unpatched document:`, error);
94
+ return wordDocument;
95
+ }
96
+ }
97
+ //# sourceMappingURL=converter.js.map
@@ -0,0 +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;AAGpD,OAAO,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAczE;;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,YAAY,CAAC,QAAQ,CAAC,CAAC;QACrC,IAAI,KAAK,EAAE,CAAC;YACV,eAAe,CAAC,KAAK,GAAG,KAAK,CAAC;QAChC,CAAC;QAED,IAAI,OAAO,CAAC,WAAW,EAAE,CAAC;YACxB,gDAAgD;YAChD,eAAe,CAAC,OAAO,GAAG;gBACxB,GAAG,EAAE,OAAO,CAAC,WAAW,CAAC,GAAG,GAAG,IAAI;gBACnC,KAAK,EAAE,OAAO,CAAC,WAAW,CAAC,KAAK,GAAG,IAAI;gBACvC,MAAM,E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EAAE,CAAC,KAAK,EAAE,EAAE;YAC9D,MAAM,QAAQ,GAAG,KAAK,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;YAC3C,OAAO,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,OAAO,CAAC,QAAQ,IAAI,QAAQ,CAAC,aAAa,CAAC,IAAI,CAAC,KAAK,IAAI,CAAC,CAAC;QAC5F,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,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 type { FontPreset } from './font-presets.js';\nimport { parseMarkdownToHtml, extractTitle } from './markdown-parser.js';\n\nexport interface ConversionOptions {\n /** Page margins in inches. */\n pageMargins?: {\n top: number;\n right: number;\n bottom: number;\n left: number;\n };\n /** Rewrites the document fonts. Omit to keep the default styling. */\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 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}"]}
@@ -0,0 +1,21 @@
1
+ import { CODE_FONT } from './docx-html.js';
2
+ export { CODE_FONT };
3
+ /**
4
+ * Makes code blocks survive in Word, regardless of the font preset:
5
+ *
6
+ * - Line breaks: the generator keeps the source newlines of a `<pre>` as bare
7
+ * `LF` inside `<w:t>`, which WinWord renders as whitespace; they become
8
+ * `<w:br/>` here. Everywhere else the generator emits `<w:br/>` itself, so a
9
+ * bare `LF` is the bug's own signature and needs no other marker.
10
+ * - Typeface: the generator sets only `w:ascii`/`w:hAnsi`, so Chinese comments
11
+ * fell through to the body font. Code paragraphs are found by their text,
12
+ * matched in order against `codeBlocks`, and get the monospace face in all
13
+ * three slots. Keying on the generator's hardcoded code font instead would
14
+ * also catch any inline `font-family` that names the same font.
15
+ *
16
+ * @param codeBlocks The text content of each `<pre>` in the source HTML, in
17
+ * document order.
18
+ */
19
+ export declare function formatCodeBlocks(wordDocument: Blob, codeBlocks: string[]): Promise<Blob>;
20
+ /** Exported for testing. */
21
+ export declare function formatDocumentXml(documentXml: string, codeBlocks: string[]): string;
@@ -0,0 +1,134 @@
1
+ import JSZip from 'jszip';
2
+ import { CODE_FONT } from './docx-html.js';
3
+ import { keepXmlDeclaration, WORDPROCESSING_NS as W_NS, XML_NS } from './xml-part.js';
4
+ export { CODE_FONT };
5
+ /** Theme slots WinWord prefers over explicitly named fonts. */
6
+ const THEME_FONT_ATTRIBUTES = ['asciiTheme', 'eastAsiaTheme', 'hAnsiTheme', 'cstheme'];
7
+ /**
8
+ * Makes code blocks survive in Word, regardless of the font preset:
9
+ *
10
+ * - Line breaks: the generator keeps the source newlines of a `<pre>` as bare
11
+ * `LF` inside `<w:t>`, which WinWord renders as whitespace; they become
12
+ * `<w:br/>` here. Everywhere else the generator emits `<w:br/>` itself, so a
13
+ * bare `LF` is the bug's own signature and needs no other marker.
14
+ * - Typeface: the generator sets only `w:ascii`/`w:hAnsi`, so Chinese comments
15
+ * fell through to the body font. Code paragraphs are found by their text,
16
+ * matched in order against `codeBlocks`, and get the monospace face in all
17
+ * three slots. Keying on the generator's hardcoded code font instead would
18
+ * also catch any inline `font-family` that names the same font.
19
+ *
20
+ * @param codeBlocks The text content of each `<pre>` in the source HTML, in
21
+ * document order.
22
+ */
23
+ export async function formatCodeBlocks(wordDocument, codeBlocks) {
24
+ const zip = await JSZip.loadAsync(await wordDocument.arrayBuffer());
25
+ const documentEntry = zip.file('word/document.xml');
26
+ if (!documentEntry) {
27
+ throw new Error('Cannot format code blocks: document contains no word/document.xml');
28
+ }
29
+ const documentXml = await documentEntry.async('string');
30
+ const formatted = formatDocumentXml(documentXml, codeBlocks);
31
+ if (formatted === documentXml) {
32
+ return wordDocument;
33
+ }
34
+ zip.file('word/document.xml', formatted);
35
+ const patched = await zip.generateAsync({ type: 'arraybuffer' });
36
+ return new Blob([patched], { type: wordDocument.type });
37
+ }
38
+ /** Exported for testing. */
39
+ export function formatDocumentXml(documentXml, codeBlocks) {
40
+ const dom = new DOMParser().parseFromString(documentXml, 'application/xml');
41
+ let changed = false;
42
+ // The generator emits one paragraph per <pre>, in source order, so a single
43
+ // forward pass pairs each code block with the next paragraph of equal text.
44
+ // Whitespace is ignored because the generator may trim or collapse it. A
45
+ // plain paragraph can repeat a code block's text, so a match also needs every
46
+ // run to name a font, as the generator does for <pre> but not for body text.
47
+ // Inline code names CODE_FONT itself (see prepareHtmlForDocx), which the
48
+ // generator never uses for <pre>, so those runs don't count.
49
+ const pending = codeBlocks.map(compact).filter((text) => text !== '');
50
+ for (const paragraph of Array.from(dom.getElementsByTagNameNS(W_NS, 'p'))) {
51
+ if (pending.length === 0) {
52
+ break;
53
+ }
54
+ if (compact(paragraphText(paragraph)) === pending[0] && hasExplicitFonts(paragraph)) {
55
+ pending.shift();
56
+ setCodeFont(paragraph);
57
+ changed = true;
58
+ }
59
+ }
60
+ for (const text of Array.from(dom.getElementsByTagNameNS(W_NS, 't'))) {
61
+ changed = expandLineBreaks(text) || changed;
62
+ }
63
+ if (!changed) {
64
+ return documentXml;
65
+ }
66
+ return keepXmlDeclaration(documentXml, new XMLSerializer().serializeToString(dom));
67
+ }
68
+ function compact(text) {
69
+ return text.replace(/\s+/g, '');
70
+ }
71
+ function paragraphText(paragraph) {
72
+ return Array.from(paragraph.getElementsByTagNameNS(W_NS, 't'))
73
+ .map((text) => text.textContent ?? '')
74
+ .join('');
75
+ }
76
+ function hasExplicitFonts(paragraph) {
77
+ return textRuns(paragraph).every((run) => {
78
+ const rFonts = firstChild(run, 'rPr')?.getElementsByTagNameNS(W_NS, 'rFonts')[0];
79
+ const font = rFonts?.getAttributeNS(W_NS, 'ascii');
80
+ return Boolean(font) && font !== CODE_FONT;
81
+ });
82
+ }
83
+ function textRuns(paragraph) {
84
+ return Array.from(paragraph.getElementsByTagNameNS(W_NS, 'r')).filter((run) => run.getElementsByTagNameNS(W_NS, 't').length > 0);
85
+ }
86
+ function setCodeFont(paragraph) {
87
+ const document = paragraph.ownerDocument;
88
+ for (const run of textRuns(paragraph)) {
89
+ let rPr = firstChild(run, 'rPr');
90
+ if (!rPr) {
91
+ rPr = run.insertBefore(document.createElementNS(W_NS, 'w:rPr'), run.firstChild);
92
+ }
93
+ // <w:rFonts> comes first in <w:rPr>.
94
+ let rFonts = firstChild(rPr, 'rFonts');
95
+ if (!rFonts) {
96
+ rFonts = rPr.insertBefore(document.createElementNS(W_NS, 'w:rFonts'), rPr.firstChild);
97
+ }
98
+ for (const attribute of THEME_FONT_ATTRIBUTES) {
99
+ rFonts.removeAttributeNS(W_NS, attribute);
100
+ }
101
+ for (const attribute of ['ascii', 'hAnsi', 'eastAsia']) {
102
+ rFonts.setAttributeNS(W_NS, `w:${attribute}`, CODE_FONT);
103
+ }
104
+ }
105
+ }
106
+ function firstChild(parent, localName) {
107
+ return Array.from(parent.children).find((child) => child.namespaceURI === W_NS && child.localName === localName);
108
+ }
109
+ /**
110
+ * Replaces one `<w:t>a\nb</w:t>` with `<w:t>a</w:t><w:br/><w:t>b</w:t>`.
111
+ * Returns whether anything changed.
112
+ */
113
+ function expandLineBreaks(text) {
114
+ const lines = (text.textContent ?? '').split('\n');
115
+ if (lines.length < 2) {
116
+ return false;
117
+ }
118
+ const document = text.ownerDocument;
119
+ const run = text.parentNode;
120
+ for (const [index, line] of lines.entries()) {
121
+ if (index > 0) {
122
+ run.insertBefore(document.createElementNS(W_NS, 'w:br'), text);
123
+ }
124
+ if (line !== '') {
125
+ const textElement = document.createElementNS(W_NS, 'w:t');
126
+ textElement.setAttributeNS(XML_NS, 'xml:space', 'preserve');
127
+ textElement.textContent = line;
128
+ run.insertBefore(textElement, text);
129
+ }
130
+ }
131
+ run.removeChild(text);
132
+ return true;
133
+ }
134
+ //# sourceMappingURL=docx-code-blocks.js.map
@@ -0,0 +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,EAAE,kBAAkB,EAAE,iBAAiB,IAAI,IAAI,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAEtF,OAAO,EAAE,SAAS,EAAE,CAAC;AAErB,+DAA+D;AAC/D,MAAM,qBAAqB,GAAG,CAAC,YAAY,EAAE,eAAe,EA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YAAY,CAAC,QAAQ,CAAC,eAAe,CAAC,IAAI,EAAE,MAAM,CAAC,EAAE,IAAI,CAAC,CAAC;QACjE,CAAC;QACD,IAAI,IAAI,KAAK,EAAE,EAAE,CAAC;YAChB,MAAM,WAAW,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 { keepXmlDeclaration, WORDPROCESSING_NS as W_NS, XML_NS } 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 *\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 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"]}
@@ -0,0 +1,15 @@
1
+ import type { FontPreset } from './font-presets.js';
2
+ /**
3
+ * Rewrites the fonts, sizes and paragraph spacing of an already generated .docx.
4
+ *
5
+ * `html-to-docx` only ever writes `w:ascii`, which WinWord applies to Latin
6
+ * characters and digits; Chinese characters fall back to the theme font. The
7
+ * East Asian slots are set here instead, so this stays out of the way of the
8
+ * default conversion output.
9
+ */
10
+ export declare function applyFontPreset(wordDocument: Blob, preset: FontPreset): Promise<Blob>;
11
+ /**
12
+ * Applies `preset` to the document default run properties and to the six
13
+ * heading styles of a styles.xml part.
14
+ */
15
+ export declare function patchStylesXml(stylesXml: string, preset: FontPreset): string;
@@ -0,0 +1,116 @@
1
+ import JSZip from 'jszip';
2
+ import { keepXmlDeclaration, WORDPROCESSING_NS as W_NS } from './xml-part.js';
3
+ /** Theme slots WinWord prefers over explicitly named fonts. */
4
+ const THEME_FONT_ATTRIBUTES = ['asciiTheme', 'eastAsiaTheme', 'hAnsiTheme', 'cstheme'];
5
+ /**
6
+ * `<w:line>` is ignored while the rule is auto, but WinWord still writes 240
7
+ * twips, so the preset writes the pair Word itself produces.
8
+ */
9
+ const LINE_SPACING = {
10
+ single: { line: '240', rule: 'auto' },
11
+ };
12
+ /**
13
+ * Rewrites the fonts, sizes and paragraph spacing of an already generated .docx.
14
+ *
15
+ * `html-to-docx` only ever writes `w:ascii`, which WinWord applies to Latin
16
+ * characters and digits; Chinese characters fall back to the theme font. The
17
+ * East Asian slots are set here instead, so this stays out of the way of the
18
+ * default conversion output.
19
+ */
20
+ export async function applyFontPreset(wordDocument, preset) {
21
+ const zip = await JSZip.loadAsync(await wordDocument.arrayBuffer());
22
+ const stylesEntry = zip.file('word/styles.xml');
23
+ if (!stylesEntry) {
24
+ throw new Error('Cannot apply font preset: document contains no word/styles.xml');
25
+ }
26
+ const stylesXml = await stylesEntry.async('string');
27
+ zip.file('word/styles.xml', patchStylesXml(stylesXml, preset));
28
+ const patched = await zip.generateAsync({ type: 'arraybuffer' });
29
+ return new Blob([patched], { type: wordDocument.type });
30
+ }
31
+ /**
32
+ * Applies `preset` to the document default run properties and to the six
33
+ * heading styles of a styles.xml part.
34
+ */
35
+ export function patchStylesXml(stylesXml, preset) {
36
+ const dom = new DOMParser().parseFromString(stylesXml, 'application/xml');
37
+ const docDefaults = requireElement(dom, 'docDefaults');
38
+ applyLevelStyle(docDefaults, preset.body, preset.paragraph);
39
+ const styles = Array.from(dom.getElementsByTagNameNS(W_NS, 'style'));
40
+ for (const style of styles) {
41
+ const heading = /^Heading([1-6])$/.exec(style.getAttributeNS(W_NS, 'styleId') ?? '');
42
+ if (heading) {
43
+ applyLevelStyle(style, preset.headings[Number(heading[1]) - 1], preset.paragraph);
44
+ }
45
+ }
46
+ return keepXmlDeclaration(stylesXml, new XMLSerializer().serializeToString(dom));
47
+ }
48
+ function applyLevelStyle(scope, style, paragraph) {
49
+ const rPr = runPropertiesOf(scope);
50
+ const rFonts = childOrCreate(rPr, 'rFonts', 'first');
51
+ for (const attribute of THEME_FONT_ATTRIBUTES) {
52
+ rFonts.removeAttributeNS(W_NS, attribute);
53
+ }
54
+ rFonts.setAttributeNS(W_NS, 'w:ascii', style.latin);
55
+ rFonts.setAttributeNS(W_NS, 'w:hAnsi', style.latin);
56
+ rFonts.setAttributeNS(W_NS, 'w:eastAsia', style.eastAsia);
57
+ for (const child of children(rPr)) {
58
+ if (child.localName === 'b' || child.localName === 'bCs') {
59
+ child.remove();
60
+ }
61
+ }
62
+ if (style.bold) {
63
+ rPr.insertBefore(rPr.ownerDocument.createElementNS(W_NS, 'w:b'), rFonts.nextSibling);
64
+ }
65
+ // <w:sz> is measured in half points.
66
+ const size = String(style.sizePt * 2);
67
+ childOrCreate(rPr, 'sz', 'last').setAttributeNS(W_NS, 'w:val', size);
68
+ childOrCreate(rPr, 'szCs', 'last').setAttributeNS(W_NS, 'w:val', size);
69
+ const spacing = childOrCreate(paragraphPropertiesOf(scope), 'spacing', 'first');
70
+ spacing.setAttributeNS(W_NS, 'w:before', String(paragraph.beforePt * 20));
71
+ spacing.setAttributeNS(W_NS, 'w:after', String(paragraph.afterPt * 20));
72
+ const line = LINE_SPACING[paragraph.lineSpacing];
73
+ spacing.setAttributeNS(W_NS, 'w:line', line.line);
74
+ spacing.setAttributeNS(W_NS, 'w:lineRule', line.rule);
75
+ }
76
+ function runPropertiesOf(parent) {
77
+ const container = parent.localName === 'docDefaults'
78
+ ? childOrCreate(parent, 'rPrDefault', 'first')
79
+ : parent;
80
+ // In a <w:style> the run properties go last, after any <w:pPr>.
81
+ return childOrCreate(container, 'rPr', 'last');
82
+ }
83
+ function paragraphPropertiesOf(parent) {
84
+ if (parent.localName === 'docDefaults') {
85
+ const pPrDefault = childOrCreate(parent, 'pPrDefault', 'last');
86
+ return childOrCreate(pPrDefault, 'pPr', 'first');
87
+ }
88
+ const existing = children(parent).find((child) => child.localName === 'pPr');
89
+ if (existing) {
90
+ return existing;
91
+ }
92
+ // In a <w:style> the paragraph properties go before the run properties.
93
+ const created = parent.ownerDocument.createElementNS(W_NS, 'w:pPr');
94
+ return parent.insertBefore(created, runPropertiesOf(parent));
95
+ }
96
+ function children(element) {
97
+ return Array.from(element.children).filter((child) => child.namespaceURI === W_NS);
98
+ }
99
+ function childOrCreate(parent, localName, position) {
100
+ const existing = children(parent).find((child) => child.localName === localName);
101
+ if (existing) {
102
+ return existing;
103
+ }
104
+ const created = parent.ownerDocument.createElementNS(W_NS, `w:${localName}`);
105
+ return position === 'first'
106
+ ? parent.insertBefore(created, parent.firstChild)
107
+ : parent.appendChild(created);
108
+ }
109
+ function requireElement(dom, localName) {
110
+ const element = dom.getElementsByTagNameNS(W_NS, localName)[0];
111
+ if (!element) {
112
+ throw new Error(`Cannot apply font preset: styles.xml has no <w:${localName}> element`);
113
+ }
114
+ return element;
115
+ }
116
+ //# sourceMappingURL=docx-font-preset.js.map