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:

    1. Data never leaves your machine: Files are only read and written locally, and the conversion requires no network requests.
    2. Controllable output: You can specify reference style files, fonts, and preprocessing rules locally, while online tools typically offer only fixed templates.
    3. 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:

    1. winget install --id JohnMacFarlane.Pandoc

    macOS users can install with Homebrew:

    1. brew install pandoc

    After installation, open a new terminal and run the following command to confirm Pandoc is on your PATH and working:

    1. 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:

    1. 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:

    1. python md2docx_pro.py input.md output.docx

    The complete code:

    1. #!/usr/bin/env python3
    2. # -*- coding: utf-8 -*-
    3. import re
    4. import shutil
    5. import subprocess
    6. import sys
    7. from pathlib import Path
    8. try:
    9. from docx import Document
    10. from docx.oxml import OxmlElement
    11. from docx.oxml.ns import qn
    12. from docx.shared import Pt
    13. HAS_DOCX_LIB = True
    14. except ImportError:
    15. HAS_DOCX_LIB = False
    16. def preprocess_markdown(text):
    17. """Normalize line breaks and insert a blank line before tables so they aren't merged into the previous paragraph."""
    18. text = text.replace("\r\n", "\n").lstrip("\ufeff")
    19. lines = text.split("\n")
    20. result = []
    21. for line in lines:
    22. is_table_line = line.strip().startswith("|")
    23. previous_is_table = bool(result) and result[-1].strip().startswith("|")
    24. if is_table_line and result and result[-1].strip() and not previous_is_table:
    25. result.append("")
    26. result.append(line)
    27. return "\n".join(result)
    28. def convert_with_pandoc(src, dst):
    29. """Call Pandoc. Arguments are passed as a list without a shell, so spaces and special characters in paths are safe."""
    30. cmd = [
    31. "pandoc",
    32. str(src.resolve()),
    33. "--resource-path", str(src.resolve().parent),
    34. "-o", str(dst.resolve()),
    35. ]
    36. try:
    37. subprocess.run(cmd, check=True, timeout=120, capture_output=True, text=True)
    38. return True
    39. except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as exc:
    40. print(f"Pandoc conversion failed: {exc}")
    41. return False
    42. def set_run_east_asia_font(run, font_name="SimSun"):
    43. """Set the East Asian font for a run. CJK characters read from the eastAsia font slot; setting font.name alone has no effect."""
    44. rpr = run._element.get_or_add_rPr()
    45. rfonts = rpr.find(qn("w:rFonts"))
    46. if rfonts is None:
    47. rfonts = OxmlElement("w:rFonts")
    48. rpr.insert(0, rfonts)
    49. rfonts.set(qn("w:eastAsia"), font_name)
    50. def add_fallback_paragraph(doc, text, font_name="SimSun"):
    51. paragraph = doc.add_paragraph()
    52. run = paragraph.add_run(text)
    53. run.font.name = "Times New Roman"
    54. run.font.size = Pt(12)
    55. set_run_east_asia_font(run, font_name)
    56. return paragraph
    57. def convert_with_python(src, dst):
    58. """Fallback mode: only recognizes headings, unordered lists, code blocks, and plain paragraphs. Tables and inline formatting are not preserved."""
    59. if not HAS_DOCX_LIB:
    60. print("python-docx is not installed; fallback mode unavailable. Run: pip install python-docx")
    61. return False
    62. text = preprocess_markdown(src.read_text(encoding="utf-8-sig"))
    63. doc = Document()
    64. in_code = False
    65. code_lines = []
    66. for raw in text.split("\n"):
    67. line = raw.rstrip()
    68. if line.startswith("```"):
    69. if in_code:
    70. paragraph = doc.add_paragraph()
    71. run = paragraph.add_run("\n".join(code_lines))
    72. run.font.name = "Consolas"
    73. code_lines = []
    74. in_code = not in_code
    75. continue
    76. if in_code:
    77. code_lines.append(raw)
    78. continue
    79. if not line.strip():
    80. continue
    81. heading = re.match(r"^(#{1,6})\s+(.*)$", line)
    82. if heading:
    83. level = len(heading.group(1))
    84. title = doc.add_heading(level=min(level, 9))
    85. run = title.add_run(heading.group(2))
    86. set_run_east_asia_font(run, "SimHei")
    87. continue
    88. bullet = re.match(r"^\s*[-*]\s+(.*)$", line)
    89. if bullet:
    90. paragraph = add_fallback_paragraph(doc, bullet.group(1))
    91. paragraph.style = doc.styles["List Bullet"]
    92. continue
    93. add_fallback_paragraph(doc, line)
    94. doc.save(dst)
    95. return True
    96. def main():
    97. if len(sys.argv) != 3:
    98. print("Usage: python md2docx_pro.py <input.md> <output.docx>")
    99. sys.exit(1)
    100. src, dst = Path(sys.argv[1]), Path(sys.argv[2])
    101. if not src.is_file():
    102. print(f"Input file does not exist: {src}")
    103. sys.exit(1)
    104. if dst.exists():
    105. print(f"Output file already exists; stopping to avoid overwriting: {dst}")
    106. sys.exit(1)
    107. if shutil.which("pandoc") and convert_with_pandoc(src, dst):
    108. print("Pandoc conversion succeeded.")
    109. return
    110. print("Switching to fallback mode; output may be incomplete.")
    111. if convert_with_python(src, dst):
    112. print("Fallback conversion completed.")
    113. else:
    114. print("Conversion failed. Check your environment configuration.")
    115. sys.exit(1)
    116. if __name__ == "__main__":
    117. 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:

    1. 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.

    1. from pathlib import Path
    2. import subprocess
    3. import sys
    4. source_dir = Path(sys.argv[1])
    5. output_dir = Path(sys.argv[2])
    6. output_dir.mkdir(parents=True, exist_ok=True)
    7. for md_file in sorted(source_dir.glob("*.md")):
    8. target = output_dir / (md_file.stem + ".docx")
    9. if target.exists():
    10. print(f"Skipping existing file: {target}")
    11. continue
    12. result = subprocess.run(
    13. [sys.executable, "md2docx_pro.py", str(md_file), str(target)],
    14. capture_output=True,
    15. text=True,
    16. )
    17. print(f"{md_file.name}: return code {result.returncode}")

    A few points to keep in mind when using batch conversion:

    1. Always keep the .md originals as source files; Word files are only the deliverable format.
    2. Output to a separate directory to avoid mixing with existing files.
    3. Redirect output to a log file so failed entries can be traced later.
    4. Back up the source directory regularly. A conversion script is no substitute for backups.