• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

mwilliamson/mammoth.js: Convert Word documents (.docx files) to HTML

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称:

mwilliamson/mammoth.js

开源软件地址:

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

开源编程语言:

JavaScript 99.5%

开源软件介绍:

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.

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, mammoth can be required in the usual way:

var mammoth = require("mammoth");

To generate a standalone JavaScript file for the browser, use mammoth.browser.js (generate using make setup if it is not already present). This uses any loaded module system. If no module system is found, mammoth is set as a window global.

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
    })
    .done();

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;
    })
    .done();

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.

    • 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)

Given an existing docx file, embedStyleMap will generate a new docx file with the passed style map embedded. When the new docx file is read by Mammoth, it will use the embedded style map.

  • 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.
  • styleMap: the style map to embed.

  • Returns a promise. Call toBuffer() on the value inside the promise to get a Buffer representing the new document.

For instance:

mammoth.embedStyleMap({path: sourcePath}, "p[style-name='Section Title'] => h1:fresh")
    .then(function(docx) {
        fs.writeFile(destinationPath, docx.toBuffer(), callback);
    });

Messages

Each message has the following properties:

  • type: a string representing the type of the message, such as "warning" or "error"

  • message: a string containing the actual message

  • error (optional): the thrown exception that caused this message, if any

Image converters

An image converter can be created by calling mammoth.images.imgElement(func). This creates an <img> element for each image in the original docx. func should be a function that has one argument image. This argument is the image element being converted, and has the following properties:

  • read([encoding]): read the image file with the specified encoding. If no encoding is specified, a Buffer is returned.

  • contentType: the content type of the image, such as image/png.

func should return an object (or a promise of an object) of attributes for the <img> element. At a minimum, this should include the src attribute. If any alt text is found for the image, this will be automatically added to the element's attributes.

For instance, the following replicates the default image conversion:

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

mammoth.images.dataUri is the default image converter.

Document transforms

The API for document transforms should be considered unstable, and may change between any versions. If you rely on this behaviour, you should pin to a specific version of mammoth.js, and test carefully before updating.

Mammoth allows a document to be transformed before it is converted. For instance, suppose that document has not been semantically marked up, but you know that any centre-aligned paragraph should be a heading. You can use the transformDocument argument to modify the document appropriately:

function transformElement(element) {
    if (element.children) {
        var children = _.map(element.children, transformElement);
        element = {...element, children: children};
    }

    if (element.type === "paragraph") {
        element = transformParagraph(element);
    }

    return element;
}

function transformParagraph(element) {
    if (element.alignment === "center" && !element.styleId) {
        return {...element, styleId: "Heading2"};
    } else {
        return element;
    }
}

var options = {
    transformDocument: transformElement
};

The return value of transformDocument is used during HTML generation.

The above can be written more succinctly using the helper mammoth.transforms.paragraph:

function transformParagraph(element) {
    if (element.alignment === "center" && !element.styleId) {
        return {...element, styleId: "Heading2"};
    } else {
        return element;
    }
}

var options = {
    transformDocument: mammoth.transforms.paragraph(transformParagraph)
};

Or if you want paragraphs that have been explicitly set to use monospace fonts to represent code:

const monospaceFonts = ["consolas", "courier", "courier new"];

function transformParagraph(paragraph) {
    var runs = mammoth.transforms.getDescendantsOfType(paragraph, "run");
    var isMatch = runs.length > 0 && runs.every(function(run) {
        return run.font && monospaceFonts.indexOf(run.font.toLowerCase()) !== -1;
    });
    if (isMatch) {
        return {
            ...paragraph,
            styleId: "code",
            styleName: "Code"
        };
    } else {
        return paragraph;
    }
}

var options = {
    transformDocument: mammoth.transforms.paragraph( 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
bigskysoftware/htmx: &lt;/&gt; htmx - high power tools for HTML发布时间:2022-06-17
下一篇:
Sponsor @boyvanamstel on GitHub Sponsors · GitHub发布时间:2022-06-17
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap