Nanfeng

Notes on software development, code, and curious ideas

How to Convert Markdown to a Word Document

Markdown is convenient for everyday writing, but sometimes a document needs to be shared, edited, or printed in Microsoft Word format. Here are two simple ways to convert Markdown to a .docx file.

Use a Python script

Install pypandoc, a Python wrapper for the Pandoc document converter, and use the following example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import pypandoc

def markdown_to_word(markdown_text, output_path):
try:
output = pypandoc.convert_text(
markdown_text,
'docx',
format='md',
outputfile=output_path
)
print(f"Conversion successful. Word document saved at: {output_path}")
except Exception as e:
print(f"Error during conversion: {e}")

if __name__ == "__main__":
markdown_text = """
# Markdown to Word

This is a sample Markdown text.

- Item 1
- Item 2
- Item 3
"""

output_path = "output.docx"
markdown_to_word(markdown_text, output_path)

Replace markdown_text with your own content and run the script. The converted Word document will be written to the specified output path. This method depends on Pandoc, so Pandoc must also be installed and available on your system path.

Pandoc is a powerful converter that supports many document formats, including Markdown and Word. Run:

1
pandoc input.md -o output.docx

This is usually the simplest option when you already have the Markdown content in a file.

+