markdown-to-word 0.0.0-stage → 0.2.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 +21 -0
- package/README.md +145 -2
- package/build/buffer-global.d.ts +1 -0
- package/build/buffer-global.js +9 -0
- package/build/buffer-global.js.map +1 -0
- package/build/converter.d.ts +20 -0
- package/build/converter.js +111 -0
- package/build/converter.js.map +1 -0
- package/build/docx-code-blocks.d.ts +24 -0
- package/build/docx-code-blocks.js +142 -0
- package/build/docx-code-blocks.js.map +1 -0
- package/build/docx-font-preset.d.ts +45 -0
- package/build/docx-font-preset.js +268 -0
- package/build/docx-font-preset.js.map +1 -0
- package/build/docx-html.d.ts +29 -0
- package/build/docx-html.js +75 -0
- package/build/docx-html.js.map +1 -0
- package/build/docx-structure.d.ts +22 -0
- package/build/docx-structure.js +99 -0
- package/build/docx-structure.js.map +1 -0
- package/build/font-presets.d.ts +94 -0
- package/build/font-presets.js +72 -0
- package/build/font-presets.js.map +1 -0
- package/build/main.d.ts +3 -0
- package/build/main.js +7 -0
- package/build/main.js.map +1 -0
- package/build/markdown-parser.d.ts +25 -0
- package/build/markdown-parser.js +95 -0
- package/build/markdown-parser.js.map +1 -0
- package/build/node.d.ts +1 -0
- package/build/node.js +15 -0
- package/build/node.js.map +1 -0
- package/build/xml-part.d.ts +14 -0
- package/build/xml-part.js +76 -0
- package/build/xml-part.js.map +1 -0
- package/package.json +92 -4
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,146 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Markdown to Word
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](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
|
+
| `` | 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 (always shown on the Chinese page, and elsewhere once the pasted text is mostly Chinese) rewrites the generated document to the layout of GB/T 9704-2012 《党政机关公文格式》. 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 | 三号 (16pt) | 仿宋 (bold) | Times New Roman |
|
|
46
|
+
| Heading 5-6 | 三号 (16pt) | 仿宋 | Times New Roman |
|
|
47
|
+
|
|
48
|
+
The preset also sets the page:
|
|
49
|
+
|
|
50
|
+
- **Paper and margins (5.1, 5.2.1):** A4, with a 37mm top margin (天头) and a 28mm left margin (订口) around a 156 × 225mm text block (版心).
|
|
51
|
+
- **22 lines of 28 characters (5.2.3):** a Word document grid (文档网格) with exact line spacing at its pitch, 28.95pt. Widow control (孤行控制) is off, so it can't push a line to the next page and leave 21.
|
|
52
|
+
- **Indent (7.3.3):** paragraphs, and the headings below the title, start two characters in (首行缩进 2 字符). Table cells, list items, and code blocks don't.
|
|
53
|
+
- **Title (7.3.1):** Heading 1 is centered.
|
|
54
|
+
- **Spacing:** 段前段后 0 行 on every level.
|
|
55
|
+
|
|
56
|
+
The app remembers your choice in this browser, and suggests the preset when the text you paste is mostly Chinese.
|
|
57
|
+
|
|
58
|
+
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. Some of the choices go beyond the standard:
|
|
59
|
+
|
|
60
|
+
- The standard names no Latin font. Times New Roman for Latin letters and digits is common practice.
|
|
61
|
+
- The standard says 小标宋体, not 方正小标宋简体 specifically. 方正小标宋简体 is a commercial Founder font that most machines don't have, so Word substitutes another font for the title unless it's installed.
|
|
62
|
+
- Heading 4, the standard's third level (1.), is bold, which the standard doesn't ask for: it generally sets its third and fourth levels in plain 仿宋. Bolding that level is how these documents are written in practice. Headings 5 and 6 stay plain and rely on their numbers ((1) and ①) to stand out, as in a printed 公文.
|
|
63
|
+
|
|
64
|
+
Page numbers (7.5) aren't added yet; see [#106](https://github.com/benbalter/markdown-to-word-js/issues/106). Neither are the red separator line and the other 版头 elements, which Markdown has no way to express.
|
|
65
|
+
|
|
66
|
+
Programmatically:
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
import {
|
|
70
|
+
convertMarkdownToWord,
|
|
71
|
+
CHINESE_OFFICIAL_DOC_FONTS,
|
|
72
|
+
} from 'markdown-to-word';
|
|
73
|
+
|
|
74
|
+
const blob = await convertMarkdownToWord(markdown, {
|
|
75
|
+
fontPreset: CHINESE_OFFICIAL_DOC_FONTS,
|
|
76
|
+
});
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
`pageMargins`, when you also pass it, takes precedence over the preset's margins; the line grid is fitted to the margins the document ends up with.
|
|
80
|
+
|
|
81
|
+
## Privacy
|
|
82
|
+
|
|
83
|
+
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/).
|
|
84
|
+
|
|
85
|
+
## Limitations
|
|
86
|
+
|
|
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). Other images, images under 1 KB (html-to-docx's minimum), and local file paths are left out.
|
|
88
|
+
- Complex raw HTML inside Markdown may not convert cleanly, and advanced Word features (comments, tracked changes, page layout) aren't produced.
|
|
89
|
+
- Very large documents can be slow, since everything runs in the browser. Files are limited to 5 MB.
|
|
90
|
+
- The site works in current versions of Chrome, Edge, Firefox, and Safari. The end-to-end tests run in Chrome.
|
|
91
|
+
|
|
92
|
+
## Use it from code
|
|
93
|
+
|
|
94
|
+
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):
|
|
95
|
+
|
|
96
|
+
```bash
|
|
97
|
+
npm install markdown-to-word
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
`convertMarkdownToWord` returns the `.docx` as a `Blob`:
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
import { writeFile } from 'node:fs/promises';
|
|
104
|
+
import { convertMarkdownToWord } from 'markdown-to-word';
|
|
105
|
+
|
|
106
|
+
const blob = await convertMarkdownToWord('# Hello\n\nFrom **Markdown**.', {
|
|
107
|
+
pageMargins: { top: 1, right: 1, bottom: 1, left: 1 }, // inches
|
|
108
|
+
});
|
|
109
|
+
await writeFile('hello.docx', Buffer.from(await blob.arrayBuffer()));
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
In a browser, hand the `Blob` to a download link with `URL.createObjectURL(blob)`.
|
|
113
|
+
|
|
114
|
+
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.
|
|
115
|
+
|
|
116
|
+
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
|
+
|
|
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.
|
|
119
|
+
|
|
120
|
+
## Development
|
|
121
|
+
|
|
122
|
+
Requires Node.js 22.12 or later (`.nvmrc` pins the version CI uses).
|
|
123
|
+
|
|
124
|
+
```bash
|
|
125
|
+
git clone https://github.com/benbalter/markdown-to-word-js.git
|
|
126
|
+
cd markdown-to-word-js
|
|
127
|
+
npm install
|
|
128
|
+
npm run dev # http://localhost:4321
|
|
129
|
+
npm run build # static site in dist/
|
|
130
|
+
npm test # unit tests; npm run test:e2e for Playwright
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md) for the project layout and checks.
|
|
134
|
+
|
|
135
|
+
- **Site:** [Astro](https://astro.build) with [Tailwind CSS](https://tailwindcss.com), sharing word2md.com's design system.
|
|
136
|
+
- **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.
|
|
137
|
+
- **Translations:** the UI is ready for more languages; see [web/i18n/README.md](web/i18n/README.md).
|
|
138
|
+
- **Hosting:** Cloudflare Workers Static Assets. A push to `main` builds, runs the tests, and deploys; see [docs/cloudflare.md](docs/cloudflare.md).
|
|
139
|
+
|
|
140
|
+
## Contributing
|
|
141
|
+
|
|
142
|
+
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.
|
|
143
|
+
|
|
144
|
+
## License
|
|
145
|
+
|
|
146
|
+
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,20 @@
|
|
|
1
|
+
import './buffer-global.js';
|
|
2
|
+
import { type FontPreset } from './font-presets.js';
|
|
3
|
+
export interface ConversionOptions {
|
|
4
|
+
/** Page margins in inches. Overrides the margins of `fontPreset.page`. */
|
|
5
|
+
pageMargins?: {
|
|
6
|
+
top: number;
|
|
7
|
+
right: number;
|
|
8
|
+
bottom: number;
|
|
9
|
+
left: number;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* Rewrites the document fonts, and the page layout if the preset has one.
|
|
13
|
+
* Omit to keep the default styling.
|
|
14
|
+
*/
|
|
15
|
+
fontPreset?: FontPreset;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Convert markdown text to a Word document blob using HTML as an intermediary format
|
|
19
|
+
*/
|
|
20
|
+
export declare function convertMarkdownToWord(markdown: string, options?: ConversionOptions): Promise<Blob>;
|
|
@@ -0,0 +1,111 @@
|
|
|
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 { mmToTwips } from './font-presets.js';
|
|
6
|
+
import { parseMarkdownToHtml, extractTitle } from './markdown-parser.js';
|
|
7
|
+
/**
|
|
8
|
+
* Convert markdown text to a Word document blob using HTML as an intermediary format
|
|
9
|
+
*/
|
|
10
|
+
export async function convertMarkdownToWord(markdown, options = {}) {
|
|
11
|
+
try {
|
|
12
|
+
const html = parseMarkdownToHtml(markdown);
|
|
13
|
+
const documentOptions = {
|
|
14
|
+
// The generator's default border size is 0, so tables had no grid lines.
|
|
15
|
+
// A thin light gray rule (size in eighths of a point) matches how
|
|
16
|
+
// GitHub draws tables.
|
|
17
|
+
table: { borderOptions: { size: 4, stroke: 'single', color: 'BFBFBF' } },
|
|
18
|
+
};
|
|
19
|
+
const title = extractTitle(markdown);
|
|
20
|
+
if (title) {
|
|
21
|
+
documentOptions.title = title;
|
|
22
|
+
}
|
|
23
|
+
const page = options.fontPreset?.page;
|
|
24
|
+
if (page) {
|
|
25
|
+
documentOptions.pageSize = {
|
|
26
|
+
width: mmToTwips(page.widthMm),
|
|
27
|
+
height: mmToTwips(page.heightMm),
|
|
28
|
+
};
|
|
29
|
+
documentOptions.margins = {
|
|
30
|
+
top: mmToTwips(page.marginsMm.top),
|
|
31
|
+
right: mmToTwips(page.marginsMm.right),
|
|
32
|
+
bottom: mmToTwips(page.marginsMm.bottom),
|
|
33
|
+
left: mmToTwips(page.marginsMm.left),
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
if (options.pageMargins) {
|
|
37
|
+
// Convert inches to twips (1 inch = 1440 twips)
|
|
38
|
+
documentOptions.margins = {
|
|
39
|
+
top: options.pageMargins.top * 1440,
|
|
40
|
+
right: options.pageMargins.right * 1440,
|
|
41
|
+
bottom: options.pageMargins.bottom * 1440,
|
|
42
|
+
left: options.pageMargins.left * 1440,
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
const result = await HTMLtoDOCX(prepareHtmlForDocx(html), null, documentOptions);
|
|
46
|
+
// HTMLtoDOCX returns Blob in browser, Buffer/ArrayBuffer in Node.js
|
|
47
|
+
const generated = result instanceof Blob ? result : new Blob([result]);
|
|
48
|
+
// The patches rewrite the .docx zip with JSZip. html-to-docx bundles its own
|
|
49
|
+
// copy, so ours is a second one; load it only when a patch actually applies.
|
|
50
|
+
// Code blocks are broken in the generator output itself, so they are fixed
|
|
51
|
+
// whether or not a font preset is requested.
|
|
52
|
+
let wordDocument = generated;
|
|
53
|
+
if (html.includes('<pre')) {
|
|
54
|
+
const codeBlocks = codeBlockTexts(html);
|
|
55
|
+
wordDocument = await patchOrKeep(wordDocument, 'code block', async (document) => {
|
|
56
|
+
const { formatCodeBlocks } = await import('./docx-code-blocks.js');
|
|
57
|
+
return formatCodeBlocks(document, codeBlocks);
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
if (html.includes('<hr') || html.includes('<table')) {
|
|
61
|
+
const structure = documentStructure(html);
|
|
62
|
+
wordDocument = await patchOrKeep(wordDocument, 'structure', async (document) => {
|
|
63
|
+
const { patchStructure } = await import('./docx-structure.js');
|
|
64
|
+
return patchStructure(document, structure);
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
const { fontPreset } = options;
|
|
68
|
+
if (fontPreset) {
|
|
69
|
+
wordDocument = await patchOrKeep(wordDocument, 'font preset', async (document) => {
|
|
70
|
+
const { applyFontPreset } = await import('./docx-font-preset.js');
|
|
71
|
+
return applyFontPreset(document, fontPreset);
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
return wordDocument;
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
console.error('Word document generation error:', error);
|
|
78
|
+
throw new Error('Failed to generate Word document', { cause: error });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
/** The text of each `<pre>` in `html`, in document order. */
|
|
82
|
+
function codeBlockTexts(html) {
|
|
83
|
+
const dom = new DOMParser().parseFromString(html, 'text/html');
|
|
84
|
+
return Array.from(dom.querySelectorAll('pre'), (pre) => pre.textContent ?? '');
|
|
85
|
+
}
|
|
86
|
+
/** The rules and table header rows in `html`, for the structure patch. */
|
|
87
|
+
function documentStructure(html) {
|
|
88
|
+
const dom = new DOMParser().parseFromString(html, 'text/html');
|
|
89
|
+
return {
|
|
90
|
+
rules: dom.querySelectorAll('hr').length,
|
|
91
|
+
headerRows: Array.from(dom.querySelectorAll('table'), (table) => {
|
|
92
|
+
const firstRow = table.querySelector('tr');
|
|
93
|
+
return Boolean(table.tHead) || Boolean(firstRow && firstRow.querySelector('td') === null);
|
|
94
|
+
}),
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* The patches polish a document html-to-docx already produced, so a failure in
|
|
99
|
+
* one (including its chunk failing to load) keeps the unpatched document
|
|
100
|
+
* rather than failing the whole conversion.
|
|
101
|
+
*/
|
|
102
|
+
async function patchOrKeep(wordDocument, name, patch) {
|
|
103
|
+
try {
|
|
104
|
+
return await patch(wordDocument);
|
|
105
|
+
}
|
|
106
|
+
catch (error) {
|
|
107
|
+
console.warn(`Skipped the ${name} patch; keeping the unpatched document:`, error);
|
|
108
|
+
return wordDocument;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
//# 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;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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AAC;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 { 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}"]}
|
|
@@ -0,0 +1,24 @@
|
|
|
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
|
+
* - Indent: the same paragraphs get an explicit zero first-line indent, so a
|
|
16
|
+
* preset that indents body text (the 公文 one) leaves the first code line
|
|
17
|
+
* aligned with the rest.
|
|
18
|
+
*
|
|
19
|
+
* @param codeBlocks The text content of each `<pre>` in the source HTML, in
|
|
20
|
+
* document order.
|
|
21
|
+
*/
|
|
22
|
+
export declare function formatCodeBlocks(wordDocument: Blob, codeBlocks: string[]): Promise<Blob>;
|
|
23
|
+
/** Exported for testing. */
|
|
24
|
+
export declare function formatDocumentXml(documentXml: string, codeBlocks: string[]): string;
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import JSZip from 'jszip';
|
|
2
|
+
import { CODE_FONT } from './docx-html.js';
|
|
3
|
+
import { keepXmlDeclaration, paragraphProperty, 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
|
+
* - Indent: the same paragraphs get an explicit zero first-line indent, so a
|
|
20
|
+
* preset that indents body text (the 公文 one) leaves the first code line
|
|
21
|
+
* aligned with the rest.
|
|
22
|
+
*
|
|
23
|
+
* @param codeBlocks The text content of each `<pre>` in the source HTML, in
|
|
24
|
+
* document order.
|
|
25
|
+
*/
|
|
26
|
+
export async function formatCodeBlocks(wordDocument, codeBlocks) {
|
|
27
|
+
const zip = await JSZip.loadAsync(await wordDocument.arrayBuffer());
|
|
28
|
+
const documentEntry = zip.file('word/document.xml');
|
|
29
|
+
if (!documentEntry) {
|
|
30
|
+
throw new Error('Cannot format code blocks: document contains no word/document.xml');
|
|
31
|
+
}
|
|
32
|
+
const documentXml = await documentEntry.async('string');
|
|
33
|
+
const formatted = formatDocumentXml(documentXml, codeBlocks);
|
|
34
|
+
if (formatted === documentXml) {
|
|
35
|
+
return wordDocument;
|
|
36
|
+
}
|
|
37
|
+
zip.file('word/document.xml', formatted);
|
|
38
|
+
const patched = await zip.generateAsync({ type: 'arraybuffer' });
|
|
39
|
+
return new Blob([patched], { type: wordDocument.type });
|
|
40
|
+
}
|
|
41
|
+
/** Exported for testing. */
|
|
42
|
+
export function formatDocumentXml(documentXml, codeBlocks) {
|
|
43
|
+
const dom = new DOMParser().parseFromString(documentXml, 'application/xml');
|
|
44
|
+
let changed = false;
|
|
45
|
+
// The generator emits one paragraph per <pre>, in source order, so a single
|
|
46
|
+
// forward pass pairs each code block with the next paragraph of equal text.
|
|
47
|
+
// Whitespace is ignored because the generator may trim or collapse it. A
|
|
48
|
+
// plain paragraph can repeat a code block's text, so a match also needs every
|
|
49
|
+
// run to name a font, as the generator does for <pre> but not for body text.
|
|
50
|
+
// Inline code names CODE_FONT itself (see prepareHtmlForDocx), which the
|
|
51
|
+
// generator never uses for <pre>, so those runs don't count.
|
|
52
|
+
const pending = codeBlocks.map(compact).filter((text) => text !== '');
|
|
53
|
+
for (const paragraph of Array.from(dom.getElementsByTagNameNS(W_NS, 'p'))) {
|
|
54
|
+
if (pending.length === 0) {
|
|
55
|
+
break;
|
|
56
|
+
}
|
|
57
|
+
if (compact(paragraphText(paragraph)) === pending[0] && hasExplicitFonts(paragraph)) {
|
|
58
|
+
pending.shift();
|
|
59
|
+
setCodeFont(paragraph);
|
|
60
|
+
changed = true;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
for (const text of Array.from(dom.getElementsByTagNameNS(W_NS, 't'))) {
|
|
64
|
+
changed = expandLineBreaks(text) || changed;
|
|
65
|
+
}
|
|
66
|
+
if (!changed) {
|
|
67
|
+
return documentXml;
|
|
68
|
+
}
|
|
69
|
+
return keepXmlDeclaration(documentXml, new XMLSerializer().serializeToString(dom));
|
|
70
|
+
}
|
|
71
|
+
function compact(text) {
|
|
72
|
+
return text.replace(/\s+/g, '');
|
|
73
|
+
}
|
|
74
|
+
function paragraphText(paragraph) {
|
|
75
|
+
return Array.from(paragraph.getElementsByTagNameNS(W_NS, 't'))
|
|
76
|
+
.map((text) => text.textContent ?? '')
|
|
77
|
+
.join('');
|
|
78
|
+
}
|
|
79
|
+
function hasExplicitFonts(paragraph) {
|
|
80
|
+
return textRuns(paragraph).every((run) => {
|
|
81
|
+
const rFonts = firstChild(run, 'rPr')?.getElementsByTagNameNS(W_NS, 'rFonts')[0];
|
|
82
|
+
const font = rFonts?.getAttributeNS(W_NS, 'ascii');
|
|
83
|
+
return Boolean(font) && font !== CODE_FONT;
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
function textRuns(paragraph) {
|
|
87
|
+
return Array.from(paragraph.getElementsByTagNameNS(W_NS, 'r')).filter((run) => run.getElementsByTagNameNS(W_NS, 't').length > 0);
|
|
88
|
+
}
|
|
89
|
+
function setCodeFont(paragraph) {
|
|
90
|
+
const document = paragraph.ownerDocument;
|
|
91
|
+
let pPr = firstChild(paragraph, 'pPr');
|
|
92
|
+
if (!pPr) {
|
|
93
|
+
pPr = paragraph.insertBefore(document.createElementNS(W_NS, 'w:pPr'), paragraph.firstChild);
|
|
94
|
+
}
|
|
95
|
+
paragraphProperty(pPr, 'ind').setAttributeNS(W_NS, 'w:firstLine', '0');
|
|
96
|
+
for (const run of textRuns(paragraph)) {
|
|
97
|
+
let rPr = firstChild(run, 'rPr');
|
|
98
|
+
if (!rPr) {
|
|
99
|
+
rPr = run.insertBefore(document.createElementNS(W_NS, 'w:rPr'), run.firstChild);
|
|
100
|
+
}
|
|
101
|
+
// <w:rFonts> comes first in <w:rPr>.
|
|
102
|
+
let rFonts = firstChild(rPr, 'rFonts');
|
|
103
|
+
if (!rFonts) {
|
|
104
|
+
rFonts = rPr.insertBefore(document.createElementNS(W_NS, 'w:rFonts'), rPr.firstChild);
|
|
105
|
+
}
|
|
106
|
+
for (const attribute of THEME_FONT_ATTRIBUTES) {
|
|
107
|
+
rFonts.removeAttributeNS(W_NS, attribute);
|
|
108
|
+
}
|
|
109
|
+
for (const attribute of ['ascii', 'hAnsi', 'eastAsia']) {
|
|
110
|
+
rFonts.setAttributeNS(W_NS, `w:${attribute}`, CODE_FONT);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
function firstChild(parent, localName) {
|
|
115
|
+
return Array.from(parent.children).find((child) => child.namespaceURI === W_NS && child.localName === localName);
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Replaces one `<w:t>a\nb</w:t>` with `<w:t>a</w:t><w:br/><w:t>b</w:t>`.
|
|
119
|
+
* Returns whether anything changed.
|
|
120
|
+
*/
|
|
121
|
+
function expandLineBreaks(text) {
|
|
122
|
+
const lines = (text.textContent ?? '').split('\n');
|
|
123
|
+
if (lines.length < 2) {
|
|
124
|
+
return false;
|
|
125
|
+
}
|
|
126
|
+
const document = text.ownerDocument;
|
|
127
|
+
const run = text.parentNode;
|
|
128
|
+
for (const [index, line] of lines.entries()) {
|
|
129
|
+
if (index > 0) {
|
|
130
|
+
run.insertBefore(document.createElementNS(W_NS, 'w:br'), text);
|
|
131
|
+
}
|
|
132
|
+
if (line !== '') {
|
|
133
|
+
const textElement = document.createElementNS(W_NS, 'w:t');
|
|
134
|
+
textElement.setAttributeNS(XML_NS, 'xml:space', 'preserve');
|
|
135
|
+
textElement.textContent = line;
|
|
136
|
+
run.insertBefore(textElement, text);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
run.removeChild(text);
|
|
140
|
+
return true;
|
|
141
|
+
}
|
|
142
|
+
//# sourceMappingURL=docx-code-blocks.js.map
|
|
@@ -0,0 +1 @@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AAC","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"]}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { FontPreset } from './font-presets.js';
|
|
2
|
+
/** Word's document grid, in the units of `<w:docGrid>`. */
|
|
3
|
+
interface Grid {
|
|
4
|
+
/** Line pitch in twips. */
|
|
5
|
+
linePitch: number;
|
|
6
|
+
/** Character pitch relative to the body font size, in 1/4096 point. */
|
|
7
|
+
charSpace: number;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Rewrites the fonts, sizes, paragraph spacing and page grid of an already
|
|
11
|
+
* generated .docx.
|
|
12
|
+
*
|
|
13
|
+
* `html-to-docx` only ever writes `w:ascii`, which WinWord applies to Latin
|
|
14
|
+
* characters and digits; Chinese characters fall back to the theme font. The
|
|
15
|
+
* East Asian slots are set here instead, so this stays out of the way of the
|
|
16
|
+
* default conversion output.
|
|
17
|
+
*
|
|
18
|
+
* The grid is measured from the page the document actually has, so it still
|
|
19
|
+
* fits when `pageMargins` overrode the preset's margins.
|
|
20
|
+
*/
|
|
21
|
+
export declare function applyFontPreset(wordDocument: Blob, preset: FontPreset): Promise<Blob>;
|
|
22
|
+
/**
|
|
23
|
+
* Applies `preset` to the document default run properties and to the six
|
|
24
|
+
* heading styles of a styles.xml part. `grid` is the page grid that
|
|
25
|
+
* `patchDocumentXml` set, which `lineSpacing: 'grid'` takes its pitch from.
|
|
26
|
+
*/
|
|
27
|
+
export declare function patchStylesXml(stylesXml: string, preset: FontPreset, grid?: Grid | null): string;
|
|
28
|
+
/**
|
|
29
|
+
* Sets the page grid in the section properties of a document.xml part, and
|
|
30
|
+
* fixes up the paragraphs that the style-level layout would break:
|
|
31
|
+
*
|
|
32
|
+
* - The generator gives every paragraph `<w:spacing w:lineRule="auto"/>`.
|
|
33
|
+
* Spacing attributes inherit one at a time, so that lone `auto` combined
|
|
34
|
+
* with the style's exact line height would read as a multiple of 240 twips
|
|
35
|
+
* (about 2.4 lines). It is dropped when the preset uses grid spacing.
|
|
36
|
+
* - Exact line spacing would crop an inline image to one line, so paragraphs
|
|
37
|
+
* with a drawing keep single spacing; the grid then rounds them up to whole
|
|
38
|
+
* lines.
|
|
39
|
+
* - Table cells drop the first-line indent; it only crowds narrow columns.
|
|
40
|
+
*/
|
|
41
|
+
export declare function patchDocumentXml(documentXml: string, preset: FontPreset): {
|
|
42
|
+
xml: string;
|
|
43
|
+
grid: Grid | null;
|
|
44
|
+
};
|
|
45
|
+
export {};
|