mammoth.js

repository·master·Indexed 27 days ago

https://github.com/mwilliamson/mammoth.js

A .docx to HTML and Markdown converter that prioritizes semantic HTML over exact visual replication. It maps document styles to HTML elements to produce clean web content. Features include support for headings, lists, tables, images, and custom style mapping. Available as a JavaScript library for Node.js and the browser, as well as a CLI tool. Also available for Python, WordPress, Java/JVM, and .NET.

Tokens
3.8K
Snippets
13
Records
30
Agent score
91%

What's inside mammoth.js

  1. Overview of Mammoth .docx to HTML conversion

    master

    Mammoth converts .docx documents (from Microsoft Word, Google Docs, LibreOffice, etc.) into clean, semantic HTML.

    Instead of attempting to replicate exact visual styling (like font size or color), Mammoth focuses on semantic information. For example, a paragraph styled as Heading 1 in Word is converted to an <h1> element in HTML. This approach produces simpler and cleaner HTML code.

    Supported features include:

    • Headings
    • Lists
    • Tables (formatting like borders is ignored, but text formatting is preserved)
    • Footnotes and endnotes
    • Images
    • Text styles: Bold, italics, underlines, strikethrough, superscript, and subscript
    • Links
    • Line breaks
    • Text boxes (contents are treated as a separate paragraph following the text box)
    • Comments
    • Custom style mapping (e.g., mapping a custom Word style WarningHeading to <h1 class="warning">)
  2. Use the :fresh modifier in style maps

    master

    By default, Mammoth reuses HTML elements if consecutive .docx elements match the same style mapping. For example, two consecutive Heading 1 paragraphs might be appended to the same <h1> element.

    To force Mammoth to create a new HTML element for every match, append the :fresh modifier to the HTML path. This is useful for headings or elements that should not be collapsed together.

    p[style-name='Heading 1'] => h1:fresh
  3. Use :separator in HTML paths

    master

    When multiple paragraphs are collapsed into a single HTML element (because they aren't marked :fresh), you can specify a string to be inserted between the contents of those paragraphs using the :separator('STRING') modifier. This is useful for mapping code blocks to <pre> elements where each paragraph represents a new line.

    p[style-name='Code Block'] => pre:separator('\n')
  4. Configure Writing Style Maps

    master

    Style maps allow you to control how .docx elements are converted to HTML. A map consists of mappings separated by new lines. Each mapping follows the format: [document element matcher] => [HTML path].

    Blank lines and lines starting with # are ignored.

    When converting, Mammoth finds the first mapping where the matcher matches the current paragraph and ensures the HTML path is satisfied.

    p[style-name='Heading 1'] => h1
  5. Install and Import Mammoth

    master

    Mammoth can be used in Node.js or the browser.

    Node.js (CommonJS):

    var mammoth = require("mammoth");

    Browser (CommonJS): Use the standalone mammoth.browser.js file which includes dependencies:

    var mammoth = require("mammoth/mammoth.browser");

    If no module system is detected, mammoth is set as a window global.

    var mammoth = require("mammoth");
  6. Migration guide for upgrading Mammoth

    master

    Upgrading to 1.0.0+

    • The convertUnderline option is removed. Use style mappings to control underlines.

    Upgrading to 0.3.0+

    • Custom Style Maps: Prefer matching by name (p[style-name='Name']) over style ID (p.ID).
    • Document Transforms: The styleName property now contains the display name, and styleId contains the internal ID. Update transforms to use styleId instead of styleName if you were previously using styleName to store the ID.
  7. Configure `convertToHtml` options

    master

    The options object for convertToHtml supports the following keys:

    • styleMap: (string or array of strings) Controls mapping of Word styles to HTML. If a string, each line is a mapping.
    • includeEmbeddedStyleMap: (boolean) If false, ignores embedded style maps in the document. Defaults to true.
    • includeDefaultStyleMap: (boolean) If false, stops using default Mammoth style mappings. Defaults to true.
    • externalFileAccess: (boolean) Enables access to external files referenced in the document. Disabled by default for security.
    • convertImage: (function) An image converter to override default inline behavior.
    • ignoreEmptyParagraphs: (boolean) If false, preserves empty paragraphs. Defaults to true.
    • idPrefix: (string) A string to prepend to generated IDs (bookmarks, footnotes, etc.).
    • transformDocument: (function) An unstable API to transform the document before conversion.
  8. Create custom image handlers

    master

    Override the default inline image behavior by providing a convertImage option to convertToHtml. Use mammoth.images.imgElement(func) to create a converter. The function func receives an image object with methods like readAsArrayBuffer(), readAsBuffer(), and readAsBase64String(). It must return an object containing at least a src attribute.

    var options = {
        convertImage: mammoth.images.imgElement(function(image) {
            return image.read("base64").then(function(imageBuffer) {
                return {
                    src: "data:" + image.contentType + ";base64," + imageBuffer
                };
            });
        })
    };
    // Use options in mammoth.convertToHtml({path: ...}, options);
  9. Embed a style map into a .docx file

    master

    Use mammoth.embedStyleMap(input, styleMap) to generate a new .docx file with a specific style map embedded. This ensures Mammoth uses these mappings when the file is later processed.

    • Input: {path: string}, {buffer: Buffer}, or {arrayBuffer: ArrayBuffer}.
    • Returns: A Promise resolving to an object. Use .toBuffer() (Node) or .toArrayBuffer() (Browser) to get the new document data.
    mammoth.embedStyleMap({path: sourcePath}, "p[style-name='Section Title'] => h1:fresh")
        .then(function(docx) {
            fs.writeFile(destinationPath, docx.toBuffer(), callback);
        });
  10. Extract raw text with `mammoth.extractRawText`

    master

    Extracts the raw text from a .docx file, ignoring all formatting. Each paragraph is followed by two newlines. Returns a Promise resolving to an object with value (the text) and messages.

    mammoth.extractRawText({path: "path/to/document.docx"})
        .then(function(result){
            var text = result.value; // The raw text
            var messages = result.messages;
        })
        .catch(function(error) {
            console.error(error);
        });