DEV Community

visiohex
visiohex

Posted on

Building a 100% Client-Side Markdown-to-Word (.docx) Converter with Raw OpenXML and fflate

Most online "Markdown to Word" converters upload your .md file to a backend running Pandoc or LibreOffice. That works, but it adds server latency, file-size costs, and an unnecessary privacy boundary for ordinary notes, specs, and LLM outputs.

When we built the free Markdown to Word (.docx) converter at PDF to MD, we wanted the entire .md → .docx pipeline to run 100% locally in the browser with zero file uploads, no account required, and a minimal client bundle footprint.

Instead of pulling in a 400 KB+ Word generation framework, we parsed Markdown into an AST with unified + remark-parse + remark-gfm, emitted raw OOXML (word/document.xml, word/styles.xml, word/numbering.xml, word/_rels/document.xml.rels), and zipped the six XML parts synchronously with fflate.

The entire converter is under 500 lines of TypeScript. Here are the exact architecture decisions and edge cases we hit along the way.


Why a .docx file is smaller to assemble than you think

An Office Open XML (.docx) archive only needs six files to open cleanly in Microsoft Word, Google Docs, Apple Pages, and LibreOffice Writer without triggering a "corrupt file" repair dialog:

  1. [Content_Types].xml — declares MIME types for .rels, .xml, and the three main Word parts.
  2. _rels/.rels — points Word at word/document.xml.
  3. word/styles.xml — defines Normal and Heading1–Heading6 (plus CJK fallback via w:eastAsia="Microsoft YaHei").
  4. word/numbering.xml — defines two abstract list definitions: bullet lists (numId="1") and decimal/alpha/roman ordered lists (numId="2"), up to 4 nesting levels.
  5. word/_rels/document.xml.rels — links styles.xml, numbering.xml, and every external <w:hyperlink> target.
  6. word/document.xml — the actual <w:body> paragraphs, lists, code blocks, blockquotes, and tables.

Packaging those six strings into a downloadable Blob with fflate takes 8 lines:

import { strToU8, zipSync } from 'fflate';
import remarkGfm from 'remark-gfm';
import remarkParse from 'remark-parse';
import { unified } from 'unified';

export function convertMarkdownToDocxBytes(markdown: string): Uint8Array {
  const tree = unified()
    .use(remarkParse)
    .use(remarkGfm)
    .parse(stripXmlControlChars(markdown));

  const ctx = { links: [] as Array<{ id: string; url: string }> };
  const bodyXml = (tree.children ?? [])
    .map((node) => renderBlockNode(node, ctx, 0))
    .join('');

  return zipSync({
    '[Content_Types].xml': strToU8(CONTENT_TYPES_XML),
    '_rels/.rels': strToU8(ROOT_RELS_XML),
    'word/_rels/document.xml.rels': strToU8(buildDocumentRelsXml(ctx.links)),
    'word/styles.xml': strToU8(STYLES_XML),
    'word/numbering.xml': strToU8(NUMBERING_XML),
    'word/document.xml': strToU8(wrapDocumentXml(bodyXml)),
  });
}
Enter fullscreen mode Exit fullscreen mode

5 Subtle OOXML Pitfalls That Break Real Documents

1. XML 1.0 Control Characters Silently Corrupt .docx Files

Pasted PDF extracts and terminal outputs often contain stray \x00–\x08, \x0B, \x0C, or \x0E–\x1F bytes. They are valid UTF-8 strings in JavaScript, so JSON.stringify and DOM rendering ignore them — but Word rejects any .docx containing XML 1.0 illegal control characters as unreadable.

Stripping them before parsing prevents silent corruption:

function stripXmlControlChars(value: string): string {
  return value.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, '');
}
Enter fullscreen mode Exit fullscreen mode

2. Preserving Whitespace in Runs (xml:space="preserve")

In OOXML, leading or trailing spaces inside <w:t> are collapsed unless you add xml:space="preserve". That bites you immediately whenever inline formatting (**bold** or `code`) sits next to plain text — "Hello **world**" turns into "Helloworld" without it.

Every <w:t> element we emit includes xml:space="preserve", and multi-line strings split on \r?\n emit explicit <w:br/> elements inside the run.

3. External Hyperlinks Need Both Deduplication and a Protocol Allowlist

Word does not store URLs inline on <w:hyperlink>. Instead, you register each URL in word/_rels/document.xml.rels with TargetMode="External" and reference its rId from <w:hyperlink r:id="rIdLink1" w:history="1">.

To prevent javascript: or file:// payloads from ending up in exported Word files, we validate every URL before registering it:

const SAFE_LINK_PROTOCOL = /^(https?:|mailto:)/i;

function registerLink(ctx: BuildContext, url: string): string | null {
  const trimmed = url.trim();
  if (!SAFE_LINK_PROTOCOL.test(trimmed)) return null;
  const existing = ctx.links.find((entry) => entry.url === trimmed);
  if (existing) return existing.id;
  const id = `rIdLink${ctx.links.length + 1}`;
  ctx.links.push({ id, url: trimmed });
  return id;
}
Enter fullscreen mode Exit fullscreen mode

4. Making GFM Tables Look Native in Word

A bare <w:tbl> renders with zero borders and cramped cells in Word. To make GitHub Flavored Markdown tables open cleanly right away, we add:

  • <w:tblW w:w="5000" w:type="pct"/> (100% page width, measured in fiftieths of a percent)
  • Subtle outer (#CBD5E1) and inner (#E2E8F0) single-line borders
  • Cell padding (<w:tcMar> top/bottom 90 dxa, left/right 120 dxa)
  • <w:trPr><w:tblHeader/></w:trPr> plus #F3F4F6 shading and bold runs on row 0 so the header repeats across page breaks
  • Column alignment mapped directly from remark-gfm's node.align array (center, right, default left)

5. Nested Lists & GFM Task Checklists

Markdown list items can contain multiple paragraphs, nested sub-lists, and GFM task checkboxes (- [x] Done). In Word:

  • Only the first paragraph in a list item should receive <w:numPr><w:ilvl/><w:numId/></w:numPr>. Continuation paragraphs use matching left indentation (720 * (level + 1) twips) so they align cleanly without spawning a duplicate bullet.
  • For task lists (item.checked === true | false), prefixing the first run with bold ☑ / ☐ works identically across Word, Google Docs, and Pages without requiring macro-enabled form controls.

Bonus: Live Edit-Then-Download Without Re-Uploading

Because convertMarkdownToDocxBytes runs synchronously in a few milliseconds on typical docs, users on pdf-to-md.app/markdown-to-word can paste or drop Markdown, tweak headings or tables in the live preview editor, and regenerate a fresh .docx (or batch ZIP) straight from their edited buffer without a single network request.

If you want to inspect the output directly, try pasting a Markdown doc with GFM tables and fenced code blocks at pdf-to-md.app/markdown-to-word, or check out the rest of our browser-local document tools (PDF, Word, HTML, and URL to Markdown) at pdf-to-md.app.

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

The six-file minimum is the detail I did not expect — I had always assumed a valid Word file needed far more plumbing than six parts, so skipping the 400 KB+ framework and hand-rolling the archive in under 500 lines of TypeScript is a genuinely lean trade. The control-character stripping is the pitfall that would have bitten me hardest, since pasted terminal output looks harmless in JavaScript and then Word rejects the whole file as unreadable. The preserve-whitespace fix is my favorite though: losing the space in "Hello bold world" is exactly the kind of bug that ships silently for months. Which part gave you more trouble in practice — the table styling with its full-width layout and cell padding, or the nested-list indentation at 720 twips per level?