User Agents

Web browsers and everyday web tech, explained

Convert HTML to DOCX with Pandoc and Python

· 4 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Convert HTML to DOCX using Pandoc and Python to transform web content into professionally formatted Word documents programmatically. This method preserves structure, styling, and layout far better than manual copy-pasting, and supports batch processing, automation, and integration into larger workflows. Pandoc, a universal document converter, handles the transformation, while Python scripts manage input, execution, and output. This guide walks you through setting up the tools, writing the conversion script, and handling common issues.

What You'll Need

  • Python 3.6 or later installed on your system
  • Pandoc (version 2.0 or higher) installed and available in your system PATH
  • Basic familiarity with command-line tools and Python scripting
  • An HTML file you want to convert (local or generated in code)
  • Optional: Internet access if installing packages via pip

Step-by-Step

  1. Install Python from python.org if not already installed. Verify installation by opening a terminal and running python --version or python3 --version depending on your system.
  2. Download and install Pandoc from pandoc.org/installing.html. Follow the instructions for your operating system (Windows, macOS, Linux). After installation, test it by running pandoc --version in the terminal. You should see version details.
  3. Install the pandoc Python package using pip. Run pip install pypandoc in your terminal. This package acts as a bridge between Python and the Pandoc executable, allowing you to call Pandoc directly from scripts.
  4. Create a new Python script file (e.g., html_to_docx.py) using any text editor or IDE.
  5. Import pypandoc at the top of your script: import pypandoc.
  6. Define the source HTML content. You can either read it from a file or define it as a string. Example: html_content = '

    This is a test.

    '
    or with open('input.html', 'r') as f: html_content = f.read().
  7. Use pypandoc.convert_text() to convert the HTML to DOCX. Specify the input format, output format, and output file. Example:
    output = pypandoc.convert_text(
        html_content,
        'docx',
        format='html',
        outputfile='output.docx'
    )
  8. Run the script using python html_to_docx.py in the terminal. If no errors occur, a file named output.docx will be created in the same directory.
  9. To convert multiple files, wrap the conversion logic in a loop. For example, iterate over all .html files in a directory using os.listdir() or glob, and process each one with a modified output filename.
  10. Optionally, pass additional Pandoc arguments using the extra_args parameter. For example, to include a title page: extra_args=['--title-prefix', 'My Document']. Refer to the Pandoc manual for supported options.

Common Mistakes

  • Forgetting to install Pandoc separately: pypandoc is only a wrapper; the actual Pandoc executable must be installed system-wide.
  • Not adding Pandoc to the system PATH: if pandoc --version fails in the terminal, Python won’t find it either.
  • Using invalid HTML: malformed or incomplete HTML (e.g., missing closing tags) may cause conversion failures or unexpected output.
  • Hardcoding file paths without checking if files exist, leading to FileNotFoundError.
  • Ignoring the return value of convert_text(): if it returns a non-empty string, it contains an error message.

Tips

  • Use pypandoc.convert_file() instead of convert_text() when working directly with file paths — it’s cleaner and handles file I/O automatically.
  • Add a check at the start of your script: if not pypandoc.pandoc_installed(): print('Pandoc not installed!') to catch setup issues early.
  • Preserve images by ensuring they are in the same directory or use Pandoc’s --extract-media option to bundle them.
  • Style your DOCX output using a custom reference.docx file: extra_args=['--reference-doc', 'my_template.docx'].
  • Test conversions with small HTML snippets first before processing large or complex documents.

Troubleshooting

If the script fails with OSError: pandoc not found , confirm Pandoc is installed and accessible via the command line. On Windows, reinstall Pandoc and ensure the installer option “Add to PATH” is checked. On macOS or Linux, verify the install location (e.g., /usr/local/bin/pandoc) is in your shell’s PATH. If HTML contains relative image links, ensure the working directory is correct or use absolute paths. If DOCX output looks unstyled, Pandoc may not be applying default templates — try generating a default reference.docx with pandoc --print-default-data-file reference.docx > reference.docx and include it. If pypandoc fails to install, upgrade pip first with pip install --upgrade pip. For encoding errors, ensure your HTML is saved in UTF-8 format.

Frequently Asked Questions

Can I convert HTML with CSS styles to DOCX?

Basic CSS is interpreted by Pandoc, but complex layouts or custom fonts may not transfer perfectly. Inline styles and simple rules (e.g., font-weight, color) are more likely to be preserved.

Does this method support tables and lists?

Yes, Pandoc handles standard HTML tables, ordered, and unordered lists well, converting them into native DOCX equivalents.

Can I run this without installing Pandoc globally?

No, pypandoc requires the standalone Pandoc executable to be installed and accessible in the system environment.

Is it possible to add a cover page or headers?

Yes, use Pandoc’s metadata (YAML block in HTML or via extra_args) or a custom reference.docx to define headers, footers, and title pages.

What if images don’t appear in the DOCX?

Ensure image paths in the HTML are correct relative to the working directory. Use the --extract-media argument to bundle images into the output document.

Can I convert multiple HTML files at once?

Yes, loop through a list of files in Python using os or glob and apply the conversion to each, generating unique output filenames.