html-for-docx is a Python library designed to convert HTML content into Microsoft Word (.docx) documents easily and efficiently. It is an actively maintained fork of the discontinued `pqzx/html2docx` project, providing a more reliable solution for generating Word documents from various HTML inputs. The current version is 1.1.4, with a consistent release cadence focusing on bug fixes and feature enhancements, including improved CSS and HTML tag support.
pip install html-for-docxVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates the core functionalities of html-for-docx: adding HTML strings to a `python-docx` Document object, saving to a file, converting to an in-memory BytesIO object, and converting directly from an HTML file.
Simplify HTML/CSS where possible. Test complex layouts thoroughly. Consider using the `style_map` option for fine-grained control over how CSS classes map to Word styles.
Set the `table_style` attribute on the `HtmlToDocx` parser instance to apply a predefined Word table style, for example: `parser.table_style = 'Table Grid'`.
Always load your template if it contains custom styles: `document = Document('your_template.docx')`. Ensure any referenced custom styles exist in the document at generation time; warnings will be logged for missing styles.Ensure that the directory path for the output `.docx` file already exists, or provide a full absolute path. Python's `os.makedirs()` can be used to create directories if needed.
Set the `table_style` attribute on your `HtmlToDocx` parser instance before processing, e.g., `parser = HtmlToDocx(table_style='Table Grid')` or `parser.table_style = 'Light Shading Accent 1'`. Refer to `python-docx` documentation or Word itself for available table style names.
Consult the `html-for-docx` documentation for the list of supported HTML tags and CSS properties. For custom class-based styling, use the `style_map` option. For highest precedence, apply inline CSS with `!important`.
Upgrade `html-for-docx` to version 1.1.3 or higher, as this specific bug was fixed in that release.