How to Convert Markdown to Word Documents Offline and Securely on Your Local Machine
Convert Markdown to Word (.docx) documents entirely offline using Pandoc with a python-docx fallback. This guide covers environment setup, a complete conversion script, table and style handling, and batch processing—keeping sensitive files on your local machine without uploading them to third-party servers.
Why Convert Offline
Markdown is great for writing and version control, but Word (.docx) remains the standard format for formal submissions at many organizations. Many people rely on online conversion websites, but once contracts, financial reports, or unpublished manuscripts are uploaded to a third-party server, they may be cached or retained. For sensitive content, local processing is the safer choice.
The main advantages of offline conversion are:
- Data never leaves your machine: Files are only read and written locally, and the conversion requires no network requests.
- Controllable output: You can specify reference style files, fonts, and preprocessing rules locally, while online tools typically offer only fixed templates.
- Easy to automate: A script can be combined with scheduled tasks to batch-process an entire directory.
Note that local processing does not automatically mean secure. File permissions, malware on your computer, the source of dependencies, and backup policies all affect the overall security level. An offline solution only reduces the risk of third parties accessing your files—it does not replace these basic protections.
The table below compares the two approaches.
| Dimension | Online Conversion Service | Local Offline Conversion |
|---|---|---|
| File destination | Uploaded to vendor’s servers | Stays on your machine only |
| Network dependency | Requires internet | No internet needed after installation |
| Output control | Limited to vendor templates | Customizable via reference style files |
| Maintenance cost | Nearly zero | Requires maintaining Pandoc and Python environments |
| Use case | Non-sensitive temporary files | Contracts, financial data, internal documents |
Architecture: Primary Engine and Fallback Mode
The approach in this article has two layers.
The primary engine is Pandoc. Pandoc is an open-source universal document converter that supports Markdown-to-docx conversion and can unify styles through a reference document. Its license is GPL-2.0-or-later, so verify compliance requirements in your organization before use.
The fallback mode uses the python-docx library. When Pandoc is not installed or the Pandoc call fails, the script switches to python-docx and parses the Markdown line by line to generate a Word file. python-docx is MIT-licensed. Note that this mode only supports headings, paragraphs, unordered lists, and code blocks—tables and inline formatting (such as bold text and links) will not be preserved. It should be treated as an emergency option, not a high-fidelity solution.
Environment Setup
1. Install Pandoc
Windows users can download the installer from the official Pandoc website (pandoc.org), or install via winget:
winget install --id JohnMacFarlane.Pandoc
macOS users can install with Homebrew:
brew install pandoc
After installation, open a new terminal and run the following command to confirm Pandoc is on your PATH and working:
pandoc --version
If the command is not found, reopen the terminal or manually add Pandoc’s installation directory to your system PATH.
2. Install Python and python-docx
Make sure Python 3.8 or later is installed, then run:
pip install python-docx
3. Notes for Corporate Environments
Installing software on a company computer usually requires IT department approval. When submitting a request, state the names, purposes, license types, and download sources of both components, and keep the checksums of the installation packages for future audits.
The Conversion Script
The script is named md2docx_pro.py and is used as follows:
python md2docx_pro.py input.md output.docx
The complete code:
#!/usr/bin/env python3# -*- coding: utf-8 -*-import reimport shutilimport subprocessimport sysfrom pathlib import Pathtry:from docx import Documentfrom docx.oxml import OxmlElementfrom docx.oxml.ns import qnfrom docx.shared import PtHAS_DOCX_LIB = Trueexcept ImportError:HAS_DOCX_LIB = Falsedef preprocess_markdown(text):"""Normalize line breaks and insert a blank line before tables so they aren't merged into the previous paragraph."""text = text.replace("\r\n", "\n").lstrip("\ufeff")lines = text.split("\n")result = []for line in lines:is_table_line = line.strip().startswith("|")previous_is_table = bool(result) and result[-1].strip().startswith("|")if is_table_line and result and result[-1].strip() and not previous_is_table:result.append("")result.append(line)return "\n".join(result)def convert_with_pandoc(src, dst):"""Call Pandoc. Arguments are passed as a list without a shell, so spaces and special characters in paths are safe."""cmd = ["pandoc",str(src.resolve()),"--resource-path", str(src.resolve().parent),"-o", str(dst.resolve()),]try:subprocess.run(cmd, check=True, timeout=120, capture_output=True, text=True)return Trueexcept (subprocess.CalledProcessError, subprocess.TimeoutExpired) as exc:print(f"Pandoc conversion failed: {exc}")return Falsedef set_run_east_asia_font(run, font_name="SimSun"):"""Set the East Asian font for a run. CJK characters read from the eastAsia font slot; setting font.name alone has no effect."""rpr = run._element.get_or_add_rPr()rfonts = rpr.find(qn("w:rFonts"))if rfonts is None:rfonts = OxmlElement("w:rFonts")rpr.insert(0, rfonts)rfonts.set(qn("w:eastAsia"), font_name)def add_fallback_paragraph(doc, text, font_name="SimSun"):paragraph = doc.add_paragraph()run = paragraph.add_run(text)run.font.name = "Times New Roman"run.font.size = Pt(12)set_run_east_asia_font(run, font_name)return paragraphdef convert_with_python(src, dst):"""Fallback mode: only recognizes headings, unordered lists, code blocks, and plain paragraphs. Tables and inline formatting are not preserved."""if not HAS_DOCX_LIB:print("python-docx is not installed; fallback mode unavailable. Run: pip install python-docx")return Falsetext = preprocess_markdown(src.read_text(encoding="utf-8-sig"))doc = Document()in_code = Falsecode_lines = []for raw in text.split("\n"):line = raw.rstrip()if line.startswith("```"):if in_code:paragraph = doc.add_paragraph()run = paragraph.add_run("\n".join(code_lines))run.font.name = "Consolas"code_lines = []in_code = not in_codecontinueif in_code:code_lines.append(raw)continueif not line.strip():continueheading = re.match(r"^(#{1,6})\s+(.*)$", line)if heading:level = len(heading.group(1))title = doc.add_heading(level=min(level, 9))run = title.add_run(heading.group(2))set_run_east_asia_font(run, "SimHei")continuebullet = re.match(r"^\s*[-*]\s+(.*)$", line)if bullet:paragraph = add_fallback_paragraph(doc, bullet.group(1))paragraph.style = doc.styles["List Bullet"]continueadd_fallback_paragraph(doc, line)doc.save(dst)return Truedef main():if len(sys.argv) != 3:print("Usage: python md2docx_pro.py <input.md> <output.docx>")sys.exit(1)src, dst = Path(sys.argv[1]), Path(sys.argv[2])if not src.is_file():print(f"Input file does not exist: {src}")sys.exit(1)if dst.exists():print(f"Output file already exists; stopping to avoid overwriting: {dst}")sys.exit(1)if shutil.which("pandoc") and convert_with_pandoc(src, dst):print("Pandoc conversion succeeded.")returnprint("Switching to fallback mode; output may be incomplete.")if convert_with_python(src, dst):print("Fallback conversion completed.")else:print("Conversion failed. Check your environment configuration.")sys.exit(1)if __name__ == "__main__":main()
Several design decisions deserve explanation.
First, the script checks whether Pandoc exists before calling it. It uses shutil.which("pandoc") rather than guessing a command name, so the primary engine is only used when Pandoc is genuinely available.
Second, Pandoc is invoked with an argument list instead of a concatenated shell string. This means filenames containing spaces, quotes, or semicolons will not be misinterpreted by the shell.
Third, the script refuses to overwrite an existing output file. During batch conversion, an old Word file may be a manually edited version, and overwriting it would cause data loss. If overwriting is truly necessary, back up the old file first, then delete or rename it manually.
Fourth, the preprocessing function does only two things: normalize line breaks and insert a blank line before tables. An earlier draft used regex to replace pipe characters, which would have rewritten all pipe-containing content in the body text—this should be avoided.
Fifth, East Asian fonts must be set through the w:eastAsia attribute. Setting only run.font.name affects Western characters only; CJK characters will keep the default font.
Advanced Handling for Tables and Styles
1. Table Syntax
Pipe tables recognized by Pandoc require a delimiter row such as |---|---|. Without it, the table will be rendered as plain text. Also, leave a blank line before and after each table.
2. Unifying Styles with a Reference Document
If you want headings, body fonts, and margins to match your organization’s template, prepare a style file ref.docx in Word first, then add the parameter to the Pandoc command:
pandoc input.md --reference-doc=ref.docx -o output.docx
Pandoc will use the style definitions from the reference document. A good practice is to generate output from a simple test Markdown file first, then adjust the reference document based on the results.
3. Image Paths
Images in Markdown usually use relative paths. The --resource-path parameter in the script sets the Markdown file’s directory as the search base, so images embed correctly. If image paths point elsewhere, the converted document may contain missing images.
Batch Conversion and Automation
To convert an entire directory, add a traversal loop around the script. The following example writes results to a separate docx_output directory without modifying the original Markdown files.
from pathlib import Pathimport subprocessimport syssource_dir = Path(sys.argv[1])output_dir = Path(sys.argv[2])output_dir.mkdir(parents=True, exist_ok=True)for md_file in sorted(source_dir.glob("*.md")):target = output_dir / (md_file.stem + ".docx")if target.exists():print(f"Skipping existing file: {target}")continueresult = subprocess.run([sys.executable, "md2docx_pro.py", str(md_file), str(target)],capture_output=True,text=True,)print(f"{md_file.name}: return code {result.returncode}")
A few points to keep in mind when using batch conversion:
- Always keep the
.mdoriginals as source files; Word files are only the deliverable format. - Output to a separate directory to avoid mixing with existing files.
- Redirect output to a log file so failed entries can be traced later.
- Back up the source directory regularly. A conversion script is no substitute for backups.
