Exapedia / Tools / JavaScript Word document libraries JavaScript Word document libraries Updated Nov 2026
JavaScript Word document libraries read, create, and fill in .docx files from code. A template library fills placeholders in a document authored in Word rather than building each paragraph in code. These libraries generate the contracts, invoices, and reports that apps export as Word files.
Popularity Mammoth docx docx-preview Docxtemplater html-to-docx @turbodocx/html-to-docx docx-templates easy-template-x FAQ Popularity Mammoth has the most monthly downloads in this comparison, at 59.9M .
Libraries and code examples Converts Word content into semantic HTML or extracts plain text for indexing and processing.
Downloads / mo 59.9M
Stars 6.3K
Last release 1.13.0
License BSD-2-Clause Strengths Extracts text for downstream processing . extractRawText returns document text without formatting. Maps Word styles into HTML . Map named paragraph styles to headings and other HTML elements. Limitations Table borders are discarded . Table content survives conversion, while table border formatting is ignored. Untrusted HTML needs separate sanitization . Sanitize converted content before embedding it into a website. $ npm install mammoth Copy
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);
});
Mammoth examples From open-source projects on GitHub async function wordDocToText(file: Express.Multer.File): Promise<string> {
const buffer = await fs.promises.readFile(file.path);
/* Reject zip-bomb DOCX before mammoth's internal extractor runs.
* mammoth has no decompressed-size cap of its own; without this, a
* sub-1MB compressed bomb (~200x ratio) would block the event loop
* and spike RSS to ~1GB. See SEC review on PR #12934. */
await assertSafeZipSize(buffer, { name: file.originalname ?? 'docx' });
const { extractRawText } = await import('mammoth');
const rawText = await extractRawText({ buffer });
return rawText.value;
}
Show full example Generates Word documents in JavaScript or TypeScript for Node.js and browser applications.
Downloads / mo 43.4M
Stars 6.0K
Last release 9.15.4
License MIT Strengths Builds rich Word documents . Add tables, images, charts, headers, and footers with the document API. Updates existing Word templates . patchDocument replaces placeholders while preserving the surrounding document structure. Converts rich HTML into content . htmlToContent turns HTML into native Word paragraphs and tables. Limitations PDF export needs another tool . Generate Word files here, then convert them separately for PDF delivery. HTML images need supplied data . Pass image data explicitly; htmlToContent does not download remote images. $ npm install --save docx Copy
import { Document, Packer, Paragraph, TextRun } from "docx";
import * as fs from "fs";
const doc = new Document({
sections: [
{
// Documents are organized into sections
children: [
new Paragraph({
children: [new TextRun("Hello World!")],
}),
],
},
],
});
Packer.toBuffer(doc).then((buffer) => {
fs.writeFileSync("My Document.docx", buffer);
});
docx examples From open-source projects on GitHub public exportToWord = async (markdown: string, fileName: string, senderId?: string | null): Promise<boolean> => {
try {
// Dialog-first is perf-driven: canceling costs zero conversion, and the dialog
// opens without waiting on the markdown→docx conversion.
const dialogOptions = {
title: t('dialog.save_file'),
filters: [{ name: t('dialog.word_document'), extensions: ['docx'] }],
defaultPath: fileName
}
// Parented dialog avoids the unparented-save crash with Unicode names.
// Missing or destroyed caller window falls back to the unparented overload.
const candidate: BrowserWindow | undefined = senderId
? application.get('WindowManager').getWindow(senderId)
: undefined
const parent = candidate && !candidate.isDestroyed() ? candidate : undefined
const { canceled, filePath } = parent
? await dialog.showSaveDialog(parent, dialogOptions)
: await dialog.showSaveDialog(dialogOptions)
if (canceled || !filePath) {
return false
}
const [{ default: MarkdownIt }, docx] = await Promise.all([import('markdown-it'), import('docx')])
const elements = this.convertMarkdownToDocxElements(markdown, new MarkdownIt(), docx)
const doc = new docx.Document({
styles: {
paragraphStyles: [
{
id: 'Normal',
name: 'Normal',
run: {
size: 24,
font: 'Arial'
}
}
]
},
sections: [
{
properties: {},
children: elements
}
]
})
const buffer = await docx.Packer.toBuffer(doc)
await fs.promises.writeFile(filePath, buffer)
logger.debug('Document exported successfully')
return true
} catch (error) {
logger.error('Export to Word failed:', error as Error)
throw error
}
}
Show full example Renders a Word document into HTML inside a web page, keeping HTML semantics where it can.
Downloads / mo 14.4M
Stars 2.2K
Last release 0.4.1
License Apache-2.0 Strengths Renders headers and footers . Options turn the rendering of headers, footers, footnotes, and endnotes on or off. Limitations Limited by what HTML can show . The page renders as HTML rather than as an image of the Word layout. No real-time page breaking . Insert manual page breaks wherever the pages must split. $ npm install docx-preview Copy
<!--lib uses jszip-->
<script src="https://unpkg.com/jszip/dist/jszip.min.js"></script>
<script src="docx-preview.min.js"></script>
<body>
<div id="container"></div>
<script>
</script>
</body>
Generates documents by replacing placeholders, loops, and conditions inside existing Word templates.
Downloads / mo 6.5M
Stars 3.7K
Last release 3.71.1
License MIT Strengths Templates stay editable in Word . Non-programmers can edit the source templates before generation. Repeats sections from structured data . Use loops and conditions to generate repeated or conditional template content. Limitations Images and HTML need modules . Add paid modules to insert images or formatted HTML. Starts with an existing template . Supply a Word template containing the placeholders to replace. $ npm install --save docxtemplater pizzip Copy
const Docxtemplater = require("docxtemplater");
const PizZip = require("pizzip");
const fs = require("fs");
const path = require("path");
const content = fs.readFileSync(
path.resolve(__dirname, "input.docx"),
"binary"
);
const zip = new PizZip(content);
const doc = new Docxtemplater(zip, {
paragraphLoop: true,
linebreaks: true,
});
doc.render({
first_name: "John",
last_name: "Doe",
phone: "+33666666",
description: "The Acme Product",
});
const buf = doc.toBuffer();
fs.writeFileSync(path.resolve(__dirname, "output.docx"), buf);
Docxtemplater examples From open-source projects on GitHub async function generateDoc(audit) {
var templatePath = `${__basedir}/../report-templates/${audit.template.name}.${audit.template.ext || 'docx'}`
var content = fs.readFileSync(templatePath, "binary");
var zip = new PizZip(content);
translate.setLocale(audit.language)
$t = translate.translate
var settings = await Settings.getAll();
var preppedAudit = await prepAuditData(audit, settings)
var opts = {};
// opts.centered = true;
opts.getImage = function(tagValue, tagName) {
if (tagValue !== "undefined") {
tagValue = tagValue.split(",")[1];
return Buffer.from(tagValue, 'base64');
}
// return fs.readFileSync(tagValue, {encoding: 'base64'});
}
opts.getSize = function(img, tagValue, tagName) {
if (img) {
var sizeObj = sizeOf.default(img);
var width = sizeObj.width;
var height = sizeObj.height;
if (tagName === "company.logo_small") {
var divider = sizeObj.height / 37;
height = 37;
width = Math.floor(sizeObj.width / divider);
}
else if (tagName === "company.logo") {
var divider = sizeObj.height / 250;
height = 250;
width = Math.floor(sizeObj.width / divider);
if (width > 400) {
divider = sizeObj.width / 400;
height = Math.floor(sizeObj.height / divider);
width = 400;
}
}
else if (sizeObj.width > 600) {
var divider = sizeObj.width / 600;
width = 600;
height = Math.floor(sizeObj.height / divider);
}
return [width,height];
}
return [0,0];
}
if (settings.report.private.imageBorder && settings.report.private.imageBorderColor)
opts.border = settings.report.private.imageBorderColor.replace('#', '')
try {
var imageModule = new ImageModule(opts);
}
catch(err) {
console.log(err)
}
expressionParser.filters = {...reportFilters.expressions, ...reportFiltersCustom.expressions}
var doc = new Docxtemplater(zip, {
parser: parser,
paragraphLoop: true,
modules: [imageModule],
});
try {
doc.render(preppedAudit);
}
catch (error) {
if (error.properties.id === 'multi_error') {
error.properties.errors.forEach(function(err) {
console.log(err);
});
}
else
console.log(error)
if (error.properties && error.properties.errors instanceof Array) {
const errorMessages = error.properties.errors.map(function (error) {
return `Explanation: ${error.properties.explanation}\nScope: ${JSON.stringify(error.properties.scope).substring(0,142)}...`
}).join("\n\n");
// errorMessages is a humanly readable message looking like this :
// 'The tag beginning with "foobar" is unopened'
throw `Template Error:\n${errorMessages}`;
}
else {
throw error
}
}
var buf = doc.getZip().generate({type:"nodebuffer"});
if (shouldApplyDraftWatermark(audit, settings)) {
var watermarkText = resolveDraftWatermarkText(settings.reviews.public.draftWatermark, audit.language);
buf = applyDraftExport(buf, watermarkText);
}
return buf;
}
Show full example Converts HTML strings into Word documents with configurable page layout, headers, footers, and tables.
Downloads / mo 1.2M
Stars 484
Last release 1.8.0
License MIT Strengths Converts existing HTML into Word . Reuse HTML content as the input for document generation. Adds page numbers to footers . Enable footer page numbers with the pageNumber option. Limitations Runs outside the browser directly . Use a server-side conversion step for browser applications. Fonts vary between Word processors . LibreOffice and Word Online choose replacement fonts themselves. $ npm install html-to-docx file-saver Copy
import HTMLtoDOCX from 'html-to-docx';
import { saveAs } from 'file-saver';
const fileBuffer = await HTMLtoDOCX(htmlString, null, {
table: { row: { cantSplit: true } },
footer: true,
pageNumber: true,
});
saveAs(fileBuffer, 'html-to-docx.docx');
html-to-docx examples From open-source projects on GitHub async function toDocx(md: string): Promise<ExportResult> {
const viaPandoc = pandocConvert(md, 'docx');
if (viaPandoc) return { buffer: viaPandoc, ext: 'docx', mime: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', engine: 'pandoc' };
// JS 兜底:marked → html → html-to-docx
// @ts-expect-error html-to-docx 无类型声明文件
const HTMLtoDOCX = (await import('html-to-docx')).default as (html: string, header?: string | null, opts?: unknown) => Promise<Buffer | ArrayBuffer>;
const out = await HTMLtoDOCX(mdToHtml(md), null, { table: { row: { cantSplit: true } } });
const buffer = Buffer.isBuffer(out) ? out : Buffer.from(out as ArrayBuffer);
return { buffer, ext: 'docx', mime: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', engine: 'html-to-docx' };
}
Show full example Converts HTML into Word documents in Node.js without a headless browser or external binaries.
Downloads / mo 1.0M
Stars 234
Last release 1.23.3
License MIT Strengths Actively maintained fork . TurboDocx continues the original html-to-docx project with the help of its contributors. Limitations SVG conversion needs Node.js . In the browser, SVG images embed natively and need a recent Office release to display. $ npm install @turbodocx/html-to-docx Copy
import HtmlToDocx from "@turbodocx/html-to-docx";
const htmlString = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<h1>Hello world</h1>
</body>
</html>`;
const docx = await HtmlToDocx(htmlString);
@turbodocx/html-to-docx examples From open-source projects on GitHub export async function createInitialDocxBuffer(
filename: string,
content?: InitialDocxContent,
): Promise<Buffer> {
if (!content?.value.trim()) return createBlankDocxBuffer(filename);
if (content.kind === "plain-text") return createPlainTextDocx(filename, content.value);
const title = filename.replace(/\.[^.]+$/, "") || "Untitled Document";
const html = `<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title>${title}</title></head>
<body>${content.value}</body>
</html>`;
try {
const output = await HTMLtoDOCX(html, null, {
title,
creator: "Prism",
font: "Calibri",
fontSize: 22,
table: { row: { cantSplit: true } },
footer: true,
pageNumber: true,
});
const buffer = await outputBuffer(output);
if (!buffer) throw new Error("Document conversion returned no bytes");
return buffer;
} catch (error) {
throw new DocxConversionError({ cause: error });
}
}
Show full example Creates reports from Word templates that hold commands, in Node.js or the browser.
Downloads / mo 555.7K
Stars 1.1K
Last release 4.15.0
License MIT Strengths Templates run JavaScript . Commands in the template run JavaScript and insert its results into the document. Repeats table rows . FOR and END-FOR commands repeat content for each item, including table rows. Limitations Template code runs untranspiled . Write template code that the target browsers support without a transpiler. $ npm install docx-templates Copy
import createReport from 'docx-templates';
import fs from 'fs';
const template = fs.readFileSync('myTemplate.docx');
const buffer = await createReport({
template,
data: {
name: 'John',
surname: 'Appleseed',
},
});
fs.writeFileSync('report.docx', buffer)
Fills Word templates with data through tags, in Node.js or the browser.
Downloads / mo 233.8K
Stars 537
Last release 8.1.0
License MIT Strengths Adds charts, images, and links . Plugins insert images, hyperlinks, charts, and raw XML into a template. Repeats rows and lists . A loop tag repeats text, table rows, table columns, or list items. Limitations Loops need paired tags . Mark each loop with an opening tag that starts with # and a closing tag that starts with a slash. $ npm install easy-template-x Copy
import * as fs from "fs";
import { TemplateHandler } from "easy-template-x";
// 1. read template file
const templateFile = fs.readFileSync("myTemplate.docx");
// 2. process the template
const data = {
posts: [
{ author: "Anakin", text: "Luke, I am\nyour father." },
{ author: "Luke", text: "No! That's impossible!" }
]
};
const handler = new TemplateHandler();
const doc = await handler.process(templateFile, data);
// 3. save output
fs.writeFileSync("myTemplate - output.docx", doc);
easy-template-x examples From open-source projects on GitHub public async DocxTemplateFill(
pcfContext: ComponentFramework.Context<IInputs>
): Promise<string> {
var params = pcfContext.parameters;
var dataSet = pcfContext.parameters.templateData?.raw || "{}";
var dataSetObject = JSON.parse(dataSet);
await this.updateImagesToArrayBuffer(dataSetObject);
const handler = new TemplateHandler();
const docxFilled = await handler.process(
this.convertStringToArray(params.docxTemplate.raw!),
dataSetObject
);
return encode(docxFilled);
}
Show full example For coding agents
Found your Word document library? Help your agent use it. Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.
Claude Code Cursor Codex VS Code Devin Devin Desktop Gemini CLI OpenCode
Run in your terminal
claude plugin install exa@claude-plugins-official Copy Add to ~/.cursor/mcp.json
{
"mcpServers": {
"exa": {
"url": "https://mcp.exa.ai/mcp"
}
}
} Copy Open in your browser, then install the Exa plugin
https://chatgpt.com/plugins/exa Copy Add to .vscode/mcp.json
{
"servers": {
"exa": {
"type": "http",
"url": "https://mcp.exa.ai/mcp"
}
}
} Copy In Devin, open Customize, then MCPs, and add a custom HTTP server with this URL
https://mcp.exa.ai/mcp Copy Add to ~/.config/devin/mcp_config.json
{
"mcpServers": {
"exa": {
"serverUrl": "https://mcp.exa.ai/mcp"
}
}
} Copy Add to ~/.gemini/settings.json
{
"mcpServers": {
"exa": {
"httpUrl": "https://mcp.exa.ai/mcp"
}
}
} Copy Add to opencode.json
{
"mcp": {
"exa": {
"type": "remote",
"url": "https://mcp.exa.ai/mcp"
}
}
} Copy