MCPcopy Index your code
hub / github.com/mwilliamson/mammoth.js

github.com/mwilliamson/mammoth.js @1.12.0 sqlite

repository ↗ · DeepWiki ↗ · release 1.12.0 ↗
380 symbols 720 edges 82 files 0 documented · 0%
README

Mammoth .docx to HTML converter

Mammoth is designed to convert .docx documents, such as those created by Microsoft Word, Google Docs and LibreOffice, and convert them to HTML. Mammoth aims to produce simple and clean HTML by using semantic information in the document, and ignoring other details. For instance, Mammoth converts any paragraph with the style Heading 1 to h1 elements, rather than attempting to exactly copy the styling (font, text size, colour, etc.) of the heading.

There's a large mismatch between the structure used by .docx and the structure of HTML, meaning that the conversion is unlikely to be perfect for more complicated documents. Mammoth works best if you only use styles to semantically mark up your document.

The following features are currently supported:

  • Headings.

  • Lists.

  • Customisable mapping from your own docx styles to HTML. For instance, you could convert WarningHeading to h1.warning by providing an appropriate style mapping.

  • Tables. The formatting of the table itself, such as borders, is currently ignored, but the formatting of the text is treated the same as in the rest of the document.

  • Footnotes and endnotes.

  • Images.

  • Bold, italics, underlines, strikethrough, superscript and subscript.

  • Links.

  • Line breaks.

  • Text boxes. The contents of the text box are treated as a separate paragraph that appears after the paragraph containing the text box.

  • Comments.

Web demo

The easiest way to try out mammoth is to use the web demo:

  • Clone this repository
  • Run make setup
  • Open browser-demo/index.html in a web browser

Installation

npm install mammoth

Other supported platforms

Usage

CLI

You can convert docx files by passing the path to the docx file and the output file. For instance:

mammoth document.docx output.html

If no output file is specified, output is written to stdout instead.

The output is an HTML fragment, rather than a full HTML document, encoded with UTF-8. Since the encoding is not explicitly set in the fragment, opening the output file in a web browser may cause Unicode characters to be rendered incorrectly if the browser doesn't default to UTF-8.

Mammoth performs no sanitisation of the source document, and should therefore be used extremely carefully with untrusted user input. See the Security section for more information.

Images

By default, images are included inline in the output HTML. If an output directory is specified by --output-dir, the images are written to separate files instead. For instance:

mammoth document.docx --output-dir=output-dir

Existing files will be overwritten if present.

Styles

A custom style map can be read from a file using --style-map. For instance:

mammoth document.docx output.html --style-map=custom-style-map

Where custom-style-map looks something like:

p[style-name='Aside Heading'] => div.aside > h2:fresh
p[style-name='Aside Text'] => div.aside > p:fresh

A description of the syntax for style maps can be found in the section "Writing style maps".

Markdown

Markdown support is deprecated. Generating HTML and using a separate library to convert the HTML to Markdown is recommended, and is likely to produce better results.

Using --output-format=markdown will cause Markdown to be generated. For instance:

mammoth document.docx --output-format=markdown

Library

In node.js and the browser, mammoth can be required in the usual way:

var mammoth = require("mammoth");

Alternatively, you may use the standalone JavaScript file mammoth.browser.js, which includes both mammoth and its dependencies. This uses any loaded module system. For instance, when using CommonJS:

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

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

The file can be generated using make setup during development.

Mammoth performs no sanitisation of the source document, and should therefore be used extremely carefully with untrusted user input. See the Security section for more information.

Basic conversion

To convert an existing .docx file to HTML, use mammoth.convertToHtml:

var mammoth = require("mammoth");

mammoth.convertToHtml({path: "path/to/document.docx"})
    .then(function(result){
        var html = result.value; // The generated HTML
        var messages = result.messages; // Any messages, such as warnings during conversion
    })
    .catch(function(error) {
        console.error(error);
    });

Note that mammoth.convertToHtml returns a promise.

You can also extract the raw text of the document by using mammoth.extractRawText. This will ignore all formatting in the document. Each paragraph is followed by two newlines.

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);
    });

Custom style map

By default, Mammoth maps some common .docx styles to HTML elements. For instance, a paragraph with the style name Heading 1 is converted to a h1 element. You can pass in a custom map for styles by passing an options object with a styleMap property as a second argument to convertToHtml. A description of the syntax for style maps can be found in the section "Writing style maps". For instance, if paragraphs with the style name Section Title should be converted to h1 elements, and paragraphs with the style name Subsection Title should be converted to h2 elements:

var mammoth = require("mammoth");

var options = {
    styleMap: [
        "p[style-name='Section Title'] => h1:fresh",
        "p[style-name='Subsection Title'] => h2:fresh"
    ]
};
mammoth.convertToHtml({path: "path/to/document.docx"}, options);

To more easily support style maps stored in text files, styleMap can also be a string. Each line is treated as a separate style mapping, ignoring blank lines and lines starting with #:

var options = {
    styleMap: "p[style-name='Section Title'] => h1:fresh\n" +
        "p[style-name='Subsection Title'] => h2:fresh"
};

User-defined style mappings are used in preference to the default style mappings. To stop using the default style mappings altogether, set options.includeDefaultStyleMap to false:

var options = {
    styleMap: [
        "p[style-name='Section Title'] => h1:fresh",
        "p[style-name='Subsection Title'] => h2:fresh"
    ],
    includeDefaultStyleMap: false
};

Custom image handlers

By default, images are converted to <img> elements with the source included inline in the src attribute. This behaviour can be changed by setting the convertImage option to an image converter .

For instance, the following would replicate the default behaviour:

var options = {
    convertImage: mammoth.images.imgElement(function(image) {
        return image.read("base64").then(function(imageBuffer) {
            return {
                src: "data:" + image.contentType + ";base64," + imageBuffer
            };
        });
    })
};

Bold

By default, bold text is wrapped in <strong> tags. This behaviour can be changed by adding a style mapping for b. For instance, to wrap bold text in <em> tags:

var mammoth = require("mammoth");

var options = {
    styleMap: [
        "b => em"
    ]
};
mammoth.convertToHtml({path: "path/to/document.docx"}, options);

Italic

By default, italic text is wrapped in <em> tags. This behaviour can be changed by adding a style mapping for i. For instance, to wrap italic text in <strong> tags:

var mammoth = require("mammoth");

var options = {
    styleMap: [
        "i => strong"
    ]
};
mammoth.convertToHtml({path: "path/to/document.docx"}, options);

Underline

By default, the underlining of any text is ignored since underlining can be confused with links in HTML documents. This behaviour can be changed by adding a style mapping for u. For instance, suppose that a source document uses underlining for emphasis. The following will wrap any explicitly underlined source text in <em> tags:

var mammoth = require("mammoth");

var options = {
    styleMap: [
        "u => em"
    ]
};
mammoth.convertToHtml({path: "path/to/document.docx"}, options);

Strikethrough

By default, strikethrough text is wrapped in <s> tags. This behaviour can be changed by adding a style mapping for strike. For instance, to wrap strikethrough text in <del> tags:

var mammoth = require("mammoth");

var options = {
    styleMap: [
        "strike => del"
    ]
};
mammoth.convertToHtml({path: "path/to/document.docx"}, options);

Comments

By default, comments are ignored. To include comments in the generated HTML, add a style mapping for comment-reference. For instance:

var mammoth = require("mammoth");

var options = {
    styleMap: [
        "comment-reference => sup"
    ]
};
mammoth.convertToHtml({path: "path/to/document.docx"}, options);

Comments will be appended to the end of the document, with links to the comments wrapped using the specified style mapping.

API

mammoth.convertToHtml(input, options)

Converts the source document to HTML.

  • input: an object describing the source document. On node.js, the following inputs are supported:

    • {path: path}, where path is the path to the .docx file.
    • {buffer: buffer}, where buffer is a node.js Buffer containing a .docx file.

In the browser, the following inputs are supported:

* `{arrayBuffer: arrayBuffer}`, where `arrayBuffer` is an array buffer containing a .docx file.
  • options (optional): options for the conversion. May have the following properties:

  • styleMap: controls the mapping of Word styles to HTML. If options.styleMap is a string, each line is treated as a separate style mapping, ignoring blank lines and lines starting with #: If options.styleMap is an array, each element is expected to be a string representing a single style mapping. See "Writing style maps" for a reference to the syntax for style maps.

  • includeEmbeddedStyleMap: by default, if the document contains an embedded style map, then it is combined with the default style map. To ignore any embedded style maps, set options.includeEmbeddedStyleMap to false.

  • includeDefaultStyleMap: by default, the style map passed in styleMap is combined with the default style map. To stop using the default style map altogether, set options.includeDefaultStyleMap to false.

  • externalFileAccess: Source documents may reference files outside of the source document. Access to any such external files is disabled by default. To enable access when converting trusted source documents, set options.externalFileAccess to true.

  • convertImage: by default, images are converted to <img> elements with the source included inline in the src attribute. Set this option to an image converter to override the default behaviour.

  • ignoreEmptyParagraphs: by default, empty paragraphs are ignored. Set this option to false to preserve empty paragraphs in the output.

  • idPrefix: a string to prepend to any generated IDs, such as those used by bookmarks, footnotes and endnotes. Defaults to an empty string.

  • transformDocument: if set, this function is applied to the document read from the docx file before the conversion to HTML. The API for document transforms should be considered unstable. See document transforms.

  • Returns a promise containing a result. This result has the following properties:

  • value: the generated HTML

  • messages: any messages, such as errors and warnings, generated during the conversion

mammoth.convertToMarkdown(input, options)

Markdown support is deprecated. Generating HTML and using a separate library to convert the HTML to Markdown is recommended, and is likely to produce better results.

Converts the source document to Markdown. This behaves the same as convertToHtml, except that the value property of the result contains Markdown rather than HTML.

mammoth.extractRawText(input)

Extract the raw text of the document. This will ignore all formatting in the document. Each paragraph is followed by two newlines.

  • input: an object describing the source document. On node.js, the following inputs are supported:

    • {path: path}, where path is the path to the .docx file.
    • {buffer: buffer}, where buffer is a node.js Buffer containing a .docx file.

In the browser, the following inputs are supported:

* `{arrayBuffer: arrayBuffer}`, where `arrayBuffer` is an array buffer containing a .docx file.
  • Returns a promise containing a result. This result has the following properties:

  • value: the raw text

  • messages: any messages, such as errors and warnings

mammoth.embedStyleMap(input, styleMap)

G

Extension points exported contracts — how you extend this code

Mammoth (Interface)
(no doc)
lib/index.d.ts
PathInput (Interface)
(no doc)
lib/index.d.ts
BufferInput (Interface)
(no doc)
lib/index.d.ts
ArrayBufferInput (Interface)
(no doc)
lib/index.d.ts
Options (Interface)
(no doc)
lib/index.d.ts

Core symbols most depended-on inside this repo

readXmlElementValue
called by 80
test/docx/body-reader.tests.js
readXmlElement
called by 40
test/docx/body-reader.tests.js
runOfText
called by 34
test/document-to-html.tests.js
isToken
called by 33
test/styles/parser/tokeniser.tests.js
runWithProperties
called by 32
test/docx/body-reader.tests.js
text
called by 30
lib/html/ast.js
paragraphOfText
called by 23
test/document-to-html.tests.js
assertDocumentMatcher
called by 22
test/style-reader.tests.js

Shape

Function 367
Interface 13

Languages

TypeScript100%

Modules by API surface

lib/docx/body-reader.js49 symbols
lib/document-to-html.js31 symbols
test/docx/body-reader.tests.js28 symbols
lib/documents.js19 symbols
lib/writers/html-writer.js16 symbols
lib/writers/markdown-writer.js15 symbols
lib/index.d.ts13 symbols
lib/styles/document-matchers.js12 symbols
lib/style-reader.js12 symbols
lib/html/simplify.js11 symbols
lib/docx/docx-reader.js10 symbols
lib/index.js8 symbols

Dependencies from manifests, versioned

@types/node20.2.5 · 1×
@xmldom/xmldom0.8.6 · 1×
argparse1.0.3 · 1×
base64-js1.5.1 · 1×
bluebird3.4.0 · 1×
browserify13.0.1 · 1×
browserify-prepend-licenses1.0.0 · 1×
dingbat-to-unicode1.0.1 · 1×
duck0.1.12 · 1×
eslint2.13.1 · 1×
hamjest4.0.1 · 1×
jszip3.7.1 · 1×

For agents

$ claude mcp add mammoth.js \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact