Mammoth is an open-source Python library designed to convert Microsoft Word `.docx` documents into clean and semantic HTML or Markdown. It focuses on preserving the semantic structure of the document (e.g., headings, lists, tables) rather than attempting to replicate exact visual formatting. The current version is 1.12.0. The library has a steady release cadence, with updates addressing features and maintenance.
pip install mammothVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to convert a `.docx` file to HTML using `mammoth.convert_to_html`. It also shows how to access any messages (warnings or errors) generated during the conversion process. The input file must be opened in binary read mode (`'rb'`). For this example, a dummy `.docx` file is created using the `python-docx` library.
Understand Mammoth's design philosophy: it converts semantic meaning. Use custom style mappings to fine-tune HTML output based on your DOCX styles, focusing on structure rather than visual appearance. Review the generated HTML to ensure it meets your structural requirements.
Migrate to converting DOCX to HTML using `mammoth.convert_to_html` and then use a dedicated HTML-to-Markdown conversion library if Markdown is required.
Always sanitize the HTML output generated by Mammoth, especially if the source documents originate from untrusted users. Implement a robust HTML sanitization library (e.g., `Bleach`) after conversion to remove potentially malicious content.
Convert WMF images to a supported format (e.g., PNG) before conversion, or implement a custom image converter using `mammoth.images.img_element` that leverages external tools like LibreOffice as demonstrated in the Mammoth recipes.
Carefully test custom style mappings, especially when using `:fresh`. Understand when you want content appended to an existing HTML element versus when a new element should be created. Refer to the official documentation for advanced style mapping syntax.