### Install Mammoth.js
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/00-index.md
Install the Mammoth.js library using npm. This is the first step for using Mammoth.js in a Node.js environment.
```bash
npm install mammoth
```
--------------------------------
### Complete Document Transformation Example
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/03-document-transforms.md
A comprehensive example demonstrating a custom document transformation function. It identifies paragraphs with monospace fonts and center-aligned paragraphs, applying specific styles and then converting the document to HTML.
```javascript
function transformDocument(document) {
// Use helper to transform all paragraphs
return mammoth.transforms.paragraph(function(paragraph) {
// Check if all runs use monospace font
var runs = mammoth.transforms.getDescendantsOfType(paragraph, "run");
var monospaceFonts = ["consolas", "courier", "courier new"];
var isMonospace = runs.length > 0 && runs.every(function(run) {
return run.font && monospaceFonts.indexOf(run.font.toLowerCase()) !== -1;
});
if (isMonospace) {
return Object.assign({}, paragraph, {
styleId: "code",
styleName: "Code"
});
}
// Mark center-aligned paragraphs as emphasis
if (paragraph.alignment === "center" && !paragraph.styleName) {
return Object.assign({}, paragraph, {
styleId: "emphasis"
});
}
return paragraph;
})(document);
}
var options = {
transformDocument: transformDocument,
styleMap: [
"p[style-name='Code'] => pre:separator('\n')",
"p[style-name='Emphasis'] => p.centered"
]
};
mammoth.convertToHtml({path: "document.docx"}, options)
.then(function(result) {
console.log(result.value);
});
```
--------------------------------
### Style Map File Format Example
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/07-cli-reference.md
An example of a style map file used to customize document conversion. It defines mappings from document styles to HTML elements.
```plaintext
# Main headings
p[style-name='Title'] => h1:fresh
p[style-name='Section'] => h2:fresh
# Body text
p[style-name='Normal'] => p:fresh
p[style-name='Body Text'] => p:fresh
# Lists
p:unordered-list(1) => ul > li:fresh
p:ordered-list(1) => ol > li:fresh
# Special formatting
p[style-name='Code Block'] => pre:separator('\n')
p[style-name='Warning'] => div.warning
p[style-name='Tip'] => div.tip
# Ignore these styles
p[style-name='Header'] => !
p[style-name='Footer'] => !
```
--------------------------------
### Simple DOCX to HTML Conversion
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/00-index.md
A straightforward example of converting a DOCX file to HTML. This is the most basic usage of the library.
```javascript
mammoth.convertToHtml({path: "document.docx"})
.then(r => console.log(r.value));
```
--------------------------------
### Convert DOCX from Buffer (Node.js)
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/09-usage-patterns.md
Use this pattern when you have the DOCX file content as a Buffer in Node.js, for example, after reading it from a file using the 'fs' module. Ensure mammoth is installed and required.
```javascript
var fs = require("fs");
var mammoth = require("mammoth");
var buffer = fs.readFileSync("document.docx");
mammoth.convertToHtml({buffer: buffer})
.then(function(result) {
console.log(result.value);
});
```
--------------------------------
### Use Custom Image URLs
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/02-image-converters.md
Set a static or dynamically generated URL for the `src` attribute of the `` tag. This example uses a placeholder URL.
```javascript
var options = {
convertImage: mammoth.images.imgElement(function(image) {
return Promise.resolve({
src: "/api/images/placeholder.png"
});
})
};
mammoth.convertToHtml({path: "document.docx"}, options);
```
--------------------------------
### Complete Browser Application Example
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/10-browser-usage.md
This snippet shows a full HTML page with JavaScript to handle file uploads via drag-and-drop or file input, and then converts the DOCX to HTML using Mammoth.js in the browser. It includes basic styling for the drop zone and message display.
```html
Mammoth DOCX Converter
DOCX to HTML Converter
Drop a .docx file here or click to select
```
--------------------------------
### Convert DOCX from File Path (Node.js)
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/09-usage-patterns.md
Use this pattern when you have a DOCX file accessible via a file path in a Node.js environment. Ensure mammoth is installed and required.
```javascript
var mammoth = require("mammoth");
mammoth.convertToHtml({path: "document.docx"})
.then(function(result) {
console.log(result.value);
});
```
--------------------------------
### Arbitrary Nesting Depth Path
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/04-style-maps.md
Demonstrates selecting elements at arbitrary nesting depths using the `>` operator. This example targets an h1 element nested within a section and an article.
```mammoth
section > article > h1
```
--------------------------------
### Example: Heading 1 to H1
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/04-style-maps.md
Illustrates a specific style map rule to convert paragraphs with 'Heading 1' style to an H1 HTML element. The ':fresh' suffix ensures a new element is created.
```text
p[style-name='Heading 1'] => h1:fresh
```
--------------------------------
### Convert DOCX with Custom Document Transform
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/00-index.md
Illustrates how to use a custom transform function to modify the document structure during conversion. This example modifies paragraph styles based on alignment.
```javascript
mammoth.convertToHtml({path: "document.docx"}, {
transformDocument: mammoth.transforms.paragraph(para => {
if (para.alignment === "center") {
return {...para, styleId: "centered"};
}
return para;
})
});
```
--------------------------------
### Custom Logger Implementation
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/06-error-handling.md
Provides a flexible way to handle warning and error messages from Mammoth.js. This example defines a `createLogger` function that can be configured with custom callbacks for warnings and errors.
```javascript
function createLogger(options) {
return {
warning: function(message) {
options.onWarning({type: "warning", message: message});
},
error: function(exception) {
options.onError({type: "error", message: exception.message, error: exception});
}
};
}
var logger = createLogger({
onWarning: function(msg) {
console.log("⚠️ " + msg.message);
},
onError: function(msg) {
console.error("❌ " + msg.message);
if (msg.error) {
console.error(" ", msg.error.stack);
}
}
});
// Messages are returned in result.messages, not logged directly
// So create a wrapper:
mammoth.convertToHtml({path: "document.docx"})
.then(function(result) {
result.messages.forEach(function(msg) {
if (msg.type === "warning") {
logger.warning(msg.message);
} else {
logger.error(msg.error || new Error(msg.message));
}
});
});
```
--------------------------------
### Custom Image Conversion (Data URI)
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/08-configuration.md
Provide a custom image converter function. This example uses mammoth.images.imgElement to create an image element with a data URI source.
```javascript
{
convertImage: mammoth.images.imgElement(function(image) {
return image.readAsBase64String().then(function(base64) {
return {
src: "data:" + image.contentType + ";base64," + base64
};
});
})
}
```
--------------------------------
### Paragraph Transformation using Helper
Source: https://github.com/mwilliamson/mammoth.js/blob/master/README.md
Applies a transformation to paragraphs using the `mammoth.transforms.paragraph` helper. This example transforms center-aligned paragraphs without a style ID into Heading2.
```javascript
function transformParagraph(element) {
if (element.alignment === "center" && !element.styleId) {
return {...element, styleId: "Heading2"};
} else {
return element;
}
}
var options = {
transformDocument: mammoth.transforms.paragraph(transformParagraph)
};
```
--------------------------------
### Extracting Images Separately with Mammoth.js
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/08-configuration.md
Customize image conversion to extract images separately and reference them via a URL. This example increments an image index, determines the file extension, and saves the image buffer to a file, returning a relative path for the `src` attribute.
```javascript
var imageIndex = 0;
mammoth.convertToHtml({path: "document.docx"}, {
convertImage: mammoth.images.imgElement(function(image) {
imageIndex++;
var ext = image.contentType.split("/")[1];
var filename = imageIndex + "." + ext;
return image.readAsBuffer().then(function(buffer) {
saveImageToFile(filename, buffer);
return {src: "/images/" + filename};
});
})
})
```
--------------------------------
### Convert DOCX on File Upload with Node.js and Express
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/07-cli-reference.md
This Node.js example uses Express and Multer to handle file uploads and convert them to HTML using Mammoth. It includes basic error handling and cleans up uploaded files after conversion.
```javascript
var express = require("express");
var mammoth = require("mammoth");
var multer = require("multer");
var fs = require("fs");
var path = require("path");
var app = express();
var upload = multer({dest: "uploads/"});
app.post("/convert", upload.single("file"), function(req, res) {
if (!req.file) {
return res.status(400).send("No file uploaded");
}
var styleMap = fs.readFileSync("styles.txt", "utf8");
mammoth.convertToHtml(
{buffer: fs.readFileSync(req.file.path)},
{styleMap: styleMap}
)
.then(function(result) {
res.send(result.value);
fs.unlinkSync(req.file.path);
})
.catch(function(error) {
res.status(500).send("Conversion error: " + error.message);
fs.unlinkSync(req.file.path);
});
});
app.listen(3000);
```
--------------------------------
### Message Deduplication Example
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/06-error-handling.md
Demonstrates how Mammoth.js deduplicates warnings for unrecognized styles. Only one warning is generated even if multiple paragraphs share the same unrecognized style.
```javascript
// If document has two "CustomStyle" paragraphs:
// Only one warning appears in messages array:
// {
// type: "warning",
// message: "Unrecognised paragraph style: 'CustomStyle' (Style ID: CustomStyle)"
// }
```
--------------------------------
### Custom Image Handler
Source: https://github.com/mwilliamson/mammoth.js/blob/master/README.md
Replace the default image conversion behavior by providing a 'convertImage' function in the options. This example replicates the default behavior of creating an element with a base64 encoded source.
```javascript
var options = {
convertImage: mammoth.images.imgElement(function(image) {
return image.read("base64").then(function(imageBuffer) {
return {
src: "data:" + image.contentType + ";base64," + imageBuffer
};
});
})
};
```
--------------------------------
### Custom Style Map (String Format)
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/08-configuration.md
Define custom style mappings using a single string with newline-separated rules. This example maps 'Heading 1' to h1 and 'Code Block' to pre.
```javascript
{
styleMap: "p[style-name='Heading 1'] => h1:fresh\n" +
"p[style-name='Code Block'] => pre:separator('\n')"
}
```
--------------------------------
### Handle File Not Found Error (Node.js)
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/06-error-handling.md
Check if a file exists before attempting conversion to prevent 'File Not Found' errors. This example uses Node.js's `fs.existsSync` for pre-checking.
```javascript
var fs = require("fs");
if (!fs.existsSync("document.docx")) {
console.error("File not found");
} else {
mammoth.convertToHtml({path: "document.docx"})
.catch(function(error) {
console.error(error);
});
}
```
--------------------------------
### Count All Elements in a Document Structure
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/03-document-transforms.md
Example showing how to use getDescendants to count all elements within a given element. This can be helpful for understanding the complexity or size of a document structure.
```javascript
var element = {/* ... */};
var descendants = mammoth.transforms.getDescendants(element);
console.log("Total descendants: " + descendants.length);
```
--------------------------------
### Mammoth.js Style Map Option
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/00-index.md
Customize the conversion of document styles to HTML by providing a style map in the options. This example shows how to map a specific paragraph style to an h1 tag.
```javascript
var options = {
styleMap: "p[style-name='Heading 1'] => h1:fresh"
};
```
--------------------------------
### Load Mammoth using CommonJS/Browserify
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/10-browser-usage.md
Use this method to include Mammoth.js in projects that utilize CommonJS module systems, often found in older build setups or specific Node.js environments.
```javascript
var mammoth = require("mammoth");
// Use as normal
```
--------------------------------
### Handle Image Conversion Errors
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/02-image-converters.md
Implement error handling within the `convertImage` function to gracefully manage issues during image reading. This example provides a fallback image and alt text.
```javascript
var options = {
convertImage: mammoth.images.imgElement(function(image) {
return image.readAsBase64String()
.then(function(base64) {
return {
src: "data:" + image.contentType + ";base64," + base64,
alt: "embedded image"
};
})
.catch(function(error) {
console.error("Failed to read image:", error);
return {
src: "/images/error.png",
alt: "image could not be loaded"
};
});
})
};
mammoth.convertToHtml({path: "document.docx"}, options);
```
--------------------------------
### Custom Style Map for Underlined Text
Source: https://github.com/mwilliamson/mammoth.js/blob/master/README.md
Control the conversion of underlined text by mapping the 'u' style. This example wraps underlined text in tags, useful for emphasis where links are not a concern.
```javascript
var mammoth = require("mammoth");
var options = {
styleMap: [
"u => em"
]
};
mammoth.convertToHtml({path: "path/to/document.docx"}, options);
```
--------------------------------
### Custom Style Map as String
Source: https://github.com/mwilliamson/mammoth.js/blob/master/README.md
Style maps can be provided as a single string, where each line represents a separate mapping. Blank lines and lines starting with '#' are ignored. This is useful for style maps stored in text files.
```javascript
var options = {
styleMap: "p[style-name='Section Title'] => h1:fresh\n" +
"p[style-name='Subsection Title'] => h2:fresh"
};
```
--------------------------------
### Get Descendants of Type
Source: https://github.com/mwilliamson/mammoth.js/blob/master/README.md
Retrieves all descendants of a specific type within an element. This example shows how to get all 'run' elements from a paragraph.
```javascript
var runs = mammoth.transforms.getDescendantsOfType(paragraph, "run");
```
--------------------------------
### Document Custom Configuration with Helper Function
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/08-configuration.md
Create a helper function to encapsulate custom conversion logic, including specific style maps, ID prefixes, and image handling, making it reusable and documented.
```javascript
// Create a helper for your use case
function convertCompanyDocument(input) {
return mammoth.convertToHtml(input, {
styleMap: fs.readFileSync("company-styles.txt", "utf8"),
ignoreEmptyParagraphs: false,
idPrefix: "company-doc-",
convertImage: mammoth.images.imgElement(function(image) {
// Custom company image handling
return companyImageConverter(image);
})
});
}
// Usage
convertCompanyDocument({path: "proposal.docx"})
.then(function(result) {
return fs.writeFile("output.html", result.value);
});
```
--------------------------------
### Build Mammoth Browser Bundle
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/10-browser-usage.md
Instructions for building the standalone browser bundle of Mammoth.js from its source code. This is typically done before serving the bundle from a static host.
```bash
cd mammoth.js
make setup
make mammoth.browser.min.js
# Serve from your web server
```
--------------------------------
### Console Logging of Messages
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/06-error-handling.md
Logs messages generated during document conversion to the console. This is a basic example for Node.js environments.
```javascript
mammoth.convertToHtml({path: "document.docx"})
.then(function(result) {
result.messages.forEach(function(msg) {
console.log("[" + msg.type.toUpperCase() + "] " + msg.message);
});
});
```
--------------------------------
### Convert All .docx Files in a Directory to HTML
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/09-usage-patterns.md
This snippet shows how to recursively create an output directory and convert all .docx files from an input directory to HTML. It handles file system operations and asynchronous conversion promises, logging progress and errors.
```javascript
var fs = require("fs");
var path = require("path");
var mammoth = require("mammoth");
function convertDirectory(inputDir, outputDir) {
fs.mkdirSync(outputDir, {recursive: true});
var files = fs.readdirSync(inputDir).filter(f => f.endsWith(".docx"));
var promises = files.map(function(file) {
var inputPath = path.join(inputDir, file);
var outputPath = path.join(outputDir, file.replace(".docx", ".html"));
console.log("Converting:", file);
return mammoth.convertToHtml({path: inputPath})
.then(function(result) {
fs.writeFileSync(outputPath, result.value);
console.log(" ✔ " + outputPath);
return {file: file, success: true, messages: result.messages};
})
.catch(function(error) {
console.error(" ✗ Failed:", error.message);
return {file: file, success: false, error: error.message};
});
});
return Promise.all(promises).then(function(results) {
var summary = {
total: results.length,
successful: results.filter(r => r.success).length,
failed: results.filter(r => !r.success).length,
details: results
};
console.log("\nSummary:", summary.successful + "/" + summary.total + " successful");
return summary;
});
}
// Usage
convertDirectory("./documents", "./html")
.then(function(summary) {
if (summary.failed > 0) process.exit(1);
});
```
--------------------------------
### Sanitize HTML Output with DOMPurify
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/10-browser-usage.md
Sanitize the HTML generated by Mammoth.js to prevent cross-site scripting (XSS) attacks. Ensure you have installed the 'dompurify' library.
```javascript
// Install a sanitization library
// npm install dompurify
var DOMPurify = require("dompurify");
mammoth.convertToHtml({arrayBuffer: docxData})
.then(function(result) {
var clean = DOMPurify.sanitize(result.value);
document.getElementById("output").innerHTML = clean;
});
```
--------------------------------
### Get All Descendants of an Element
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/03-document-transforms.md
Retrieves all descendant elements of a root element, irrespective of their type. This function is useful for a comprehensive count or traversal of all nested elements.
```javascript
getDescendants(element)
```
--------------------------------
### Batch Convert with Custom Styles
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/07-cli-reference.md
Converts multiple DOCX files to HTML, applying the same set of custom company styles to each.
```bash
mammoth doc1.docx doc1.html --style-map=company-styles.txt
mammoth doc2.docx doc2.html --style-map=company-styles.txt
```
--------------------------------
### Browser Conversion of DOCX to HTML
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/00-index.md
Example of converting a DOCX file to HTML directly in the browser using a FileReader. This requires a File object to be available.
```javascript
var reader = new FileReader();
reader.onload = e => mammoth.convertToHtml({arrayBuffer: e.target.result})
.then(r => document.body.innerHTML = r.value);
reader.readAsArrayBuffer(file);
```
--------------------------------
### Custom Document Transformation
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/08-configuration.md
Provide a transformDocument function to modify the document structure before conversion. This example applies a 'centered' style to paragraphs with center alignment.
```javascript
{
transformDocument: function(document) {
return mammoth.transforms.paragraph(function(para) {
if (para.alignment === "center") {
return Object.assign({}, para, {styleId: "centered"});
}
return para;
})(document);
}
}
```
--------------------------------
### Load Styles from File
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/09-usage-patterns.md
Load custom styles from a text file to influence the HTML conversion. Ensure the style map file exists at the specified path.
```javascript
var fs = require("fs");
var mammoth = require("mammoth");
var styleMap = fs.readFileSync("company-styles.txt", "utf8");
mammoth.convertToHtml({path: "document.docx"}, {styleMap: styleMap})
.then(function(result) {
console.log(result.value);
});
```
--------------------------------
### Convert DOCX to HTML
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/07-cli-reference.md
Reads a DOCX file and writes the converted HTML to a specified output file. This is the most basic usage of the CLI.
```bash
mammoth input.docx output.html
```
--------------------------------
### Basic HTML Conversion
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/07-cli-reference.md
Converts a DOCX file to an HTML file using default settings.
```bash
mammoth document.docx document.html
```
--------------------------------
### Match Unordered List at Depth
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/04-style-maps.md
Targets paragraphs that are part of an unordered list at a specific nesting depth. Depth starts at 1 for the outermost list.
```text
p:unordered-list(1)
```
--------------------------------
### Match Ordered List at Depth
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/04-style-maps.md
Targets paragraphs that are part of an ordered list at a specific nesting depth. Depth starts at 1 for the outermost list.
```text
p:ordered-list(1)
```
--------------------------------
### Specify Output Format with --output-format
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/07-cli-reference.md
Allows specifying the desired output format, such as HTML or Markdown. Note that Markdown support is currently deprecated.
```bash
mammoth input.docx output.md --output-format=markdown
```
--------------------------------
### Basic Conversion with Options
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/08-configuration.md
The options object is passed as the second parameter to conversion functions like convertToHtml.
```javascript
mammoth.convertToHtml(input, options)
```
--------------------------------
### HTML Conversion with Custom Styles
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/07-cli-reference.md
Converts a DOCX file to HTML, applying custom styles defined in a separate file.
```bash
mammoth document.docx document.html --style-map=custom-styles.txt
```
--------------------------------
### Custom Element Transformation
Source: https://github.com/mwilliamson/mammoth.js/blob/master/README.md
Transforms elements within a document. This example recursively transforms children and then applies a specific transformation to paragraphs based on alignment and style.
```javascript
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
};
```
--------------------------------
### Nested Elements Path
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/04-style-maps.md
Specifies nested HTML elements using the `>` operator. This example selects an h2 element that is a direct child of a div with the class 'aside'.
```mammoth
div.aside > h2
```
--------------------------------
### Handle Large Documents with Streaming and Options
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/08-configuration.md
For large documents, especially those with many images, consider using streaming and optimizing options like `ignoreEmptyParagraphs` to reduce output size and improve performance.
```javascript
// For documents with many images, consider streaming
mammoth.convertToHtml({path: "large-document.docx"}, {
ignoreEmptyParagraphs: true, // Reduce output size
convertImage: mammoth.images.imgElement(function(image) {
// Could implement image caching/deduplication here
return streamingImageHandler(image);
})
})
```
--------------------------------
### Merging Consecutive Elements Path
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/04-style-maps.md
Consecutive elements of the same type are merged by default. This example shows how a paragraph with a specific style name is converted to an h1 element.
```mammoth
p[style-name='Heading 1'] => h1
```
--------------------------------
### Load Mammoth using Standalone Bundle
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/10-browser-usage.md
This method utilizes a pre-built standalone bundle of Mammoth.js, which is compatible with any module system and makes the mammoth object globally available.
```html
```
--------------------------------
### Find All Runs in a Paragraph
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/03-document-transforms.md
Example demonstrating how to use getDescendantsOfType to find all 'run' elements within a paragraph. This is useful for inspecting text formatting within a paragraph.
```javascript
var paragraph = {/* ... */};
var runs = mammoth.transforms.getDescendantsOfType(paragraph, "run");
console.log("Found " + runs.length + " runs");
```
--------------------------------
### Mammoth.js Document Transform Option
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/00-index.md
Modify the document's structure before conversion using document transformations. This example uses a paragraph transform to return the paragraph unchanged.
```javascript
var options = {
transformDocument: mammoth.transforms.paragraph(function(para) {
return para;
})
};
```
--------------------------------
### HTML Meta Tag for UTF-8 Encoding
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/07-cli-reference.md
Example of an HTML document structure including the meta tag for UTF-8 encoding to ensure correct rendering of output from Mammoth.js.
```html
Document
```
--------------------------------
### Convert DOCX with Custom Style Map
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/01-core-api.md
Demonstrates how to convert a .docx document to HTML while applying custom style mappings to override default conversions for specific paragraph styles.
```javascript
var options = {
styleMap: [
"p[style-name='Section Title'] => h1:fresh",
"p[style-name='Subsection Title'] => h2:fresh",
"p[style-name='Code Block'] => pre:separator('\n')"
]
};
mammoth.convertToHtml({path: "document.docx"}, options)
.then(function(result) {
console.log(result.value);
});
```
--------------------------------
### Custom Style Map with --style-map
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/07-cli-reference.md
Applies custom style mappings defined in a separate file to control the conversion process. Each line in the style map file represents a single mapping.
```bash
mammoth input.docx output.html --style-map=styles.txt
```
```plaintext
p[style-name='Section Title'] => h1:fresh
p[style-name='Subsection Title'] => h2:fresh
p[style-name='Code Block'] => pre:separator('\n')
```
--------------------------------
### Convert DOCX with Image Output Directory via CLI
Source: https://github.com/mwilliamson/mammoth.js/blob/master/README.md
Convert a .docx file to HTML and save images to a specified directory using the Mammoth.js CLI. Existing files will be overwritten.
```bash
mammoth document.docx --output-dir=output-dir
```
--------------------------------
### Get Descendants of a Specific Type
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/03-document-transforms.md
Retrieves all descendant elements of a given type within a specified root element. Useful for targeting specific element types for analysis or modification.
```javascript
getDescendantsOfType(element, type)
```
--------------------------------
### Convert DOCX with Custom Style Map via CLI
Source: https://github.com/mwilliamson/mammoth.js/blob/master/README.md
Convert a .docx file to HTML using a custom style map file with the Mammoth.js CLI.
```bash
mammoth document.docx output.html --style-map=custom-style-map
```
--------------------------------
### Convert DOCX from URL (Browser with CORS)
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/09-usage-patterns.md
Use this pattern in a browser to fetch a DOCX file from a URL and convert it to HTML. This requires the server hosting the DOCX file to have CORS enabled. The output is written to an HTML element with the ID 'output'.
```javascript
// Fetch DOCX from URL and convert
fetch("https://example.com/document.docx")
.then(function(response) {
return response.arrayBuffer();
})
.then(function(arrayBuffer) {
return mammoth.convertToHtml({arrayBuffer: arrayBuffer});
})
.then(function(result) {
document.getElementById("output").innerHTML = result.value;
})
.catch(function(error) {
console.error("Conversion failed:", error);
});
```
--------------------------------
### BookmarkStart Type Definition
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/05-internal-types.md
Defines the structure for an anchor point used for internal links. It requires a unique name to identify the bookmark.
```javascript
{
type: "bookmarkStart",
name: string
}
```
--------------------------------
### Extract Images and Use Custom Styles
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/07-cli-reference.md
Converts a DOCX file to HTML, extracting images to a specified directory and applying custom styles.
```bash
mammoth document.docx output.html \
--output-dir=images \
--style-map=styles.txt
```
--------------------------------
### Custom Style Map for Italic Text
Source: https://github.com/mwilliamson/mammoth.js/blob/master/README.md
Change how italic text is converted by mapping the 'i' style. This example wraps italic text in tags instead of the default tags.
```javascript
var mammoth = require("mammoth");
var options = {
styleMap: [
"i => strong"
]
};
mammoth.convertToHtml({path: "path/to/document.docx"}, options);
```
--------------------------------
### mammoth.images.imgElement()
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/02-image-converters.md
Creates a custom image converter that generates `` elements. The provided function controls how image attributes (especially `src`) are generated.
```APIDOC
## mammoth.images.imgElement()
### Description
Creates a custom image converter that generates `` elements. The provided function controls how image attributes (especially `src`) are generated.
### Parameters
#### Path Parameters
- **func** (function) - Required - Function to convert an image element to attributes
### Function Signature
```javascript
function(image: Image): Promise
```
The function receives an `Image` object and must return a Promise resolving to an object of HTML attributes.
### Image Object Properties
- **contentType** (string) - MIME type of the image (e.g., "image/png")
- **readAsArrayBuffer()** (function) - Returns `Promise`
- **readAsBase64String()** (function) - Returns `Promise` with base64-encoded data
- **readAsBuffer()** (function) - Returns `Promise` (Node.js only)
- **read(encoding?)** (function) - Deprecated. Returns `Promise` or `Promise`
- **altText** (string) - Alt text if present in the document
### ImageAttributes
Must return an object with at least a `src` property. The `alt` property is automatically added if the image has alt text.
```javascript
{
src: string, // Required: URL or data URI
alt: string, // Optional: automatically added from image.altText
width: string, // Optional: any valid HTML attribute
height: string // Optional: any valid HTML attribute
}
```
### Return Value
Returns an `ImageConverter` function.
### Examples
**Base64 Data URI (Default Behavior)**
```javascript
var mammoth = require("mammoth");
var options = {
convertImage: mammoth.images.imgElement(function(image) {
return image.readAsBase64String().then(function(base64) {
return {
src: "data:" + image.contentType + ";base64," + base64
};
});
})
};
mammoth.convertToHtml({path: "document.docx"}, options);
```
**Save Images to Disk**
```javascript
var fs = require("fs");
var path = require("path");
var imageIndex = 0;
var options = {
convertImage: mammoth.images.imgElement(function(image) {
imageIndex++;
var extension = image.contentType.split("/")[1];
var filename = imageIndex + "." + extension;
var imagePath = path.join("output-images", filename);
return image.readAsBuffer().then(function(buffer) {
fs.writeFileSync(imagePath, buffer);
return {src: filename};
});
})
};
mammoth.convertToHtml({path: "document.docx"}, options);
```
**Custom Image URL**
```javascript
var options = {
convertImage: mammoth.images.imgElement(function(image) {
return Promise.resolve({
src: "/api/images/placeholder.png"
});
})
};
mammoth.convertToHtml({path: "document.docx"}, options);
```
**With Error Handling**
```javascript
var options = {
convertImage: mammoth.images.imgElement(function(image) {
return image.readAsBase64String()
.then(function(base64) {
return {
src: "data:" + image.contentType + ";base64," + base64,
alt: "embedded image"
};
})
.catch(function(error) {
console.error("Failed to read image:", error);
return {
src: "/images/error.png",
alt: "image could not be loaded"
};
});
})
};
mammoth.convertToHtml({path: "document.docx"}, options);
```
**Resize Images in Conversion**
```javascript
var options = {
convertImage: mammoth.images.imgElement(function(image) {
return image.readAsBase64String().then(function(base64) {
return {
src: "data:" + image.contentType + ";base64," + base64,
width: "400",
height: "300",
style: "max-width: 100%;"
};
});
})
};
mammoth.convertToHtml({path: "document.docx"}, options);
```
```
--------------------------------
### Convert DOCX to HTML with TypeScript
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/00-index.md
Demonstrates basic conversion of a DOCX file to HTML using Mammoth.js with TypeScript. Ensure you have imported the mammoth library.
```typescript
import * as mammoth from "mammoth";
mammoth.convertToHtml({path: "document.docx"})
.then((result: mammoth.Result) => {
console.log(result.value);
});
```
--------------------------------
### Match Paragraph by Style Name Prefix
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/04-style-maps.md
Targets paragraphs whose style names start with a given prefix. This is useful for applying styles to a range of related headings or text types.
```text
p[style-name^='Heading']
```
--------------------------------
### Batch Convert DOCX Files to HTML
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/07-cli-reference.md
Iterates through all DOCX files in the current directory and converts each to its corresponding HTML file.
```bash
for file in *.docx; do
mammoth "$file" "${file%.docx}.html"
done
```
--------------------------------
### Custom Style Map for Comments
Source: https://github.com/mwilliamson/mammoth.js/blob/master/README.md
Include document comments in the generated HTML by adding a style mapping for 'comment-reference'. This example maps comments to tags. Comments are appended to the document with links.
```javascript
var mammoth = require("mammoth");
var options = {
styleMap: [
"comment-reference => sup"
]
};
mammoth.convertToHtml({path: "path/to/document.docx"}, options);
```
--------------------------------
### mammoth.images.imgElement
Source: https://github.com/mwilliamson/mammoth.js/blob/master/README.md
Creates a custom image converter for Mammoth. This allows for fine-grained control over how images are processed and rendered in the output.
```APIDOC
## mammoth.images.imgElement(func)
### Description
An image converter can be created by calling `mammoth.images.imgElement(func)`. This creates an `` element for each image in the original docx. `func` should be a function that has one argument `image`.
### Parameters
#### Path Parameters
- `func` (function) - Required - A function that takes an `image` object and returns an object of attributes for the `` element.
- `image` (object) - Properties:
- `contentType` (string): The content type of the image (e.g., `image/png`).
- `readAsArrayBuffer()`: Returns a promise of an `ArrayBuffer`.
- `readAsBuffer()`: Returns a promise of a `Buffer` (Node.js only).
- `readAsBase64String()`: Returns a promise of a base64-encoded string.
- `read([encoding])` (deprecated): Returns a promise of a `Buffer` or `string`.
### Returns
An image converter function that can be used with Mammoth.
### Example
```javascript
mammoth.images.imgElement(function(image) {
return image.readAsBase64String().then(function(imageBuffer) {
return {
src: "data:" + image.contentType + ";base64," + imageBuffer
};
});
})
```
```
--------------------------------
### Express.js Middleware for Document Conversion
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/09-usage-patterns.md
Sets up an Express.js server to serve the Mammoth.js browser version and provides an API endpoint for converting DOCX files to HTML using a custom style map. Ensure 'uploads/document.docx' and 'styles.txt' exist.
```javascript
var express = require("express");
var fs = require("fs");
var mammoth = require("mammoth");
var app = express();
// Serve mammoth in browser
app.use("/mammoth.js", express.static("node_modules/mammoth/mammoth.browser.min.js"));
// Conversion endpoint
app.post("/api/convert", function(req, res) {
var inputFile = "uploads/document.docx";
var styleMap = fs.readFileSync("styles.txt", "utf8");
mammoth.convertToHtml({path: inputFile}, {styleMap: styleMap})
.then(function(result) {
res.json({
html: result.value,
messages: result.messages
});
})
.catch(function(error) {
res.status(500).json({
error: error.message
});
});
});
app.listen(3000);
```
--------------------------------
### Custom Style Map for Strikethrough Text
Source: https://github.com/mwilliamson/mammoth.js/blob/master/README.md
Alter the HTML tag used for strikethrough text by mapping the 'strike' style. This example changes strikethrough text to be wrapped in tags instead of the default .
```javascript
var mammoth = require("mammoth");
var options = {
styleMap: [
"strike => del"
]
};
mammoth.convertToHtml({path: "path/to/document.docx"}, options);
```
--------------------------------
### Minimal Mammoth.js Conversion
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/08-configuration.md
Use default settings for a quick conversion. This applies default style maps, handles images using base64 encoding, and ignores empty paragraphs.
```javascript
mammoth.convertToHtml({path: "document.docx"})
// Uses all defaults: default style map, base64 images, ignore empty paragraphs
```
--------------------------------
### Custom Style Map for Bold Text
Source: https://github.com/mwilliamson/mammoth.js/blob/master/README.md
Modify the default behavior for bold text by adding a style mapping for 'b'. This example changes bold text to be wrapped in tags instead of .
```javascript
var mammoth = require("mammoth");
var options = {
styleMap: [
"b => em"
]
};
mammoth.convertToHtml({path: "path/to/document.docx"}, options);
```
--------------------------------
### Basic File Upload for DOCX Conversion
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/10-browser-usage.md
Handles a basic file upload from an HTML input element, reads the file as an ArrayBuffer, and converts it to HTML using Mammoth.js. The output is displayed in a designated div.
```html
```
--------------------------------
### Reuse Configuration Across Multiple Conversions
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/08-configuration.md
Define common options in a single object and reuse it for multiple document conversions to maintain consistency and reduce redundancy.
```javascript
var commonOptions = {
styleMap: fs.readFileSync("styles.txt", "utf8"),
idPrefix: "document-",
ignoreEmptyParagraphs: false
};
// Use for multiple conversions
var doc1Promise = mammoth.convertToHtml({path: "doc1.docx"}, commonOptions);
var doc2Promise = mammoth.convertToHtml({path: "doc2.docx"}, commonOptions);
```
--------------------------------
### Convert DOCX to HTML via CLI
Source: https://github.com/mwilliamson/mammoth.js/blob/master/README.md
Convert a .docx file to an HTML fragment using the Mammoth.js CLI. Output is written to stdout if no output file is specified.
```bash
mammoth document.docx output.html
```
--------------------------------
### Content Security Policy Meta Tag
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/10-browser-usage.md
Implement a Content Security Policy (CSP) using a meta tag to mitigate security risks like XSS and data injection. This example restricts script and style sources.
```html
```
--------------------------------
### Check Document Structure with extractRawText()
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/06-error-handling.md
This example shows how to use `extractRawText()` to read a DOCX file and log any issues or the total character count. It's useful for verifying document readability and identifying potential parsing problems.
```javascript
mammoth.extractRawText({path: "document.docx"})
.then(function(result) {
if (result.messages.length > 0) {
console.log("Issues during text extraction:");
result.messages.forEach(function(msg) {
console.log(msg.message);
});
}
console.log("Document has " + result.value.length + " characters");
})
.catch(function(error) {
console.error("Cannot read document:", error.message);
});
```
--------------------------------
### Measure Mammoth Conversion Time
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/07-cli-reference.md
Use the `time` command to measure the execution time of the Mammoth CLI for large documents. This helps in identifying performance bottlenecks.
```bash
time mammoth large-document.docx output.html
```
--------------------------------
### Style Transformation and Mapping in Mammoth.js
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/08-configuration.md
Apply custom transformations to the document structure before applying style mappings. This example transforms centered paragraphs by assigning them a 'centered' style ID and name, then maps this new style to a CSS class.
```javascript
mammoth.convertToHtml({path: "document.docx"}, {
// First transform the document structure
transformDocument: function(doc) {
return mammoth.transforms.paragraph(function(para) {
if (para.alignment === "center") {
return Object.assign({}, para, {
styleId: "centered",
styleName: "Centered"
});
}
return para;
})(doc);
},
// Then apply style mappings to the transformed structure
styleMap: [
"p[style-name='Centered'] => p.centered:fresh"
]
})
```
--------------------------------
### Load Style Map from File
Source: https://github.com/mwilliamson/mammoth.js/blob/master/_autodocs/10-browser-usage.md
This snippet allows you to load a custom style map from a separate text file. It first reads the style map file and then uses it when converting the DOCX file to HTML.
```html
```