markdown-to-word 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -17,24 +17,26 @@ The document is named after its first heading, which also becomes its title.
17
17
 
18
18
  ## What converts
19
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)) |
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
+ | `![images](https://example.com/a.png)` | 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
 
35
37
  ## Optional Font Presets
36
38
 
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:
39
+ 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
40
 
39
41
  | Level | Font size | Chinese characters | Latin letters and digits |
40
42
  | ----------- | ----------- | ------------------ | ------------------------ |
@@ -42,33 +44,54 @@ Conversions use Word's standard styling by default. Choosing **Chinese official
42
44
  | Heading 1 | 二号 (22pt) | 方正小标宋简体 | Times New Roman |
43
45
  | Heading 2 | 三号 (16pt) | 黑体 | Times New Roman |
44
46
  | Heading 3 | 三号 (16pt) | 楷体 | Times New Roman |
45
- | Heading 4-6 | 三号 (16pt) | 仿宋 (bold) | Times New Roman |
47
+ | Heading 4 | 三号 (16pt) | 仿宋 (bold) | Times New Roman |
48
+ | Heading 5-6 | 三号 (16pt) | 仿宋 | Times New Roman |
49
+
50
+ The preset also sets the page:
51
+
52
+ - **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 (版心).
53
+ - **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.
54
+ - **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.
55
+ - **Title (7.3.1):** Heading 1 is centered.
56
+ - **Spacing:** 段前段后 0 行 on every level.
46
57
 
47
58
  The app remembers your choice in this browser, and suggests the preset when the text you paste is mostly Chinese.
48
59
 
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.
60
+ 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:
50
61
 
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 磅.
62
+ - The standard names no Latin font. Times New Roman for Latin letters and digits is common practice.
63
+ - 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.
64
+ - 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 公文.
52
65
 
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).
66
+ 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.
54
67
 
55
68
  Programmatically:
56
69
 
57
70
  ```ts
58
- import { convertMarkdownToWord, CHINESE_OFFICIAL_DOC_FONTS } from 'markdown-to-word';
71
+ import {
72
+ convertMarkdownToWord,
73
+ CHINESE_OFFICIAL_DOC_FONTS,
74
+ } from 'markdown-to-word';
59
75
 
60
76
  const blob = await convertMarkdownToWord(markdown, {
61
77
  fontPreset: CHINESE_OFFICIAL_DOC_FONTS,
62
78
  });
63
79
  ```
64
80
 
81
+ `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.
82
+
65
83
  ## Privacy
66
84
 
67
85
  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
86
 
69
87
  ## Limitations
70
88
 
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.
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.
72
95
  - Complex raw HTML inside Markdown may not convert cleanly, and advanced Word features (comments, tracked changes, page layout) aren't produced.
73
96
  - Very large documents can be slow, since everything runs in the browser. Files are limited to 5 MB.
74
97
  - The site works in current versions of Chrome, Edge, Firefox, and Safari. The end-to-end tests run in Chrome.
@@ -99,7 +122,7 @@ The converter needs the DOM's `DOMParser` and `XMLSerializer`. Browsers have the
99
122
 
100
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.
101
124
 
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.
125
+ 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 (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.
103
126
 
104
127
  ## Development
105
128
 
@@ -1,14 +1,17 @@
1
1
  import './buffer-global.js';
2
- import type { FontPreset } from './font-presets.js';
2
+ import { type FontPreset } from './font-presets.js';
3
3
  export interface ConversionOptions {
4
- /** Page margins in inches. */
4
+ /** Page margins in inches. Overrides the margins of `fontPreset.page`. */
5
5
  pageMargins?: {
6
6
  top: number;
7
7
  right: number;
8
8
  bottom: number;
9
9
  left: number;
10
10
  };
11
- /** Rewrites the document fonts. Omit to keep the default styling. */
11
+ /**
12
+ * Rewrites the document fonts, and the page layout if the preset has one.
13
+ * Omit to keep the default styling.
14
+ */
12
15
  fontPreset?: FontPreset;
13
16
  }
14
17
  /**
@@ -2,13 +2,19 @@
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';
6
+ import { mmToTwips } from './font-presets.js';
5
7
  import { parseMarkdownToHtml, extractTitle } from './markdown-parser.js';
6
8
  /**
7
9
  * Convert markdown text to a Word document blob using HTML as an intermediary format
8
10
  */
9
11
  export async function convertMarkdownToWord(markdown, options = {}) {
10
12
  try {
11
- const html = parseMarkdownToHtml(markdown);
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
+ }
12
18
  const documentOptions = {
13
19
  // The generator's default border size is 0, so tables had no grid lines.
14
20
  // A thin light gray rule (size in eighths of a point) matches how
@@ -19,6 +25,19 @@ export async function convertMarkdownToWord(markdown, options = {}) {
19
25
  if (title) {
20
26
  documentOptions.title = title;
21
27
  }
28
+ const page = options.fontPreset?.page;
29
+ if (page) {
30
+ documentOptions.pageSize = {
31
+ width: mmToTwips(page.widthMm),
32
+ height: mmToTwips(page.heightMm),
33
+ };
34
+ documentOptions.margins = {
35
+ top: mmToTwips(page.marginsMm.top),
36
+ right: mmToTwips(page.marginsMm.right),
37
+ bottom: mmToTwips(page.marginsMm.bottom),
38
+ left: mmToTwips(page.marginsMm.left),
39
+ };
40
+ }
22
41
  if (options.pageMargins) {
23
42
  // Convert inches to twips (1 inch = 1440 twips)
24
43
  documentOptions.margins = {
@@ -32,7 +51,9 @@ export async function convertMarkdownToWord(markdown, options = {}) {
32
51
  // HTMLtoDOCX returns Blob in browser, Buffer/ArrayBuffer in Node.js
33
52
  const generated = result instanceof Blob ? result : new Blob([result]);
34
53
  // 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.
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.
36
57
  // Code blocks are broken in the generator output itself, so they are fixed
37
58
  // whether or not a font preset is requested.
38
59
  let wordDocument = generated;
@@ -43,13 +64,13 @@ export async function convertMarkdownToWord(markdown, options = {}) {
43
64
  return formatCodeBlocks(document, codeBlocks);
44
65
  });
45
66
  }
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
- }
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
+ });
53
74
  const { fontPreset } = options;
54
75
  if (fontPreset) {
55
76
  wordDocument = await patchOrKeep(wordDocument, 'font preset', async (document) => {
@@ -71,12 +92,16 @@ function codeBlockTexts(html) {
71
92
  }
72
93
  /** The rules and table header rows in `html`, for the structure patch. */
73
94
  function documentStructure(html) {
95
+ if (!html.includes('<hr') && !html.includes('<table')) {
96
+ return { rules: 0, headerRows: [] };
97
+ }
74
98
  const dom = new DOMParser().parseFromString(html, 'text/html');
75
99
  return {
76
100
  rules: dom.querySelectorAll('hr').length,
77
101
  headerRows: Array.from(dom.querySelectorAll('table'), (table) => {
78
102
  const firstRow = table.querySelector('tr');
79
- return Boolean(table.tHead) || Boolean(firstRow && firstRow.querySelector('td') === null);
103
+ return (Boolean(table.tHead) ||
104
+ Boolean(firstRow && firstRow.querySelector('td') === null));
80
105
  }),
81
106
  };
82
107
  }
@@ -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;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,OA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ACL,KAAK,EAAE,GAAG,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC,MAAM;QACxC,UAAU,EAAE,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,gBAAgB,CAAC,OAAO,CAAC,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}"]}
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,C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GAAG,CAAC,gBAAgB,CAAC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,EAAE;YAC9D,MAAM,QAAQ,GAAG,KAAK,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;YAC3C,OAAO,CACL,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC;gBACpB,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"]}
@@ -12,6 +12,9 @@ export { CODE_FONT };
12
12
  * matched in order against `codeBlocks`, and get the monospace face in all
13
13
  * three slots. Keying on the generator's hardcoded code font instead would
14
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.
15
18
  *
16
19
  * @param codeBlocks The text content of each `<pre>` in the source HTML, in
17
20
  * document order.
@@ -1,9 +1,14 @@
1
1
  import JSZip from 'jszip';
2
2
  import { CODE_FONT } from './docx-html.js';
3
- import { keepXmlDeclaration, WORDPROCESSING_NS as W_NS, XML_NS } from './xml-part.js';
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 = ['asciiTheme', 'eastAsiaTheme', 'hAnsiTheme', 'cstheme'];
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
  *
@@ -16,6 +21,9 @@ const THEME_FONT_ATTRIBUTES = ['asciiTheme', 'eastAsiaTheme', 'hAnsiTheme', 'cst
16
21
  * matched in order against `codeBlocks`, and get the monospace face in all
17
22
  * three slots. Keying on the generator's hardcoded code font instead would
18
23
  * also catch any inline `font-family` that names the same font.
24
+ * - Indent: the same paragraphs get an explicit zero first-line indent, so a
25
+ * preset that indents body text (the 公文 one) leaves the first code line
26
+ * aligned with the rest.
19
27
  *
20
28
  * @param codeBlocks The text content of each `<pre>` in the source HTML, in
21
29
  * document order.
@@ -51,7 +59,8 @@ export function formatDocumentXml(documentXml, codeBlocks) {
51
59
  if (pending.length === 0) {
52
60
  break;
53
61
  }
54
- if (compact(paragraphText(paragraph)) === pending[0] && hasExplicitFonts(paragraph)) {
62
+ if (compact(paragraphText(paragraph)) === pending[0] &&
63
+ hasExplicitFonts(paragraph)) {
55
64
  pending.shift();
56
65
  setCodeFont(paragraph);
57
66
  changed = true;
@@ -85,6 +94,11 @@ function textRuns(paragraph) {
85
94
  }
86
95
  function setCodeFont(paragraph) {
87
96
  const document = paragraph.ownerDocument;
97
+ let pPr = firstChild(paragraph, 'pPr');
98
+ if (!pPr) {
99
+ pPr = paragraph.insertBefore(document.createElementNS(W_NS, 'w:pPr'), paragraph.firstChild);
100
+ }
101
+ paragraphProperty(pPr, 'ind').setAttributeNS(W_NS, 'w:firstLine', '0');
88
102
  for (const run of textRuns(paragraph)) {
89
103
  let rPr = firstChild(run, 'rPr');
90
104
  if (!rPr) {
@@ -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,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,EAAE,YAAY,EAAE,SAAS,CAAC,CAAC;AAEvF;;;;;;;;;;;;;;;GAeG;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,CAAC,WAAW,EAAE,UAAU,CAAC,CAAC;IAC7D,IAAI,SAAS,KAAK,WAAW,EAAE,CAAC;QAC9B,OAAO,YAAY,CAAC;IACtB,CAAC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C,IAAI,CACrC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,YAAY,KAAK,IAAI,IAAI,KAAK,CAAC,SAAS,KAAK,SAAS,CACxE,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,SAAS,gBAAgB,CAAC,IAAa;IACrC,MAAM,KAAK,GAAG,CAAC,IAAI,CAAC,WAAW,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACnD,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACrB,OAAO,KAAK,CAAC;IACf,CAAC;IAED,MAAM,QAAQ,GAAG,IAAI,CAAC,aAAa,CAAC;IACpC,MAAM,GAAG,GAAG,IAAI,CAAC,UAAqB,CAAC;IAEvC,KAAK,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,IAAI,KAAK,CAAC,OAAO,EAAE,EAAE,CAAC;QAC5C,IAAI,KAAK,GAAG,CAAC,EAAE,CAAC;YACd,GAAG,CAAC,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"]}
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,CA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,IAAI,KAAK,GAAG,CAAC,EAAE,CAAC;YACd,GAAG,CAAC,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 {\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,15 +1,45 @@
1
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
+ }
2
9
  /**
3
- * Rewrites the fonts, sizes and paragraph spacing of an already generated .docx.
10
+ * Rewrites the fonts, sizes, paragraph spacing and page grid of an already
11
+ * generated .docx.
4
12
  *
5
13
  * `html-to-docx` only ever writes `w:ascii`, which WinWord applies to Latin
6
14
  * characters and digits; Chinese characters fall back to the theme font. The
7
15
  * East Asian slots are set here instead, so this stays out of the way of the
8
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.
9
20
  */
10
21
  export declare function applyFontPreset(wordDocument: Blob, preset: FontPreset): Promise<Blob>;
11
22
  /**
12
23
  * Applies `preset` to the document default run properties and to the six
13
- * heading styles of a styles.xml part.
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.
14
40
  */
15
- export declare function patchStylesXml(stylesXml: string, preset: FontPreset): string;
41
+ export declare function patchDocumentXml(documentXml: string, preset: FontPreset): {
42
+ xml: string;
43
+ grid: Grid | null;
44
+ };
45
+ export {};