To generate a DOCX from Markdown in JavaScript in the browser, you parse the Markdown into tokens and build real OOXML from them — you do not render HTML and rename the file. We did this for a Markdown to Word converter that runs entirely client-side: marked.lexer() gives you a token tree, and docx turns that tree into Paragraph, Table and ImageRun objects it can pack into a .docx. Here is a small executable mapping, followed by the production features and their limits.
Why create an OOXML package instead of renaming HTML?
A .docx is an Office Open XML package: a ZIP container holding parts such as word/document.xml, styles and relationships. Changing an HTML file's extension does not create that package. Word can import some HTML, but that is a separate workflow whose formatting depends on its import rules. Generate OOXML when your downstream system expects a DOCX package.
Our conversion has three stages:
- Parse Markdown with
marked.lexer(md, { gfm: true }). - Map block and inline tokens into
docxobjects. - Pack the document with
Packer.toBlob()for the browser.
The example uses the versions installed in our tool: marked@12.0.2 and docx@9.5.1. These are pinned example versions, not a claim that they are the newest releases.
How do you map marked tokens to DOCX in JavaScript?
Start with a small converter whose limits are explicit. This ES module supports headings, paragraphs, bold, italic, inline code and fenced code blocks. It rejects tables, lists, links, images and other unsupported tokens so that a successful export does not silently discard them. Our production converter supports more elements; those are described separately below.
Install the dependencies in a bundler project:
npm install marked@12.0.2 docx@9.5.1
Save this as converter.mjs:
import { marked } from 'marked';
import { Document, Packer, Paragraph, TextRun, HeadingLevel } from 'docx';
const headings = [
HeadingLevel.HEADING_1, HeadingLevel.HEADING_2,
HeadingLevel.HEADING_3, HeadingLevel.HEADING_4,
HeadingLevel.HEADING_5, HeadingLevel.HEADING_6,
];
function runs(tokens, style = {}) {
return tokens.flatMap(t => {
if (t.type === 'strong') return runs(t.tokens, { ...style, bold: true });
if (t.type === 'em') return runs(t.tokens, { ...style, italics: true });
if (t.type === 'text' && t.tokens) return runs(t.tokens, style);
if (['text', 'escape', 'codespan'].includes(t.type)) {
return [new TextRun({ ...style, text: t.text,
...(t.type === 'codespan' ? { font: 'Consolas' } : {}) })];
}
throw new Error(`Unsupported inline token: ${t.type}`);
});
}
export async function convert(md) {
const children = marked.lexer(md, { gfm: true }).flatMap(t => {
if (t.type === 'space') return [];
if (t.type === 'heading') return [new Paragraph({
heading: headings[t.depth - 1], children: runs(t.tokens),
})];
if (t.type === 'paragraph') return [new Paragraph({ children: runs(t.tokens) })];
if (t.type === 'code') return t.text.split('\n').map(line => new Paragraph({
children: [new TextRun({ text: line || ' ', font: 'Consolas' })],
}));
throw new Error(`Unsupported block token: ${t.type}`);
});
if (!children.length) throw new Error('No document content');
return Packer.toBlob(new Document({ sections: [{ children }] }));
}
Call convert(markdown) from your application's export button. Await the returned Blob, create a temporary object URL, attach it to an anchor with a .docx download name and click the anchor; remove the anchor and revoke the URL after the download has been initiated. Handle the error by showing the unsupported token to the user. Browser imports need a bundler or another way of resolving the two package names.
For a local package check, import convert in Node 20+, call it with a sample containing headings, bold, italic and code, then save new Uint8Array(await blob.arrayBuffer()) using Node's file API. Unzip the result and inspect the document XML; this verifies the package structure, not the appearance in every Word client.
Mapping each marked token to a Word element
| marked token | docx element | What Word shows |
|---|---|---|
heading (depth 1–6) |
Paragraph({ heading }) |
Built-in Heading 1–6 styles |
paragraph, text
|
Paragraph |
Body text |
strong / em / del
|
TextRun flags |
<w:b/> / <w:i/> / <w:strike/>
|
codespan, code
|
TextRun with mono font |
Consolas, optional grey shading |
link |
ExternalHyperlink |
Real clickable link in document.xml.rels
|
list (ordered) |
Paragraph({ numbering }) |
Entry in word/numbering.xml
|
list (unordered) |
Paragraph({ bullet }) |
Word bullet, ● ○ ■ by level |
table |
Table / TableRow / TableCell
|
Real Word table with repeating header |
hr |
Paragraph with a bottom border |
Horizontal rule |
br |
TextRun({ break: 1 }) |
Soft line break inside one paragraph |
def (reference definition) |
— | Dropped, as it should be |
Why can CJK text display as boxes?
Font selection and character encoding are different problems. In our production mapper, each run carries Latin font slots and an eastAsia slot for Chinese, Japanese and Korean text. This records the font preference; it does not embed a font or guarantee that the recipient has it installed. Check the document on the receiving device. The minimal example above leaves font selection to the document defaults except for code.
Detail two: ordered-list numbering instances
A single reference in numbering.config is a numbering definition, not a counter. Two separate ordered lists sharing one reference and one instance will continue each other — your second list starts at 4. The fix is the instance field: bump a counter for every top-level list (ctx.olInstance++), pass the same instance down through nested ordered items, and allocate a fresh one when an unordered list contains an ordered child.
One consequence worth documenting for your users: because every level's <w:start> is 1, Markdown that says 5. still renders as 1. in Word. Markdown's start number is not carried through this mapping.
Why are remote images missing from the DOCX?
The minimal example rejects images. Our production tool embeds only supported inline data: PNG, JPEG, GIF and BMP images. It does not fetch remote or relative image addresses while creating the DOCX. Supported images wider than 600 px are scaled down proportionally; smaller images are not enlarged.
Other images leave a placeholder, or a text line with their address when Images → Turn into a link line is selected. Use descriptive alt text. A known limitation of the shipped core is that its placeholder wording is Chinese; remove that line in Word or use link mode with alt text if it appears in your export.
The web preview has a separate policy: its iframe can request remote image URLs from their hosts. Local DOCX generation therefore does not mean the page makes no network requests. Remove remote images before pasting a document if those requests would be inappropriate.
What this approach does not give you
The shipped converter has these boundaries; the minimal example above supports only the smaller subset it explicitly handles:
-
No syntax highlighting. A fenced block's
langis available on the token and simply isn't read — you get monospace plus optional shading, no colour. -
No footnotes or YAML front matter.
[^1]: noteis adef-shaped token and disappears;----delimited front matter is parsed as content. - No table of contents, page numbers, headers, footers, columns or math. Markdown has no syntax for them and this mapping generates none.
-
Headings inside blockquotes lose their style.
> # Titlebecomes a decorated italic paragraph, because the blockquote branch renders its children as quote paragraphs. - Code blocks inside list items flatten. They end up as plain text in the list item's paragraph.
-
Nesting caps at 9 levels (
level0–8); deeper items pile up at level 9. - The preview is not Word. Our page renders the same Markdown as HTML in a sandboxed iframe for structure checking only, and that iframe does fetch remote images — so image URLs are visible to their host even though the Markdown itself never leaves the device. Fonts, line spacing and page breaks have to be judged in Word.
And the non-browser alternative, because it is often the right answer: if you are converting Markdown in a build step rather than in a user's tab, Pandoc with a reference .docx gives you far more control over styles than any hand-written mapping. The browser route earns its keep when the input must not be uploaded.
FAQ
Can you really generate a DOCX from Markdown in JavaScript with no server?
Yes. Parsing and DOCX assembly run locally in JavaScript. Our tool caps input at 10 MB of UTF-8 Markdown and loads library code on demand; the web preview can also request remote images. This is an in-memory pipeline, not a streaming converter.
Why not just convert Markdown to HTML and rename it .docx?
Because an extension change does not create an OOXML package. A consumer expecting a DOCX ZIP needs the XML parts and relationships, rather than an HTML document bearing the wrong filename.
Which Markdown features survive?
Headings 1–6 as Word styles, bold, italic, strikethrough, inline code, real hyperlinks, bulleted and numbered lists, GFM task lists (as ☑/☐ characters, not Word checkbox controls), GFM tables with per-column alignment and a repeating header row, fenced code blocks, blockquotes and horizontal rules. What is listed in the previous section does not.
Do I need docx specifically?
No, but you need something that writes OOXML. docx is MIT-licensed, has no native dependencies and supports both Node and browser environments, which is why we picked it over a template-filling approach.
Can I trust the output to open everywhere?
It is a valid OOXML package with a standard extension, which is a strong indicator — but we have verified the package structure by unzipping it in tests, not by opening it in every client. Test your own output in the clients your users actually have.
Last updated: 3 December 2026.
The finished version of all of the above is Markdown to Word — paste or drop a .md, pick page size and fonts, download a .docx. For the return trip there is Word to TXT, whose Markdown output feeds straight back into this pipeline.
Top comments (0)