Convert HTML to DOCX with Pandoc and Python
In this article
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
- Install Python from python.org if not already installed. Verify installation by opening a terminal and running
python --versionorpython3 --versiondepending on your system. - 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 --versionin the terminal. You should see version details. - Install the
pandocPython package using pip. Runpip install pypandocin your terminal. This package acts as a bridge between Python and the Pandoc executable, allowing you to call Pandoc directly from scripts. - Create a new Python script file (e.g.,
html_to_docx.py) using any text editor or IDE. - Import
pypandocat the top of your script:import pypandoc. - Define the source HTML content. You can either read it from a file or define it as a string. Example:
html_content = 'orThis is a test.
'with open('input.html', 'r') as f: html_content = f.read(). - 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' ) - Run the script using
python html_to_docx.pyin the terminal. If no errors occur, a file namedoutput.docxwill be created in the same directory. - To convert multiple files, wrap the conversion logic in a loop. For example, iterate over all
.htmlfiles in a directory usingos.listdir()orglob, and process each one with a modified output filename. - Optionally, pass additional Pandoc arguments using the
extra_argsparameter. 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:
pypandocis only a wrapper; the actual Pandoc executable must be installed system-wide. - Not adding Pandoc to the system PATH: if
pandoc --versionfails 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 ofconvert_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-mediaoption 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.