markdown-to-word 0.1.0 → 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/README.md CHANGED
@@ -34,7 +34,7 @@ As on GitHub, a single newline inside a paragraph is joined into the same line,
34
34
 
35
35
  ## Optional Font Presets
36
36
 
37
- Conversions use Word's standard styling by default. Choosing **Chinese official document (公文)** from the **Style** menu rewrites the generated document so each level gets an East Asian face and a 公文 size alongside Times New Roman:
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
38
 
39
39
  | Level | Font size | Chinese characters | Latin letters and digits |
40
40
  | ----------- | ----------- | ------------------ | ------------------------ |
@@ -42,26 +42,42 @@ Conversions use Word's standard styling by default. Choosing **Chinese official
42
42
  | Heading 1 | 二号 (22pt) | 方正小标宋简体 | Times New Roman |
43
43
  | Heading 2 | 三号 (16pt) | 黑体 | Times New Roman |
44
44
  | Heading 3 | 三号 (16pt) | 楷体 | Times New Roman |
45
- | Heading 4-6 | 三号 (16pt) | 仿宋 (bold) | 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.
46
55
 
47
56
  The app remembers your choice in this browser, and suggests the preset when the text you paste is mostly Chinese.
48
57
 
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.
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:
50
59
 
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 磅.
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 公文.
52
63
 
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).
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.
54
65
 
55
66
  Programmatically:
56
67
 
57
68
  ```ts
58
- import { convertMarkdownToWord, CHINESE_OFFICIAL_DOC_FONTS } from 'markdown-to-word';
69
+ import {
70
+ convertMarkdownToWord,
71
+ CHINESE_OFFICIAL_DOC_FONTS,
72
+ } from 'markdown-to-word';
59
73
 
60
74
  const blob = await convertMarkdownToWord(markdown, {
61
75
  fontPreset: CHINESE_OFFICIAL_DOC_FONTS,
62
76
  });
63
77
  ```
64
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
+
65
81
  ## Privacy
66
82
 
67
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/).
@@ -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,6 +2,7 @@
2
2
  import './buffer-global.js';
3
3
  import HTMLtoDOCX from '@turbodocx/html-to-docx';
4
4
  import { prepareHtmlForDocx } from './docx-html.js';
5
+ import { mmToTwips } from './font-presets.js';
5
6
  import { parseMarkdownToHtml, extractTitle } from './markdown-parser.js';
6
7
  /**
7
8
  * Convert markdown text to a Word document blob using HTML as an intermediary format
@@ -19,6 +20,19 @@ export async function convertMarkdownToWord(markdown, options = {}) {
19
20
  if (title) {
20
21
  documentOptions.title = title;
21
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
+ }
22
36
  if (options.pageMargins) {
23
37
  // Convert inches to twips (1 inch = 1440 twips)
24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AAC,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;AAEpD,OAAO,EAAE,SAAS,EAAmB,MAAM,mBAAmB,CAAC;AAC/D,OAAO,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAiBzE;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,qBAAqB,CACzC,QAAgB,EAChB,UAA6B,EAAE;IAE/B,IAAI,CAAC;QACH,MAAM,IAAI,GAAG,mBAAmB,CAAC,QAAQ,CAAC,CAAC;QAE3C,MAAM,eAAe,GAA+B;YAClD,yEAAyE;YACzE,kEAAkE;YAClE,uBAAuB;YACvB,KAAK,EAAE,EAAE,aAAa,EAAE,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,QAAQ,EAAE,EAAE;SACzE,CAAC;QAEF,MAAM,KAAK,GAAG,YAAY,CAAC,QAAQ,CAAC,CAAC;QACrC,IAAI,KAAK,EAAE,CAAC;YACV,eAAe,CAAC,KAAK,GAAG,KAAK,CAAC;QAChC,CAAC;QAED,MAAM,IAAI,GAAG,OAAO,CAAC,UAAU,EAAE,IAAI,CAAC;QACtC,IAAI,IAAI,EAAE,CAAC;YACT,eAAe,CAAC,QAAQ,GAAG;gBACzB,KAAK,EAAE,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC;gBAC9B,MAAM,EAAE,SAAS,CAAC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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}"]}
@@ -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,6 +1,6 @@
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
6
  const THEME_FONT_ATTRIBUTES = ['asciiTheme', 'eastAsiaTheme', 'hAnsiTheme', 'cstheme'];
@@ -16,6 +16,9 @@ const THEME_FONT_ATTRIBUTES = ['asciiTheme', 'eastAsiaTheme', 'hAnsiTheme', 'cst
16
16
  * matched in order against `codeBlocks`, and get the monospace face in all
17
17
  * three slots. Keying on the generator's hardcoded code font instead would
18
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.
19
22
  *
20
23
  * @param codeBlocks The text content of each `<pre>` in the source HTML, in
21
24
  * document order.
@@ -85,6 +88,11 @@ function textRuns(paragraph) {
85
88
  }
86
89
  function setCodeFont(paragraph) {
87
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');
88
96
  for (const run of textRuns(paragraph)) {
89
97
  let rPr = firstChild(run, 'rPr');
90
98
  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;IAED,GAAG,CAAC,IAAI,CAAC,mBAAmB,EAAE,SAAS,CAAC,CAAC;IACzC,MAAM,OAAO,GAAG,MAAM,GAAG,CAAC,aAAa,CAAC,EAAE,IAAI,EAAE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;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,CAAC,YAAY,EAAE,eAAe,EAAE,YAAY,EAAE,SAAS,CAAC,CAAC;AAEvF;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,CAAC,KAAK,UAAU,gBAAgB,CAAC,YAAkB,EAAE,UAAoB;IAC7E,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC,SAAS,CAAC,MAAM,YAAY,CAAC,WAAW,EAAE,CAAC,CAAC;IACpE,MAAM,aAAa,GAAG,GAAG,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC;IACpD,IAAI,CAAC,aAAa,EAAE,CAAC;QACnB,MAAM,IAAI,KAAK,CAAC,mEAAmE,CAAC,CAAC;IACvF,CAAC;IAED,MAAM,WAAW,GAAG,MAAM,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AAC,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 = ['asciiTheme', 'eastAsiaTheme', 'hAnsiTheme', 'cstheme'];\n\n/**\n * Makes code blocks survive in Word, regardless of the font preset:\n *\n * - Line breaks: the generator keeps the source newlines of a `<pre>` as bare\n * `LF` inside `<w:t>`, which WinWord renders as whitespace; they become\n * `<w:br/>` here. Everywhere else the generator emits `<w:br/>` itself, so a\n * bare `LF` is the bug's own signature and needs no other marker.\n * - Typeface: the generator sets only `w:ascii`/`w:hAnsi`, so Chinese comments\n * fell through to the body font. Code paragraphs are found by their text,\n * matched in order against `codeBlocks`, and get the monospace face in all\n * three slots. Keying on the generator's hardcoded code font instead would\n * also catch any inline `font-family` that names the same font.\n * - Indent: the same paragraphs get an explicit zero first-line indent, so a\n * preset that indents body text (the 公文 one) leaves the first code line\n * aligned with the rest.\n *\n * @param codeBlocks The text content of each `<pre>` in the source HTML, in\n * document order.\n */\nexport async function formatCodeBlocks(wordDocument: Blob, codeBlocks: string[]): Promise<Blob> {\n const zip = await JSZip.loadAsync(await wordDocument.arrayBuffer());\n const documentEntry = zip.file('word/document.xml');\n if (!documentEntry) {\n throw new Error('Cannot format code blocks: document contains no word/document.xml');\n }\n\n const documentXml = await documentEntry.async('string');\n const formatted = formatDocumentXml(documentXml, codeBlocks);\n if (formatted === documentXml) {\n return wordDocument;\n }\n\n zip.file('word/document.xml', formatted);\n const patched = await zip.generateAsync({ type: 'arraybuffer' });\n return new Blob([patched], { type: wordDocument.type });\n}\n\n/** Exported for testing. */\nexport function formatDocumentXml(documentXml: string, codeBlocks: string[]): string {\n const dom = new DOMParser().parseFromString(documentXml, 'application/xml');\n let changed = false;\n\n // The generator emits one paragraph per <pre>, in source order, so a single\n // forward pass pairs each code block with the next paragraph of equal text.\n // Whitespace is ignored because the generator may trim or collapse it. A\n // plain paragraph can repeat a code block's text, so a match also needs every\n // run to name a font, as the generator does for <pre> but not for body text.\n // Inline code names CODE_FONT itself (see prepareHtmlForDocx), which the\n // generator never uses for <pre>, so those runs don't count.\n const pending = codeBlocks.map(compact).filter((text) => text !== '');\n for (const paragraph of Array.from(dom.getElementsByTagNameNS(W_NS, 'p'))) {\n if (pending.length === 0) {\n break;\n }\n if (compact(paragraphText(paragraph)) === pending[0] && hasExplicitFonts(paragraph)) {\n pending.shift();\n setCodeFont(paragraph);\n changed = true;\n }\n }\n\n for (const text of Array.from(dom.getElementsByTagNameNS(W_NS, 't'))) {\n changed = expandLineBreaks(text) || changed;\n }\n\n if (!changed) {\n return documentXml;\n }\n return keepXmlDeclaration(documentXml, new XMLSerializer().serializeToString(dom));\n}\n\nfunction compact(text: string): string {\n return text.replace(/\\s+/g, '');\n}\n\nfunction paragraphText(paragraph: Element): string {\n return Array.from(paragraph.getElementsByTagNameNS(W_NS, 't'))\n .map((text) => text.textContent ?? '')\n .join('');\n}\n\nfunction hasExplicitFonts(paragraph: Element): boolean {\n return textRuns(paragraph).every((run) => {\n const rFonts = firstChild(run, 'rPr')?.getElementsByTagNameNS(W_NS, 'rFonts')[0];\n const font = rFonts?.getAttributeNS(W_NS, 'ascii');\n return Boolean(font) && font !== CODE_FONT;\n });\n}\n\nfunction textRuns(paragraph: Element): Element[] {\n return Array.from(paragraph.getElementsByTagNameNS(W_NS, 'r')).filter(\n (run) => run.getElementsByTagNameNS(W_NS, 't').length > 0\n );\n}\n\nfunction setCodeFont(paragraph: Element): void {\n const document = paragraph.ownerDocument;\n\n let pPr = firstChild(paragraph, 'pPr');\n if (!pPr) {\n pPr = paragraph.insertBefore(document.createElementNS(W_NS, 'w:pPr'), paragraph.firstChild);\n }\n paragraphProperty(pPr, 'ind').setAttributeNS(W_NS, 'w:firstLine', '0');\n\n for (const run of textRuns(paragraph)) {\n let rPr = firstChild(run, 'rPr');\n if (!rPr) {\n rPr = run.insertBefore(document.createElementNS(W_NS, 'w:rPr'), run.firstChild);\n }\n\n // <w:rFonts> comes first in <w:rPr>.\n let rFonts = firstChild(rPr, 'rFonts');\n if (!rFonts) {\n rFonts = rPr.insertBefore(document.createElementNS(W_NS, 'w:rFonts'), rPr.firstChild);\n }\n\n for (const attribute of THEME_FONT_ATTRIBUTES) {\n rFonts.removeAttributeNS(W_NS, attribute);\n }\n for (const attribute of ['ascii', 'hAnsi', 'eastAsia'] as const) {\n rFonts.setAttributeNS(W_NS, `w:${attribute}`, CODE_FONT);\n }\n }\n}\n\nfunction firstChild(parent: Element, localName: string): Element | undefined {\n return Array.from(parent.children).find(\n (child) => child.namespaceURI === W_NS && child.localName === localName\n );\n}\n\n/**\n * Replaces one `<w:t>a\\nb</w:t>` with `<w:t>a</w:t><w:br/><w:t>b</w:t>`.\n * Returns whether anything changed.\n */\nfunction expandLineBreaks(text: Element): boolean {\n const lines = (text.textContent ?? '').split('\\n');\n if (lines.length < 2) {\n return false;\n }\n\n const document = text.ownerDocument;\n const run = text.parentNode as Element;\n\n for (const [index, line] of lines.entries()) {\n if (index > 0) {\n run.insertBefore(document.createElementNS(W_NS, 'w:br'), text);\n }\n if (line !== '') {\n const textElement = document.createElementNS(W_NS, 'w:t');\n textElement.setAttributeNS(XML_NS, 'xml:space', 'preserve');\n textElement.textContent = line;\n run.insertBefore(textElement, text);\n }\n }\n\n run.removeChild(text);\n return true;\n}\n"]}
@@ -1,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 {};
@@ -1,21 +1,23 @@
1
1
  import JSZip from 'jszip';
2
- import { keepXmlDeclaration, WORDPROCESSING_NS as W_NS } from './xml-part.js';
2
+ import { keepXmlDeclaration, paragraphProperty, WORDPROCESSING_NS as W_NS } from './xml-part.js';
3
3
  /** Theme slots WinWord prefers over explicitly named fonts. */
4
4
  const THEME_FONT_ATTRIBUTES = ['asciiTheme', 'eastAsiaTheme', 'hAnsiTheme', 'cstheme'];
5
5
  /**
6
6
  * `<w:line>` is ignored while the rule is auto, but WinWord still writes 240
7
7
  * twips, so the preset writes the pair Word itself produces.
8
8
  */
9
- const LINE_SPACING = {
10
- single: { line: '240', rule: 'auto' },
11
- };
9
+ const SINGLE_SPACING = { line: '240', rule: 'auto' };
12
10
  /**
13
- * Rewrites the fonts, sizes and paragraph spacing of an already generated .docx.
11
+ * Rewrites the fonts, sizes, paragraph spacing and page grid of an already
12
+ * generated .docx.
14
13
  *
15
14
  * `html-to-docx` only ever writes `w:ascii`, which WinWord applies to Latin
16
15
  * characters and digits; Chinese characters fall back to the theme font. The
17
16
  * East Asian slots are set here instead, so this stays out of the way of the
18
17
  * default conversion output.
18
+ *
19
+ * The grid is measured from the page the document actually has, so it still
20
+ * fits when `pageMargins` overrode the preset's margins.
19
21
  */
20
22
  export async function applyFontPreset(wordDocument, preset) {
21
23
  const zip = await JSZip.loadAsync(await wordDocument.arrayBuffer());
@@ -23,29 +25,169 @@ export async function applyFontPreset(wordDocument, preset) {
23
25
  if (!stylesEntry) {
24
26
  throw new Error('Cannot apply font preset: document contains no word/styles.xml');
25
27
  }
28
+ let grid = null;
29
+ const pageGrid = preset.page?.grid;
30
+ if (pageGrid ||
31
+ preset.paragraph.lineSpacing === 'grid' ||
32
+ preset.paragraph.firstLineIndentChars) {
33
+ const documentEntry = zip.file('word/document.xml');
34
+ if (!documentEntry) {
35
+ throw new Error('Cannot apply font preset: document contains no word/document.xml');
36
+ }
37
+ const documentXml = await documentEntry.async('string');
38
+ const patched = patchDocumentXml(documentXml, preset);
39
+ grid = patched.grid;
40
+ zip.file('word/document.xml', patched.xml);
41
+ }
26
42
  const stylesXml = await stylesEntry.async('string');
27
- zip.file('word/styles.xml', patchStylesXml(stylesXml, preset));
43
+ zip.file('word/styles.xml', patchStylesXml(stylesXml, preset, grid));
28
44
  const patched = await zip.generateAsync({ type: 'arraybuffer' });
29
45
  return new Blob([patched], { type: wordDocument.type });
30
46
  }
31
47
  /**
32
48
  * Applies `preset` to the document default run properties and to the six
33
- * heading styles of a styles.xml part.
49
+ * heading styles of a styles.xml part. `grid` is the page grid that
50
+ * `patchDocumentXml` set, which `lineSpacing: 'grid'` takes its pitch from.
34
51
  */
35
- export function patchStylesXml(stylesXml, preset) {
52
+ export function patchStylesXml(stylesXml, preset, grid = null) {
36
53
  const dom = new DOMParser().parseFromString(stylesXml, 'application/xml');
54
+ const layout = resolveLayout(preset, grid);
37
55
  const docDefaults = requireElement(dom, 'docDefaults');
38
- applyLevelStyle(docDefaults, preset.body, preset.paragraph);
56
+ applyLevelStyle(docDefaults, preset.body, preset.paragraph, layout);
57
+ if (layout.spacing.rule === 'exact') {
58
+ // Widow control pulls a line onto the next page whenever a paragraph would
59
+ // leave a single line behind, so pages would often hold one line fewer
60
+ // than the grid. Word turns it on unless the document says otherwise.
61
+ paragraphProperty(paragraphPropertiesOf(docDefaults), 'widowControl').setAttributeNS(W_NS, 'w:val', '0');
62
+ }
39
63
  const styles = Array.from(dom.getElementsByTagNameNS(W_NS, 'style'));
40
64
  for (const style of styles) {
41
65
  const heading = /^Heading([1-6])$/.exec(style.getAttributeNS(W_NS, 'styleId') ?? '');
42
66
  if (heading) {
43
- applyLevelStyle(style, preset.headings[Number(heading[1]) - 1], preset.paragraph);
67
+ applyLevelStyle(style, preset.headings[Number(heading[1]) - 1], preset.paragraph, layout);
44
68
  }
45
69
  }
46
70
  return keepXmlDeclaration(stylesXml, new XMLSerializer().serializeToString(dom));
47
71
  }
48
- function applyLevelStyle(scope, style, paragraph) {
72
+ function resolveLayout(preset, grid) {
73
+ const { lineSpacing, firstLineIndentChars = 0 } = preset.paragraph;
74
+ if (lineSpacing === 'grid' && !grid) {
75
+ throw new Error("Cannot apply font preset: lineSpacing 'grid' needs page.grid");
76
+ }
77
+ return {
78
+ spacing: lineSpacing === 'grid' && grid
79
+ ? { line: String(grid.linePitch), rule: 'exact' }
80
+ : SINGLE_SPACING,
81
+ firstLineIndent: Math.round(firstLineIndentChars * preset.body.sizePt * 20),
82
+ };
83
+ }
84
+ /**
85
+ * Sets the page grid in the section properties of a document.xml part, and
86
+ * fixes up the paragraphs that the style-level layout would break:
87
+ *
88
+ * - The generator gives every paragraph `<w:spacing w:lineRule="auto"/>`.
89
+ * Spacing attributes inherit one at a time, so that lone `auto` combined
90
+ * with the style's exact line height would read as a multiple of 240 twips
91
+ * (about 2.4 lines). It is dropped when the preset uses grid spacing.
92
+ * - Exact line spacing would crop an inline image to one line, so paragraphs
93
+ * with a drawing keep single spacing; the grid then rounds them up to whole
94
+ * lines.
95
+ * - Table cells drop the first-line indent; it only crowds narrow columns.
96
+ */
97
+ export function patchDocumentXml(documentXml, preset) {
98
+ const dom = new DOMParser().parseFromString(documentXml, 'application/xml');
99
+ let grid = null;
100
+ const pageGrid = preset.page?.grid;
101
+ if (pageGrid) {
102
+ for (const sectPr of Array.from(dom.getElementsByTagNameNS(W_NS, 'sectPr'))) {
103
+ grid = measureGrid(sectPr, pageGrid, preset.body.sizePt);
104
+ setDocGrid(sectPr, grid);
105
+ }
106
+ }
107
+ const gridSpacing = preset.paragraph.lineSpacing === 'grid';
108
+ for (const paragraph of Array.from(dom.getElementsByTagNameNS(W_NS, 'p'))) {
109
+ const pPr = children(paragraph).find((child) => child.localName === 'pPr');
110
+ if (gridSpacing) {
111
+ if (paragraph.getElementsByTagNameNS(W_NS, 'drawing').length > 0) {
112
+ const spacing = paragraphProperty(pPrOf(paragraph), 'spacing');
113
+ spacing.setAttributeNS(W_NS, 'w:line', SINGLE_SPACING.line);
114
+ spacing.setAttributeNS(W_NS, 'w:lineRule', SINGLE_SPACING.rule);
115
+ }
116
+ else {
117
+ const spacing = pPr && children(pPr).find((child) => child.localName === 'spacing');
118
+ if (spacing && !spacing.hasAttributeNS(W_NS, 'line')) {
119
+ spacing.removeAttributeNS(W_NS, 'lineRule');
120
+ if (spacing.attributes.length === 0) {
121
+ spacing.remove();
122
+ }
123
+ }
124
+ }
125
+ }
126
+ if (preset.paragraph.firstLineIndentChars && isInTableCell(paragraph)) {
127
+ removeFirstLineIndent(pPrOf(paragraph));
128
+ }
129
+ }
130
+ return {
131
+ xml: keepXmlDeclaration(documentXml, new XMLSerializer().serializeToString(dom)),
132
+ grid,
133
+ };
134
+ }
135
+ /**
136
+ * The grid for the text block of `sectPr`'s page. Word stores the character
137
+ * pitch as an offset from the body font size. Both pitches are rounded down,
138
+ * as Word does, so the lines and characters always fit: for the page Word
139
+ * itself sets up with GB/T 9704 margins, this reproduces its linePitch="579"
140
+ * and charSpace="-834".
141
+ */
142
+ function measureGrid(sectPr, { linesPerPage, charsPerLine }, bodySizePt) {
143
+ const pgSz = children(sectPr).find((child) => child.localName === 'pgSz');
144
+ const pgMar = children(sectPr).find((child) => child.localName === 'pgMar');
145
+ const twips = (element, attribute) => {
146
+ const value = Number(element?.getAttributeNS(W_NS, attribute));
147
+ if (!Number.isFinite(value) || value <= 0) {
148
+ throw new Error(`Cannot apply font preset: section has no page ${attribute}`);
149
+ }
150
+ return value;
151
+ };
152
+ const textHeight = twips(pgSz, 'h') - twips(pgMar, 'top') - twips(pgMar, 'bottom');
153
+ const textWidth = twips(pgSz, 'w') - twips(pgMar, 'left') - twips(pgMar, 'right');
154
+ const charPitchPt = textWidth / 20 / charsPerLine;
155
+ return {
156
+ linePitch: Math.floor(textHeight / linesPerPage),
157
+ charSpace: Math.floor((charPitchPt - bodySizePt) * 4096),
158
+ };
159
+ }
160
+ function setDocGrid(sectPr, grid) {
161
+ let docGrid = children(sectPr).find((child) => child.localName === 'docGrid');
162
+ if (!docGrid) {
163
+ docGrid = sectPr.ownerDocument.createElementNS(W_NS, 'w:docGrid');
164
+ // <w:docGrid> is the last section property but <w:printerSettings>.
165
+ const printerSettings = children(sectPr).find((child) => child.localName === 'printerSettings');
166
+ sectPr.insertBefore(docGrid, printerSettings ?? null);
167
+ }
168
+ docGrid.setAttributeNS(W_NS, 'w:type', 'linesAndChars');
169
+ docGrid.setAttributeNS(W_NS, 'w:linePitch', String(grid.linePitch));
170
+ docGrid.setAttributeNS(W_NS, 'w:charSpace', String(grid.charSpace));
171
+ }
172
+ function isInTableCell(paragraph) {
173
+ for (let node = paragraph.parentElement; node; node = node.parentElement) {
174
+ if (node.namespaceURI === W_NS && node.localName === 'tc') {
175
+ return true;
176
+ }
177
+ }
178
+ return false;
179
+ }
180
+ function removeFirstLineIndent(pPr) {
181
+ const ind = paragraphProperty(pPr, 'ind');
182
+ if (!ind.hasAttributeNS(W_NS, 'hanging')) {
183
+ ind.setAttributeNS(W_NS, 'w:firstLine', '0');
184
+ }
185
+ }
186
+ /** A paragraph's `<w:pPr>`, created as its first child if missing. */
187
+ function pPrOf(paragraph) {
188
+ return childOrCreate(paragraph, 'pPr', 'first');
189
+ }
190
+ function applyLevelStyle(scope, style, paragraph, layout) {
49
191
  const rPr = runPropertiesOf(scope);
50
192
  const rFonts = childOrCreate(rPr, 'rFonts', 'first');
51
193
  for (const attribute of THEME_FONT_ATTRIBUTES) {
@@ -66,12 +208,22 @@ function applyLevelStyle(scope, style, paragraph) {
66
208
  const size = String(style.sizePt * 2);
67
209
  childOrCreate(rPr, 'sz', 'last').setAttributeNS(W_NS, 'w:val', size);
68
210
  childOrCreate(rPr, 'szCs', 'last').setAttributeNS(W_NS, 'w:val', size);
69
- const spacing = childOrCreate(paragraphPropertiesOf(scope), 'spacing', 'first');
211
+ const pPr = paragraphPropertiesOf(scope);
212
+ const spacing = paragraphProperty(pPr, 'spacing');
70
213
  spacing.setAttributeNS(W_NS, 'w:before', String(paragraph.beforePt * 20));
71
214
  spacing.setAttributeNS(W_NS, 'w:after', String(paragraph.afterPt * 20));
72
- const line = LINE_SPACING[paragraph.lineSpacing];
73
- spacing.setAttributeNS(W_NS, 'w:line', line.line);
74
- spacing.setAttributeNS(W_NS, 'w:lineRule', line.rule);
215
+ spacing.setAttributeNS(W_NS, 'w:line', layout.spacing.line);
216
+ spacing.setAttributeNS(W_NS, 'w:lineRule', layout.spacing.rule);
217
+ if (style.centered) {
218
+ // An indented first line would push a centered title off center.
219
+ if (layout.firstLineIndent) {
220
+ paragraphProperty(pPr, 'ind').setAttributeNS(W_NS, 'w:firstLine', '0');
221
+ }
222
+ paragraphProperty(pPr, 'jc').setAttributeNS(W_NS, 'w:val', 'center');
223
+ }
224
+ else if (layout.firstLineIndent) {
225
+ paragraphProperty(pPr, 'ind').setAttributeNS(W_NS, 'w:firstLine', String(layout.firstLineIndent));
226
+ }
75
227
  }
76
228
  function runPropertiesOf(parent) {
77
229
  const container = parent.localName === 'docDefaults'
@@ -1 +1 @@
1
- {"version":3,"file":"docx-font-preset.js","sourceRoot":"","sources":["../src/docx-font-preset.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAE1B,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,IAAI,IAAI,EAAE,MAAM,eAAe,CAAC;AAE9E,+DAA+D;AAC/D,MAAM,qBAAqB,GAAG,CAAC,YAAY,EAAE,eAAe,EAAE,YAAY,EAAE,SAAS,CAAC,CAAC;AAEvF;;;GAGG;AACH,MAAM,YAAY,GAAwD;IACxE,MAAM,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE;CACtC,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,CAAC,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S,EAAE,CAAC,CAAC;IAC7E,OAAO,QAAQ,KAAK,OAAO;QACzB,CAAC,CAAC,MAAM,CAAC,YAAY,CAAC,OAAO,EAAE,MAAM,CAAC,UAAU,CAAC;QACjD,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;AAClC,CAAC;AAED,SAAS,cAAc,CAAC,GAAa,EAAE,SAAiB;IACtD,MAAM,OAAO,GAAG,GAAG,CAAC,sBAAsB,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/D,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CAAC,kDAAkD,SAAS,WAAW,CAAC,CAAC;IAC1F,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import JSZip from 'jszip';\nimport type { FontPreset, LevelStyle, LineSpacing, ParagraphStyle } from './font-presets.js';\nimport { keepXmlDeclaration, WORDPROCESSING_NS as W_NS } from './xml-part.js';\n\n/** Theme slots WinWord prefers over explicitly named fonts. */\nconst THEME_FONT_ATTRIBUTES = ['asciiTheme', 'eastAsiaTheme', 'hAnsiTheme', 'cstheme'];\n\n/**\n * `<w:line>` is ignored while the rule is auto, but WinWord still writes 240\n * twips, so the preset writes the pair Word itself produces.\n */\nconst LINE_SPACING: Record<LineSpacing, { line: string; rule: string }> = {\n single: { line: '240', rule: 'auto' },\n};\n\n/**\n * Rewrites the fonts, sizes and paragraph spacing of an already generated .docx.\n *\n * `html-to-docx` only ever writes `w:ascii`, which WinWord applies to Latin\n * characters and digits; Chinese characters fall back to the theme font. The\n * East Asian slots are set here instead, so this stays out of the way of the\n * default conversion output.\n */\nexport async function applyFontPreset(wordDocument: Blob, preset: FontPreset): Promise<Blob> {\n const zip = await JSZip.loadAsync(await wordDocument.arrayBuffer());\n const stylesEntry = zip.file('word/styles.xml');\n if (!stylesEntry) {\n throw new Error('Cannot apply font preset: document contains no word/styles.xml');\n }\n\n const stylesXml = await stylesEntry.async('string');\n zip.file('word/styles.xml', patchStylesXml(stylesXml, preset));\n\n const patched = await zip.generateAsync({ type: 'arraybuffer' });\n return new Blob([patched], { type: wordDocument.type });\n}\n\n/**\n * Applies `preset` to the document default run properties and to the six\n * heading styles of a styles.xml part.\n */\nexport function patchStylesXml(stylesXml: string, preset: FontPreset): string {\n const dom = new DOMParser().parseFromString(stylesXml, 'application/xml');\n\n const docDefaults = requireElement(dom, 'docDefaults');\n applyLevelStyle(docDefaults, preset.body, preset.paragraph);\n\n const styles = Array.from(dom.getElementsByTagNameNS(W_NS, 'style'));\n for (const style of styles) {\n const heading = /^Heading([1-6])$/.exec(style.getAttributeNS(W_NS, 'styleId') ?? '');\n if (heading) {\n applyLevelStyle(style, preset.headings[Number(heading[1]) - 1], preset.paragraph);\n }\n }\n\n return keepXmlDeclaration(stylesXml, new XMLSerializer().serializeToString(dom));\n}\n\nfunction applyLevelStyle(scope: Element, style: LevelStyle, paragraph: ParagraphStyle): void {\n const rPr = runPropertiesOf(scope);\n\n const rFonts = childOrCreate(rPr, 'rFonts', 'first');\n for (const attribute of THEME_FONT_ATTRIBUTES) {\n rFonts.removeAttributeNS(W_NS, attribute);\n }\n rFonts.setAttributeNS(W_NS, 'w:ascii', style.latin);\n rFonts.setAttributeNS(W_NS, 'w:hAnsi', style.latin);\n rFonts.setAttributeNS(W_NS, 'w:eastAsia', style.eastAsia);\n\n for (const child of children(rPr)) {\n if (child.localName === 'b' || child.localName === 'bCs') {\n child.remove();\n }\n }\n if (style.bold) {\n rPr.insertBefore(rPr.ownerDocument.createElementNS(W_NS, 'w:b'), rFonts.nextSibling);\n }\n\n // <w:sz> is measured in half points.\n const size = String(style.sizePt * 2);\n childOrCreate(rPr, 'sz', 'last').setAttributeNS(W_NS, 'w:val', size);\n childOrCreate(rPr, 'szCs', 'last').setAttributeNS(W_NS, 'w:val', size);\n\n const spacing = childOrCreate(paragraphPropertiesOf(scope), 'spacing', 'first');\n spacing.setAttributeNS(W_NS, 'w:before', String(paragraph.beforePt * 20));\n spacing.setAttributeNS(W_NS, 'w:after', String(paragraph.afterPt * 20));\n\n const line = LINE_SPACING[paragraph.lineSpacing];\n spacing.setAttributeNS(W_NS, 'w:line', line.line);\n spacing.setAttributeNS(W_NS, 'w:lineRule', line.rule);\n}\n\nfunction runPropertiesOf(parent: Element): Element {\n const container =\n parent.localName === 'docDefaults'\n ? childOrCreate(parent, 'rPrDefault', 'first')\n : parent;\n // In a <w:style> the run properties go last, after any <w:pPr>.\n return childOrCreate(container, 'rPr', 'last');\n}\n\nfunction paragraphPropertiesOf(parent: Element): Element {\n if (parent.localName === 'docDefaults') {\n const pPrDefault = childOrCreate(parent, 'pPrDefault', 'last');\n return childOrCreate(pPrDefault, 'pPr', 'first');\n }\n\n const existing = children(parent).find((child) => child.localName === 'pPr');\n if (existing) {\n return existing;\n }\n // In a <w:style> the paragraph properties go before the run properties.\n const created = parent.ownerDocument.createElementNS(W_NS, 'w:pPr');\n return parent.insertBefore(created, runPropertiesOf(parent));\n}\n\nfunction children(element: Element): Element[] {\n return Array.from(element.children).filter((child) => child.namespaceURI === W_NS);\n}\n\nfunction childOrCreate(parent: Element, localName: string, position: 'first' | 'last'): Element {\n const existing = children(parent).find((child) => child.localName === localName);\n if (existing) {\n return existing;\n }\n const created = parent.ownerDocument.createElementNS(W_NS, `w:${localName}`);\n return position === 'first'\n ? parent.insertBefore(created, parent.firstChild)\n : parent.appendChild(created);\n}\n\nfunction requireElement(dom: Document, localName: string): Element {\n const element = dom.getElementsByTagNameNS(W_NS, localName)[0];\n if (!element) {\n throw new Error(`Cannot apply font preset: styles.xml has no <w:${localName}> element`);\n }\n return element;\n}\n"]}
1
+ {"version":3,"file":"docx-font-preset.js","sourceRoot":"","sources":["../src/docx-font-preset.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAE1B,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,iBAAiB,IAAI,IAAI,EAAE,MAAM,eA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,MAAM,CAAC,YAAY,CAAC,OAAO,EAAE,MAAM,CAAC,UAAU,CAAC;QACjD,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;AAClC,CAAC;AAED,SAAS,cAAc,CAAC,GAAa,EAAE,SAAiB;IACtD,MAAM,OAAO,GAAG,GAAG,CAAC,sBAAsB,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/D,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CAAC,kDAAkD,SAAS,WAAW,CAAC,CAAC;IAC1F,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import JSZip from 'jszip';\nimport type { FontPreset, LevelStyle, ParagraphStyle } from './font-presets.js';\nimport { keepXmlDeclaration, paragraphProperty, WORDPROCESSING_NS as W_NS } from './xml-part.js';\n\n/** Theme slots WinWord prefers over explicitly named fonts. */\nconst THEME_FONT_ATTRIBUTES = ['asciiTheme', 'eastAsiaTheme', 'hAnsiTheme', 'cstheme'];\n\n/**\n * `<w:line>` is ignored while the rule is auto, but WinWord still writes 240\n * twips, so the preset writes the pair Word itself produces.\n */\nconst SINGLE_SPACING = { line: '240', rule: 'auto' };\n\n/** Word's document grid, in the units of `<w:docGrid>`. */\ninterface Grid {\n /** Line pitch in twips. */\n linePitch: number;\n /** Character pitch relative to the body font size, in 1/4096 point. */\n charSpace: number;\n}\n\n/** What the styles need to know about the paragraphs, resolved once. */\ninterface Layout {\n spacing: { line: string; rule: string };\n /** First-line indent of body paragraphs in twips, or 0 for none. */\n firstLineIndent: number;\n}\n\n/**\n * Rewrites the fonts, sizes, paragraph spacing and page grid of an already\n * generated .docx.\n *\n * `html-to-docx` only ever writes `w:ascii`, which WinWord applies to Latin\n * characters and digits; Chinese characters fall back to the theme font. The\n * East Asian slots are set here instead, so this stays out of the way of the\n * default conversion output.\n *\n * The grid is measured from the page the document actually has, so it still\n * fits when `pageMargins` overrode the preset's margins.\n */\nexport async function applyFontPreset(wordDocument: Blob, preset: FontPreset): Promise<Blob> {\n const zip = await JSZip.loadAsync(await wordDocument.arrayBuffer());\n const stylesEntry = zip.file('word/styles.xml');\n if (!stylesEntry) {\n throw new Error('Cannot apply font preset: document contains no word/styles.xml');\n }\n\n let grid: Grid | null = null;\n const pageGrid = preset.page?.grid;\n if (\n pageGrid ||\n preset.paragraph.lineSpacing === 'grid' ||\n preset.paragraph.firstLineIndentChars\n ) {\n const documentEntry = zip.file('word/document.xml');\n if (!documentEntry) {\n throw new Error('Cannot apply font preset: document contains no word/document.xml');\n }\n const documentXml = await documentEntry.async('string');\n const patched = patchDocumentXml(documentXml, preset);\n grid = patched.grid;\n zip.file('word/document.xml', patched.xml);\n }\n\n const stylesXml = await stylesEntry.async('string');\n zip.file('word/styles.xml', patchStylesXml(stylesXml, preset, grid));\n\n const patched = await zip.generateAsync({ type: 'arraybuffer' });\n return new Blob([patched], { type: wordDocument.type });\n}\n\n/**\n * Applies `preset` to the document default run properties and to the six\n * heading styles of a styles.xml part. `grid` is the page grid that\n * `patchDocumentXml` set, which `lineSpacing: 'grid'` takes its pitch from.\n */\nexport function patchStylesXml(\n stylesXml: string,\n preset: FontPreset,\n grid: Grid | null = null\n): string {\n const dom = new DOMParser().parseFromString(stylesXml, 'application/xml');\n const layout = resolveLayout(preset, grid);\n\n const docDefaults = requireElement(dom, 'docDefaults');\n applyLevelStyle(docDefaults, preset.body, preset.paragraph, layout);\n if (layout.spacing.rule === 'exact') {\n // Widow control pulls a line onto the next page whenever a paragraph would\n // leave a single line behind, so pages would often hold one line fewer\n // than the grid. Word turns it on unless the document says otherwise.\n paragraphProperty(paragraphPropertiesOf(docDefaults), 'widowControl').setAttributeNS(\n W_NS,\n 'w:val',\n '0'\n );\n }\n\n const styles = Array.from(dom.getElementsByTagNameNS(W_NS, 'style'));\n for (const style of styles) {\n const heading = /^Heading([1-6])$/.exec(style.getAttributeNS(W_NS, 'styleId') ?? '');\n if (heading) {\n applyLevelStyle(style, preset.headings[Number(heading[1]) - 1], preset.paragraph, layout);\n }\n }\n\n return keepXmlDeclaration(stylesXml, new XMLSerializer().serializeToString(dom));\n}\n\nfunction resolveLayout(preset: FontPreset, grid: Grid | null): Layout {\n const { lineSpacing, firstLineIndentChars = 0 } = preset.paragraph;\n if (lineSpacing === 'grid' && !grid) {\n throw new Error(\"Cannot apply font preset: lineSpacing 'grid' needs page.grid\");\n }\n return {\n spacing:\n lineSpacing === 'grid' && grid\n ? { line: String(grid.linePitch), rule: 'exact' }\n : SINGLE_SPACING,\n firstLineIndent: Math.round(firstLineIndentChars * preset.body.sizePt * 20),\n };\n}\n\n/**\n * Sets the page grid in the section properties of a document.xml part, and\n * fixes up the paragraphs that the style-level layout would break:\n *\n * - The generator gives every paragraph `<w:spacing w:lineRule=\"auto\"/>`.\n * Spacing attributes inherit one at a time, so that lone `auto` combined\n * with the style's exact line height would read as a multiple of 240 twips\n * (about 2.4 lines). It is dropped when the preset uses grid spacing.\n * - Exact line spacing would crop an inline image to one line, so paragraphs\n * with a drawing keep single spacing; the grid then rounds them up to whole\n * lines.\n * - Table cells drop the first-line indent; it only crowds narrow columns.\n */\nexport function patchDocumentXml(\n documentXml: string,\n preset: FontPreset\n): { xml: string; grid: Grid | null } {\n const dom = new DOMParser().parseFromString(documentXml, 'application/xml');\n\n let grid: Grid | null = null;\n const pageGrid = preset.page?.grid;\n if (pageGrid) {\n for (const sectPr of Array.from(dom.getElementsByTagNameNS(W_NS, 'sectPr'))) {\n grid = measureGrid(sectPr, pageGrid, preset.body.sizePt);\n setDocGrid(sectPr, grid);\n }\n }\n\n const gridSpacing = preset.paragraph.lineSpacing === 'grid';\n for (const paragraph of Array.from(dom.getElementsByTagNameNS(W_NS, 'p'))) {\n const pPr = children(paragraph).find((child) => child.localName === 'pPr');\n\n if (gridSpacing) {\n if (paragraph.getElementsByTagNameNS(W_NS, 'drawing').length > 0) {\n const spacing = paragraphProperty(pPrOf(paragraph), 'spacing');\n spacing.setAttributeNS(W_NS, 'w:line', SINGLE_SPACING.line);\n spacing.setAttributeNS(W_NS, 'w:lineRule', SINGLE_SPACING.rule);\n } else {\n const spacing = pPr && children(pPr).find((child) => child.localName === 'spacing');\n if (spacing && !spacing.hasAttributeNS(W_NS, 'line')) {\n spacing.removeAttributeNS(W_NS, 'lineRule');\n if (spacing.attributes.length === 0) {\n spacing.remove();\n }\n }\n }\n }\n\n if (preset.paragraph.firstLineIndentChars && isInTableCell(paragraph)) {\n removeFirstLineIndent(pPrOf(paragraph));\n }\n }\n\n return {\n xml: keepXmlDeclaration(documentXml, new XMLSerializer().serializeToString(dom)),\n grid,\n };\n}\n\n/**\n * The grid for the text block of `sectPr`'s page. Word stores the character\n * pitch as an offset from the body font size. Both pitches are rounded down,\n * as Word does, so the lines and characters always fit: for the page Word\n * itself sets up with GB/T 9704 margins, this reproduces its linePitch=\"579\"\n * and charSpace=\"-834\".\n */\nfunction measureGrid(\n sectPr: Element,\n { linesPerPage, charsPerLine }: { linesPerPage: number; charsPerLine: number },\n bodySizePt: number\n): Grid {\n const pgSz = children(sectPr).find((child) => child.localName === 'pgSz');\n const pgMar = children(sectPr).find((child) => child.localName === 'pgMar');\n const twips = (element: Element | undefined, attribute: string): number => {\n const value = Number(element?.getAttributeNS(W_NS, attribute));\n if (!Number.isFinite(value) || value <= 0) {\n throw new Error(`Cannot apply font preset: section has no page ${attribute}`);\n }\n return value;\n };\n\n const textHeight = twips(pgSz, 'h') - twips(pgMar, 'top') - twips(pgMar, 'bottom');\n const textWidth = twips(pgSz, 'w') - twips(pgMar, 'left') - twips(pgMar, 'right');\n const charPitchPt = textWidth / 20 / charsPerLine;\n\n return {\n linePitch: Math.floor(textHeight / linesPerPage),\n charSpace: Math.floor((charPitchPt - bodySizePt) * 4096),\n };\n}\n\nfunction setDocGrid(sectPr: Element, grid: Grid): void {\n let docGrid = children(sectPr).find((child) => child.localName === 'docGrid');\n if (!docGrid) {\n docGrid = sectPr.ownerDocument.createElementNS(W_NS, 'w:docGrid');\n // <w:docGrid> is the last section property but <w:printerSettings>.\n const printerSettings = children(sectPr).find((child) => child.localName === 'printerSettings');\n sectPr.insertBefore(docGrid, printerSettings ?? null);\n }\n docGrid.setAttributeNS(W_NS, 'w:type', 'linesAndChars');\n docGrid.setAttributeNS(W_NS, 'w:linePitch', String(grid.linePitch));\n docGrid.setAttributeNS(W_NS, 'w:charSpace', String(grid.charSpace));\n}\n\nfunction isInTableCell(paragraph: Element): boolean {\n for (let node = paragraph.parentElement; node; node = node.parentElement) {\n if (node.namespaceURI === W_NS && node.localName === 'tc') {\n return true;\n }\n }\n return false;\n}\n\nfunction removeFirstLineIndent(pPr: Element): void {\n const ind = paragraphProperty(pPr, 'ind');\n if (!ind.hasAttributeNS(W_NS, 'hanging')) {\n ind.setAttributeNS(W_NS, 'w:firstLine', '0');\n }\n}\n\n/** A paragraph's `<w:pPr>`, created as its first child if missing. */\nfunction pPrOf(paragraph: Element): Element {\n return childOrCreate(paragraph, 'pPr', 'first');\n}\n\nfunction applyLevelStyle(\n scope: Element,\n style: LevelStyle,\n paragraph: ParagraphStyle,\n layout: Layout\n): void {\n const rPr = runPropertiesOf(scope);\n\n const rFonts = childOrCreate(rPr, 'rFonts', 'first');\n for (const attribute of THEME_FONT_ATTRIBUTES) {\n rFonts.removeAttributeNS(W_NS, attribute);\n }\n rFonts.setAttributeNS(W_NS, 'w:ascii', style.latin);\n rFonts.setAttributeNS(W_NS, 'w:hAnsi', style.latin);\n rFonts.setAttributeNS(W_NS, 'w:eastAsia', style.eastAsia);\n\n for (const child of children(rPr)) {\n if (child.localName === 'b' || child.localName === 'bCs') {\n child.remove();\n }\n }\n if (style.bold) {\n rPr.insertBefore(rPr.ownerDocument.createElementNS(W_NS, 'w:b'), rFonts.nextSibling);\n }\n\n // <w:sz> is measured in half points.\n const size = String(style.sizePt * 2);\n childOrCreate(rPr, 'sz', 'last').setAttributeNS(W_NS, 'w:val', size);\n childOrCreate(rPr, 'szCs', 'last').setAttributeNS(W_NS, 'w:val', size);\n\n const pPr = paragraphPropertiesOf(scope);\n const spacing = paragraphProperty(pPr, 'spacing');\n spacing.setAttributeNS(W_NS, 'w:before', String(paragraph.beforePt * 20));\n spacing.setAttributeNS(W_NS, 'w:after', String(paragraph.afterPt * 20));\n spacing.setAttributeNS(W_NS, 'w:line', layout.spacing.line);\n spacing.setAttributeNS(W_NS, 'w:lineRule', layout.spacing.rule);\n\n if (style.centered) {\n // An indented first line would push a centered title off center.\n if (layout.firstLineIndent) {\n paragraphProperty(pPr, 'ind').setAttributeNS(W_NS, 'w:firstLine', '0');\n }\n paragraphProperty(pPr, 'jc').setAttributeNS(W_NS, 'w:val', 'center');\n } else if (layout.firstLineIndent) {\n paragraphProperty(pPr, 'ind').setAttributeNS(\n W_NS,\n 'w:firstLine',\n String(layout.firstLineIndent)\n );\n }\n}\n\nfunction runPropertiesOf(parent: Element): Element {\n const container =\n parent.localName === 'docDefaults'\n ? childOrCreate(parent, 'rPrDefault', 'first')\n : parent;\n // In a <w:style> the run properties go last, after any <w:pPr>.\n return childOrCreate(container, 'rPr', 'last');\n}\n\nfunction paragraphPropertiesOf(parent: Element): Element {\n if (parent.localName === 'docDefaults') {\n const pPrDefault = childOrCreate(parent, 'pPrDefault', 'last');\n return childOrCreate(pPrDefault, 'pPr', 'first');\n }\n\n const existing = children(parent).find((child) => child.localName === 'pPr');\n if (existing) {\n return existing;\n }\n // In a <w:style> the paragraph properties go before the run properties.\n const created = parent.ownerDocument.createElementNS(W_NS, 'w:pPr');\n return parent.insertBefore(created, runPropertiesOf(parent));\n}\n\nfunction children(element: Element): Element[] {\n return Array.from(element.children).filter((child) => child.namespaceURI === W_NS);\n}\n\nfunction childOrCreate(parent: Element, localName: string, position: 'first' | 'last'): Element {\n const existing = children(parent).find((child) => child.localName === localName);\n if (existing) {\n return existing;\n }\n const created = parent.ownerDocument.createElementNS(W_NS, `w:${localName}`);\n return position === 'first'\n ? parent.insertBefore(created, parent.firstChild)\n : parent.appendChild(created);\n}\n\nfunction requireElement(dom: Document, localName: string): Element {\n const element = dom.getElementsByTagNameNS(W_NS, localName)[0];\n if (!element) {\n throw new Error(`Cannot apply font preset: styles.xml has no <w:${localName}> element`);\n }\n return element;\n}\n"]}
@@ -14,14 +14,41 @@ export interface LevelStyle {
14
14
  /** Font size in points. Chinese named sizes: size 2 (二号) = 22pt, size 3 (三号) = 16pt. */
15
15
  sizePt: number;
16
16
  bold: boolean;
17
+ /** Centers the paragraph, without the first-line indent. */
18
+ centered?: boolean;
17
19
  }
18
- /** Word line spacing rule. The presets only need single spacing so far. */
19
- export type LineSpacing = 'single';
20
+ /**
21
+ * Word line spacing rule:
22
+ *
23
+ * - `single`: single line spacing.
24
+ * - `grid`: exact line spacing at the line pitch of the page's document grid,
25
+ * with widow control off, so every full page holds `page.grid.linesPerPage`
26
+ * lines. Needs `page.grid`.
27
+ */
28
+ export type LineSpacing = 'single' | 'grid';
20
29
  export interface ParagraphStyle {
21
30
  /** Paragraph spacing before and after, in points. */
22
31
  beforePt: number;
23
32
  afterPt: number;
24
33
  lineSpacing: LineSpacing;
34
+ /** First-line indent, in characters of the body font size. */
35
+ firstLineIndentChars?: number;
36
+ }
37
+ /** Paper and text block, in millimeters. */
38
+ export interface PageLayout {
39
+ widthMm: number;
40
+ heightMm: number;
41
+ marginsMm: {
42
+ top: number;
43
+ right: number;
44
+ bottom: number;
45
+ left: number;
46
+ };
47
+ /** Word's document grid (文档网格): a fixed number of lines and characters. */
48
+ grid?: {
49
+ linesPerPage: number;
50
+ charsPerLine: number;
51
+ };
25
52
  }
26
53
  export interface FontPreset {
27
54
  body: LevelStyle;
@@ -29,20 +56,34 @@ export interface FontPreset {
29
56
  headings: LevelStyle[];
30
57
  /** Shared by the body text and every heading level. */
31
58
  paragraph: ParagraphStyle;
59
+ /**
60
+ * Page size and margins. Margins passed to `convertMarkdownToWord` as
61
+ * `pageMargins` take precedence.
62
+ */
63
+ page?: PageLayout;
32
64
  }
33
65
  /**
34
- * Fonts and sizes for Chinese official documents (公文):
66
+ * Chinese official documents (公文), after GB/T 9704-2012 《党政机关公文格式》:
35
67
  *
36
68
  * - Body: FangSong (仿宋), size 3
37
- * - Heading 1: FZXiaoBiaoSong (方正小标宋简体), size 2
69
+ * - Heading 1 (the title): FZXiaoBiaoSong (方正小标宋简体), size 2, centered (7.3.1)
38
70
  * - Heading 2: SimHei (黑体), size 3
39
71
  * - Heading 3: KaiTi (楷体), size 3
40
- * - Heading 4 and below: bold FangSong, size 3
72
+ * - Heading 4: FangSong, size 3, bold. The standard sets levels 3 and 4 in
73
+ * plain 仿宋, but a bolded fourth level is how these documents are made.
74
+ * - Heading 5 and below: FangSong, size 3, not bold.
75
+ * - A4 paper with a 37mm top and 28mm left margin around a 156 × 225mm text
76
+ * block (5.1, 5.2.1)
77
+ * - 22 lines of 28 characters per page (5.2.3), as a document grid with exact
78
+ * line spacing at its pitch
79
+ * - Paragraphs indented two characters (7.3.3), headings below the title too
41
80
  *
42
- * Every level uses Times New Roman for Latin text, no space before or after
43
- * paragraphs, and single line spacing.
81
+ * Every level uses Times New Roman for Latin text and no space before or after
82
+ * paragraphs. The standard names no Latin font; Times New Roman is common
83
+ * practice.
44
84
  */
45
85
  export declare const CHINESE_OFFICIAL_DOC_FONTS: FontPreset;
86
+ export declare function mmToTwips(mm: number): number;
46
87
  /** The presets offered in the UI, keyed by the value of their `<option>`. */
47
88
  export declare const FONT_PRESETS: Record<string, FontPreset>;
48
89
  /**
@@ -5,29 +5,55 @@ const SIZE_ER = 22;
5
5
  /** Chinese size 3 (三号). */
6
6
  const SIZE_SAN = 16;
7
7
  /**
8
- * Fonts and sizes for Chinese official documents (公文):
8
+ * Chinese official documents (公文), after GB/T 9704-2012 《党政机关公文格式》:
9
9
  *
10
10
  * - Body: FangSong (仿宋), size 3
11
- * - Heading 1: FZXiaoBiaoSong (方正小标宋简体), size 2
11
+ * - Heading 1 (the title): FZXiaoBiaoSong (方正小标宋简体), size 2, centered (7.3.1)
12
12
  * - Heading 2: SimHei (黑体), size 3
13
13
  * - Heading 3: KaiTi (楷体), size 3
14
- * - Heading 4 and below: bold FangSong, size 3
14
+ * - Heading 4: FangSong, size 3, bold. The standard sets levels 3 and 4 in
15
+ * plain 仿宋, but a bolded fourth level is how these documents are made.
16
+ * - Heading 5 and below: FangSong, size 3, not bold.
17
+ * - A4 paper with a 37mm top and 28mm left margin around a 156 × 225mm text
18
+ * block (5.1, 5.2.1)
19
+ * - 22 lines of 28 characters per page (5.2.3), as a document grid with exact
20
+ * line spacing at its pitch
21
+ * - Paragraphs indented two characters (7.3.3), headings below the title too
15
22
  *
16
- * Every level uses Times New Roman for Latin text, no space before or after
17
- * paragraphs, and single line spacing.
23
+ * Every level uses Times New Roman for Latin text and no space before or after
24
+ * paragraphs. The standard names no Latin font; Times New Roman is common
25
+ * practice.
18
26
  */
19
27
  export const CHINESE_OFFICIAL_DOC_FONTS = {
20
28
  body: { latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: false },
21
29
  headings: [
22
- { latin: LATIN_FONT, eastAsia: '方正小标宋简体', sizePt: SIZE_ER, bold: false },
30
+ {
31
+ latin: LATIN_FONT,
32
+ eastAsia: '方正小标宋简体',
33
+ sizePt: SIZE_ER,
34
+ bold: false,
35
+ centered: true,
36
+ },
23
37
  { latin: LATIN_FONT, eastAsia: '黑体', sizePt: SIZE_SAN, bold: false },
24
38
  { latin: LATIN_FONT, eastAsia: '楷体', sizePt: SIZE_SAN, bold: false },
25
39
  { latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: true },
26
- { latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: true },
27
- { latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: true },
40
+ { latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: false },
41
+ { latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: false },
28
42
  ],
29
- paragraph: { beforePt: 0, afterPt: 0, lineSpacing: 'single' },
43
+ paragraph: { beforePt: 0, afterPt: 0, lineSpacing: 'grid', firstLineIndentChars: 2 },
44
+ page: {
45
+ widthMm: 210,
46
+ heightMm: 297,
47
+ // 297 - 37 - 225 = 35 at the bottom, 210 - 28 - 156 = 26 on the right.
48
+ marginsMm: { top: 37, right: 26, bottom: 35, left: 28 },
49
+ grid: { linesPerPage: 22, charsPerLine: 28 },
50
+ },
30
51
  };
52
+ /** Twips (1/20 point) per millimeter. */
53
+ const TWIPS_PER_MM = 1440 / 25.4;
54
+ export function mmToTwips(mm) {
55
+ return Math.round(mm * TWIPS_PER_MM);
56
+ }
31
57
  /** The presets offered in the UI, keyed by the value of their `<option>`. */
32
58
  export const FONT_PRESETS = {
33
59
  'chinese-official': CHINESE_OFFICIAL_DOC_FONTS,
@@ -1 +1 @@
1
- {"version":3,"file":"font-presets.js","sourceRoot":"","sources":["../src/font-presets.ts"],"names":[],"mappings":"AAoCA,MAAM,UAAU,GAAG,iBAAiB,CAAC;AACrC,MAAM,SAAS,GAAG,IAAI,CAAC;AAEvB,2BAA2B;AAC3B,MAAM,OAAO,GAAG,EAAE,CAAC;AACnB,2BAA2B;AAC3B,MAAM,QAAQ,GAAG,EAAE,CAAC;AAEpB;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAe;IACpD,IAAI,EAAE,EAAE,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE;IAC/E,QAAQ,EAAE;QACR,EAAE,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE;QACxE,EAAE,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE;QACpE,EAAE,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE;QACpE,EAAE,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE;QACxE,EAAE,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE;QACxE,EAAE,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE;KACzE;IACD,SAAS,EAAE,EAAE,QAAQ,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,WAAW,EAAE,QAAQ,EAAE;CAC9D,CAAC;AAEF,6EAA6E;AAC7E,MAAM,CAAC,MAAM,YAAY,GAA+B;IACtD,kBAAkB,EAAE,0BAA0B;CAC/C,CAAC;AAEF;;;;GAIG;AACH,MAAM,UAAU,eAAe,CAAC,IAAY;IAC1C,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,EAAE,MAAM,IAAI,CAAC,CAAC;IACnD,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,kBAAkB,CAAC,EAAE,MAAM,IAAI,CAAC,CAAC;IACxD,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,4CAA4C,CAAC,EAAE,MAAM,IAAI,CAAC,CAAC;IAEnF,OAAO,GAAG,IAAI,EAAE,IAAI,GAAG,GAAG,OAAO,IAAI,GAAG,IAAI,IAAI,GAAG,GAAG,GAAG,EAAE,CAAC;AAC9D,CAAC","sourcesContent":["/**\n * Typography for one level of a document.\n *\n * Word selects a typeface per character class: Latin letters and digits are\n * rendered from the `w:ascii`/`w:hAnsi` run-property slots, Chinese characters\n * from `w:eastAsia`. Naming both fonts per level is therefore enough to keep\n * Chinese text in a Chinese face and Latin text in a Latin one.\n */\nexport interface LevelStyle {\n /** Typeface for Latin letters, digits and punctuation. */\n latin: string;\n /** Typeface for Chinese characters. */\n eastAsia: string;\n /** Font size in points. Chinese named sizes: size 2 (二号) = 22pt, size 3 (三号) = 16pt. */\n sizePt: number;\n bold: boolean;\n}\n\n/** Word line spacing rule. The presets only need single spacing so far. */\nexport type LineSpacing = 'single';\n\nexport interface ParagraphStyle {\n /** Paragraph spacing before and after, in points. */\n beforePt: number;\n afterPt: number;\n lineSpacing: LineSpacing;\n}\n\nexport interface FontPreset {\n body: LevelStyle;\n /** Six entries, applied to the `Heading1` - `Heading6` styles. */\n headings: LevelStyle[];\n /** Shared by the body text and every heading level. */\n paragraph: ParagraphStyle;\n}\n\nconst LATIN_FONT = 'Times New Roman';\nconst BODY_FONT = '仿宋';\n\n/** Chinese size 2 (二号). */\nconst SIZE_ER = 22;\n/** Chinese size 3 (三号). */\nconst SIZE_SAN = 16;\n\n/**\n * Fonts and sizes for Chinese official documents (公文):\n *\n * - Body: FangSong (仿宋), size 3\n * - Heading 1: FZXiaoBiaoSong (方正小标宋简体), size 2\n * - Heading 2: SimHei (黑体), size 3\n * - Heading 3: KaiTi (楷体), size 3\n * - Heading 4 and below: bold FangSong, size 3\n *\n * Every level uses Times New Roman for Latin text, no space before or after\n * paragraphs, and single line spacing.\n */\nexport const CHINESE_OFFICIAL_DOC_FONTS: FontPreset = {\n body: { latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: false },\n headings: [\n { latin: LATIN_FONT, eastAsia: '方正小标宋简体', sizePt: SIZE_ER, bold: false },\n { latin: LATIN_FONT, eastAsia: '黑体', sizePt: SIZE_SAN, bold: false },\n { latin: LATIN_FONT, eastAsia: '楷体', sizePt: SIZE_SAN, bold: false },\n { latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: true },\n { latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: true },\n { latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: true },\n ],\n paragraph: { beforePt: 0, afterPt: 0, lineSpacing: 'single' },\n};\n\n/** The presets offered in the UI, keyed by the value of their `<option>`. */\nexport const FONT_PRESETS: Record<string, FontPreset> = {\n 'chinese-official': CHINESE_OFFICIAL_DOC_FONTS,\n};\n\n/**\n * Whether most of the letters in `text` are Chinese characters, used to suggest\n * the Chinese preset. Kana means Japanese, which also uses Han characters, so\n * text with a meaningful share of kana does not count.\n */\nexport function isMostlyChinese(text: string): boolean {\n const letters = text.match(/\\p{L}/gu)?.length ?? 0;\n const han = text.match(/\\p{Script=Han}/gu)?.length ?? 0;\n const kana = text.match(/[\\p{Script=Hiragana}\\p{Script=Katakana}]/gu)?.length ?? 0;\n\n return han >= 10 && han / letters >= 0.5 && kana < han / 10;\n}\n"]}
1
+ {"version":3,"file":"font-presets.js","sourceRoot":"","sources":["../src/font-presets.ts"],"names":[],"mappings":"AA6DA,MAAM,UAAU,GAAG,iBAAiB,CAAC;AACrC,MAAM,SAAS,GAAG,IAAI,CAAC;AAEvB,2BAA2B;AAC3B,MAAM,OAAO,GAAG,EAAE,CAAC;AACnB,2BAA2B;AAC3B,MAAM,QAAQ,GAAG,EAAE,CAAC;AAEpB;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAe;IACpD,IAAI,EAAE,EAAE,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE;IAC/E,QAAQ,EAAE;QACR;YACE,KAAK,EAAE,UAAU;YACjB,QAAQ,EAAE,SAAS;YACnB,MAAM,EAAE,OAAO;YACf,IAAI,EAAE,KAAK;YACX,QAAQ,EAAE,IAAI;SACf;QACD,EAAE,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,E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O,GAAG,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,EAAE,MAAM,IAAI,CAAC,CAAC;IACnD,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,kBAAkB,CAAC,EAAE,MAAM,IAAI,CAAC,CAAC;IACxD,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,4CAA4C,CAAC,EAAE,MAAM,IAAI,CAAC,CAAC;IAEnF,OAAO,GAAG,IAAI,EAAE,IAAI,GAAG,GAAG,OAAO,IAAI,GAAG,IAAI,IAAI,GAAG,GAAG,GAAG,EAAE,CAAC;AAC9D,CAAC","sourcesContent":["/**\n * Typography for one level of a document.\n *\n * Word selects a typeface per character class: Latin letters and digits are\n * rendered from the `w:ascii`/`w:hAnsi` run-property slots, Chinese characters\n * from `w:eastAsia`. Naming both fonts per level is therefore enough to keep\n * Chinese text in a Chinese face and Latin text in a Latin one.\n */\nexport interface LevelStyle {\n /** Typeface for Latin letters, digits and punctuation. */\n latin: string;\n /** Typeface for Chinese characters. */\n eastAsia: string;\n /** Font size in points. Chinese named sizes: size 2 (二号) = 22pt, size 3 (三号) = 16pt. */\n sizePt: number;\n bold: boolean;\n /** Centers the paragraph, without the first-line indent. */\n centered?: boolean;\n}\n\n/**\n * Word line spacing rule:\n *\n * - `single`: single line spacing.\n * - `grid`: exact line spacing at the line pitch of the page's document grid,\n * with widow control off, so every full page holds `page.grid.linesPerPage`\n * lines. Needs `page.grid`.\n */\nexport type LineSpacing = 'single' | 'grid';\n\nexport interface ParagraphStyle {\n /** Paragraph spacing before and after, in points. */\n beforePt: number;\n afterPt: number;\n lineSpacing: LineSpacing;\n /** First-line indent, in characters of the body font size. */\n firstLineIndentChars?: number;\n}\n\n/** Paper and text block, in millimeters. */\nexport interface PageLayout {\n widthMm: number;\n heightMm: number;\n marginsMm: { top: number; right: number; bottom: number; left: number };\n /** Word's document grid (文档网格): a fixed number of lines and characters. */\n grid?: { linesPerPage: number; charsPerLine: number };\n}\n\nexport interface FontPreset {\n body: LevelStyle;\n /** Six entries, applied to the `Heading1` - `Heading6` styles. */\n headings: LevelStyle[];\n /** Shared by the body text and every heading level. */\n paragraph: ParagraphStyle;\n /**\n * Page size and margins. Margins passed to `convertMarkdownToWord` as\n * `pageMargins` take precedence.\n */\n page?: PageLayout;\n}\n\nconst LATIN_FONT = 'Times New Roman';\nconst BODY_FONT = '仿宋';\n\n/** Chinese size 2 (二号). */\nconst SIZE_ER = 22;\n/** Chinese size 3 (三号). */\nconst SIZE_SAN = 16;\n\n/**\n * Chinese official documents (公文), after GB/T 9704-2012 《党政机关公文格式》:\n *\n * - Body: FangSong (仿宋), size 3\n * - Heading 1 (the title): FZXiaoBiaoSong (方正小标宋简体), size 2, centered (7.3.1)\n * - Heading 2: SimHei (黑体), size 3\n * - Heading 3: KaiTi (楷体), size 3\n * - Heading 4: FangSong, size 3, bold. The standard sets levels 3 and 4 in\n * plain 仿宋, but a bolded fourth level is how these documents are made.\n * - Heading 5 and below: FangSong, size 3, not bold.\n * - A4 paper with a 37mm top and 28mm left margin around a 156 × 225mm text\n * block (5.1, 5.2.1)\n * - 22 lines of 28 characters per page (5.2.3), as a document grid with exact\n * line spacing at its pitch\n * - Paragraphs indented two characters (7.3.3), headings below the title too\n *\n * Every level uses Times New Roman for Latin text and no space before or after\n * paragraphs. The standard names no Latin font; Times New Roman is common\n * practice.\n */\nexport const CHINESE_OFFICIAL_DOC_FONTS: FontPreset = {\n body: { latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: false },\n headings: [\n {\n latin: LATIN_FONT,\n eastAsia: '方正小标宋简体',\n sizePt: SIZE_ER,\n bold: false,\n centered: true,\n },\n { latin: LATIN_FONT, eastAsia: '黑体', sizePt: SIZE_SAN, bold: false },\n { latin: LATIN_FONT, eastAsia: '楷体', sizePt: SIZE_SAN, bold: false },\n { latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: true },\n { latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: false },\n { latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: false },\n ],\n paragraph: { beforePt: 0, afterPt: 0, lineSpacing: 'grid', firstLineIndentChars: 2 },\n page: {\n widthMm: 210,\n heightMm: 297,\n // 297 - 37 - 225 = 35 at the bottom, 210 - 28 - 156 = 26 on the right.\n marginsMm: { top: 37, right: 26, bottom: 35, left: 28 },\n grid: { linesPerPage: 22, charsPerLine: 28 },\n },\n};\n\n/** Twips (1/20 point) per millimeter. */\nconst TWIPS_PER_MM = 1440 / 25.4;\n\nexport function mmToTwips(mm: number): number {\n return Math.round(mm * TWIPS_PER_MM);\n}\n\n/** The presets offered in the UI, keyed by the value of their `<option>`. */\nexport const FONT_PRESETS: Record<string, FontPreset> = {\n 'chinese-official': CHINESE_OFFICIAL_DOC_FONTS,\n};\n\n/**\n * Whether most of the letters in `text` are Chinese characters, used to suggest\n * the Chinese preset. Kana means Japanese, which also uses Han characters, so\n * text with a meaningful share of kana does not count.\n */\nexport function isMostlyChinese(text: string): boolean {\n const letters = text.match(/\\p{L}/gu)?.length ?? 0;\n const han = text.match(/\\p{Script=Han}/gu)?.length ?? 0;\n const kana = text.match(/[\\p{Script=Hiragana}\\p{Script=Katakana}]/gu)?.length ?? 0;\n\n return han >= 10 && han / letters >= 0.5 && kana < han / 10;\n}\n"]}
package/build/main.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  export { convertMarkdownToWord, type ConversionOptions } from './converter.js';
2
2
  export { extractTitle, parseMarkdownToHtml } from './markdown-parser.js';
3
- export { CHINESE_OFFICIAL_DOC_FONTS, FONT_PRESETS, type FontPreset, type LevelStyle, type LineSpacing, type ParagraphStyle, } from './font-presets.js';
3
+ export { CHINESE_OFFICIAL_DOC_FONTS, FONT_PRESETS, type FontPreset, type LevelStyle, type LineSpacing, type PageLayout, type ParagraphStyle, } from './font-presets.js';
package/build/main.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"main.js","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,+EAA+E;AAC/E,0CAA0C;AAC1C,OAAO,EAAE,qBAAqB,EAA0B,MAAM,gBAAgB,CAAC;AAC/E,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AACzE,OAAO,EACL,0BAA0B,EAC1B,YAAY,GAKb,MAAM,mBAAmB,CAAC","sourcesContent":["// The npm package's entry: the converter without the browser UI (index.ts).\n// Browsers and bundlers load this directly; Node loads node.ts, which supplies\n// the DOM APIs the converter needs first.\nexport { convertMarkdownToWord, type ConversionOptions } from './converter.js';\nexport { extractTitle, parseMarkdownToHtml } from './markdown-parser.js';\nexport {\n CHINESE_OFFICIAL_DOC_FONTS,\n FONT_PRESETS,\n type FontPreset,\n type LevelStyle,\n type LineSpacing,\n type ParagraphStyle,\n} from './font-presets.js';\n"]}
1
+ {"version":3,"file":"main.js","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,+EAA+E;AAC/E,0CAA0C;AAC1C,OAAO,EAAE,qBAAqB,EAA0B,MAAM,gBAAgB,CAAC;AAC/E,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AACzE,OAAO,EACL,0BAA0B,EAC1B,YAAY,GAMb,MAAM,mBAAmB,CAAC","sourcesContent":["// The npm package's entry: the converter without the browser UI (index.ts).\n// Browsers and bundlers load this directly; Node loads node.ts, which supplies\n// the DOM APIs the converter needs first.\nexport { convertMarkdownToWord, type ConversionOptions } from './converter.js';\nexport { extractTitle, parseMarkdownToHtml } from './markdown-parser.js';\nexport {\n CHINESE_OFFICIAL_DOC_FONTS,\n FONT_PRESETS,\n type FontPreset,\n type LevelStyle,\n type LineSpacing,\n type PageLayout,\n type ParagraphStyle,\n} from './font-presets.js';\n"]}
@@ -7,3 +7,8 @@ export declare const XML_NS = "http://www.w3.org/XML/1998/namespace";
7
7
  * copied back from the source.
8
8
  */
9
9
  export declare function keepXmlDeclaration(original: string, serialized: string): string;
10
+ /**
11
+ * The `localName` child of a `<w:pPr>`, created in schema order if missing.
12
+ * WinWord rejects paragraph properties that are out of order.
13
+ */
14
+ export declare function paragraphProperty(pPr: Element, localName: string): Element;
package/build/xml-part.js CHANGED
@@ -13,4 +13,64 @@ export function keepXmlDeclaration(original, serialized) {
13
13
  }
14
14
  return serialized;
15
15
  }
16
+ /** The children of `<w:pPr>`, in the order the schema requires. */
17
+ const PARAGRAPH_PROPERTY_ORDER = [
18
+ 'pStyle',
19
+ 'keepNext',
20
+ 'keepLines',
21
+ 'pageBreakBefore',
22
+ 'framePr',
23
+ 'widowControl',
24
+ 'numPr',
25
+ 'suppressLineNumbers',
26
+ 'pBdr',
27
+ 'shd',
28
+ 'tabs',
29
+ 'suppressAutoHyphens',
30
+ 'kinsoku',
31
+ 'wordWrap',
32
+ 'overflowPunct',
33
+ 'topLinePunct',
34
+ 'autoSpaceDE',
35
+ 'autoSpaceDN',
36
+ 'bidi',
37
+ 'adjustRightInd',
38
+ 'snapToGrid',
39
+ 'spacing',
40
+ 'ind',
41
+ 'contextualSpacing',
42
+ 'mirrorIndents',
43
+ 'suppressOverlap',
44
+ 'jc',
45
+ 'textDirection',
46
+ 'textAlignment',
47
+ 'textboxTightWrap',
48
+ 'outlineLvl',
49
+ 'divId',
50
+ 'cnfStyle',
51
+ 'rPr',
52
+ 'sectPr',
53
+ 'pPrChange',
54
+ ];
55
+ /**
56
+ * The `localName` child of a `<w:pPr>`, created in schema order if missing.
57
+ * WinWord rejects paragraph properties that are out of order.
58
+ */
59
+ export function paragraphProperty(pPr, localName) {
60
+ const rank = PARAGRAPH_PROPERTY_ORDER.indexOf(localName);
61
+ let before = null;
62
+ for (const child of Array.from(pPr.children)) {
63
+ if (child.namespaceURI !== WORDPROCESSING_NS) {
64
+ continue;
65
+ }
66
+ if (child.localName === localName) {
67
+ return child;
68
+ }
69
+ if (before === null && PARAGRAPH_PROPERTY_ORDER.indexOf(child.localName) > rank) {
70
+ before = child;
71
+ }
72
+ }
73
+ const created = pPr.ownerDocument.createElementNS(WORDPROCESSING_NS, `w:${localName}`);
74
+ return pPr.insertBefore(created, before);
75
+ }
16
76
  //# sourceMappingURL=xml-part.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"xml-part.js","sourceRoot":"","sources":["../src/xml-part.ts"],"names":[],"mappings":"AAAA,8DAA8D;AAC9D,MAAM,CAAC,MAAM,iBAAiB,GAAG,8DAA8D,CAAC;AAEhG,4DAA4D;AAC5D,MAAM,CAAC,MAAM,MAAM,GAAG,sCAAsC,CAAC;AAE7D;;;GAGG;AACH,MAAM,UAAU,kBAAkB,CAAC,QAAgB,EAAE,UAAkB;IACrE,MAAM,WAAW,GAAG,sBAAsB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IAC1D,IAAI,WAAW,IAAI,CAAC,UAAU,CAAC,SAAS,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;QAC5D,OAAO,GAAG,WAAW,CAAC,CAAC,CAAC,KAAK,UAAU,EAAE,CAAC;IAC5C,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["/** Namespace of the WordprocessingML parts inside a .docx. */\nexport const WORDPROCESSING_NS = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';\n\n/** Namespace of the `xml:` prefix, used for `xml:space`. */\nexport const XML_NS = 'http://www.w3.org/XML/1998/namespace';\n\n/**\n * `XMLSerializer` drops the XML declaration that OPC parts start with, so it is\n * copied back from the source.\n */\nexport function keepXmlDeclaration(original: string, serialized: string): string {\n const declaration = /^\\s*(<\\?xml[^>]*\\?>)/.exec(original);\n if (declaration && !serialized.trimStart().startsWith('<?')) {\n return `${declaration[1]}\\n${serialized}`;\n }\n return serialized;\n}\n"]}
1
+ {"version":3,"file":"xml-part.js","sourceRoot":"","sources":["../src/xml-part.ts"],"names":[],"mappings":"AAAA,8DAA8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CAAC,YAAY,KAAK,iBAAiB,EAAE,CAAC;YAC7C,SAAS;QACX,CAAC;QACD,IAAI,KAAK,CAAC,SAAS,KAAK,SAAS,EAAE,CAAC;YAClC,OAAO,KAAK,CAAC;QACf,CAAC;QACD,IAAI,MAAM,KAAK,IAAI,IAAI,wBAAwB,CAAC,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,CAAC;YAChF,MAAM,GAAG,KAAK,CAAC;QACjB,CAAC;IACH,CAAC;IACD,MAAM,OAAO,GAAG,GAAG,CAAC,aAAa,CAAC,eAAe,CAAC,iBAAiB,EAAE,KAAK,SAAS,EAAE,CAAC,CAAC;IACvF,OAAO,GAAG,CAAC,YAAY,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;AAC3C,CAAC","sourcesContent":["/** Namespace of the WordprocessingML parts inside a .docx. */\nexport const WORDPROCESSING_NS = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';\n\n/** Namespace of the `xml:` prefix, used for `xml:space`. */\nexport const XML_NS = 'http://www.w3.org/XML/1998/namespace';\n\n/**\n * `XMLSerializer` drops the XML declaration that OPC parts start with, so it is\n * copied back from the source.\n */\nexport function keepXmlDeclaration(original: string, serialized: string): string {\n const declaration = /^\\s*(<\\?xml[^>]*\\?>)/.exec(original);\n if (declaration && !serialized.trimStart().startsWith('<?')) {\n return `${declaration[1]}\\n${serialized}`;\n }\n return serialized;\n}\n\n/** The children of `<w:pPr>`, in the order the schema requires. */\nconst PARAGRAPH_PROPERTY_ORDER = [\n 'pStyle',\n 'keepNext',\n 'keepLines',\n 'pageBreakBefore',\n 'framePr',\n 'widowControl',\n 'numPr',\n 'suppressLineNumbers',\n 'pBdr',\n 'shd',\n 'tabs',\n 'suppressAutoHyphens',\n 'kinsoku',\n 'wordWrap',\n 'overflowPunct',\n 'topLinePunct',\n 'autoSpaceDE',\n 'autoSpaceDN',\n 'bidi',\n 'adjustRightInd',\n 'snapToGrid',\n 'spacing',\n 'ind',\n 'contextualSpacing',\n 'mirrorIndents',\n 'suppressOverlap',\n 'jc',\n 'textDirection',\n 'textAlignment',\n 'textboxTightWrap',\n 'outlineLvl',\n 'divId',\n 'cnfStyle',\n 'rPr',\n 'sectPr',\n 'pPrChange',\n];\n\n/**\n * The `localName` child of a `<w:pPr>`, created in schema order if missing.\n * WinWord rejects paragraph properties that are out of order.\n */\nexport function paragraphProperty(pPr: Element, localName: string): Element {\n const rank = PARAGRAPH_PROPERTY_ORDER.indexOf(localName);\n let before: Element | null = null;\n for (const child of Array.from(pPr.children)) {\n if (child.namespaceURI !== WORDPROCESSING_NS) {\n continue;\n }\n if (child.localName === localName) {\n return child;\n }\n if (before === null && PARAGRAPH_PROPERTY_ORDER.indexOf(child.localName) > rank) {\n before = child;\n }\n }\n const created = pPr.ownerDocument.createElementNS(WORDPROCESSING_NS, `w:${localName}`);\n return pPr.insertBefore(created, before);\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "markdown-to-word",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Convert GitHub Flavored Markdown to Word (.docx) documents in Node or the browser",
5
5
  "type": "module",
6
6
  "main": "build/main.js",