# JavaScript Word document libraries

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

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [Mammoth](#mammoth) | 59.9M | 6.3K | Sep 2026 | BSD-2-Clause |
| [docx](#docx) | 43.4M | 6.0K | Nov 2026 | MIT |
| [docx-preview](#docx-preview) | 14.4M | 2.2K | Sep 2026 | Apache-2.0 |
| [Docxtemplater](#docxtemplater) | 6.5M | 3.7K | Oct 2026 | MIT |
| [html-to-docx](#html-to-docx) | 1.2M | 484 | Mar 2023 | MIT |
| [@turbodocx/html-to-docx](#turbodocx-html-to-docx) | 1.0M | 234 | Oct 2026 | MIT |
| [docx-templates](#docx-templates) | 555.7K | 1.1K | Dec 2025 | MIT |
| [easy-template-x](#easy-template-x) | 233.8K | 537 | Nov 2026 | MIT |

Downloads: npm, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[Mammoth](#mammoth) has the most monthly downloads in this comparison, at 59.9M.

## Capabilities

| Library | Create DOCX content | Word template input |
| --- | --- | --- |
| [Mammoth](#mammoth) | No | No |
| [docx](#docx) | Yes | Yes |
| [docx-preview](#docx-preview) | No | No |
| [Docxtemplater](#docxtemplater) | Yes | Yes |
| [html-to-docx](#html-to-docx) | Yes | No |
| [@turbodocx/html-to-docx](#turbodocx-html-to-docx) | Yes | No |
| [docx-templates](#docx-templates) | Yes | Yes |
| [easy-template-x](#easy-template-x) | Yes | Yes |

## Libraries

### Mammoth

[GitHub](https://github.com/mwilliamson/mammoth.js) · [npm](https://www.npmjs.com/package/mammoth) · [Docs](https://cdn.jsdelivr.net/npm/mammoth@1.13.0/README.md)

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
- Capabilities: [From the Mammoth docs](https://cdn.jsdelivr.net/npm/mammoth@1.13.0/README.md)

**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.

**Watch out for**

- **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.

```sh
npm install mammoth
```

**LibreChat-AI/LibreChat** (47.2K stars)

[LibreChat-AI/LibreChat](https://github.com/LibreChat-AI/LibreChat) 

```javascript
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;
}

```

[packages/api/src/files/documents/crud.ts](https://github.com/LibreChat-AI/LibreChat/blob/9363db541ecd4e23ab6a41dca47ca48ee2bd418e/packages/api/src/files/documents/crud.ts#L103-L113) · [More projects using Mammoth →](https://dashboard.exa.ai/playground/search?q=JavaScript%20TypeScript%20projects%20using%20mammoth%20to%20export%20Word%20reports%2C%20fill%20templates%2C%20convert%20HTML%20or%20extract%20uploaded%20document%20text&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

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

```

From [README.md](https://github.com/mwilliamson/mammoth.js/blob/master/README.md)

### docx

[GitHub](https://github.com/dolanmiu/docx) · [npm](https://www.npmjs.com/package/docx) · [Docs](https://docx.js.org/)

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
- Capabilities: [From the docx docs](https://docx.js.org/)

**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.

**Watch out for**

- **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.

```sh
npm install --save docx
```

**CherryHQ/cherry-studio** (53.6K stars)

[CherryHQ/cherry-studio](https://github.com/CherryHQ/cherry-studio) 

```javascript
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
    }
  }

```

[src/main/services/ExportService.ts](https://github.com/CherryHQ/cherry-studio/blob/b8241ecaac3ee0e33711c67592e24ab1b23152cc/src/main/services/ExportService.ts#L378-L433) · [More projects using docx →](https://dashboard.exa.ai/playground/search?q=JavaScript%20TypeScript%20projects%20using%20docx%20to%20export%20Word%20reports%2C%20fill%20templates%2C%20convert%20HTML%20or%20extract%20uploaded%20document%20text&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

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

```

From [quickstart.md](https://github.com/dolanmiu/docx/blob/master/docs/quickstart.md)

### docx-preview

[GitHub](https://github.com/VolodymyrBaydalka/docxjs) · [npm](https://www.npmjs.com/package/docx-preview) · [Docs](https://api.github.com/repos/VolodymyrBaydalka/docxjs/contents/README.md)

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
- Capabilities: [From the docx-preview docs](https://api.github.com/repos/VolodymyrBaydalka/docxjs/contents/README.md)

**Strengths**

- **Renders headers and footers.** Options turn the rendering of headers, footers, footnotes, and endnotes on or off.

**Watch out for**

- **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.

```sh
npm install docx-preview
```

**Quickstart**

```javascript
<!--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>

```

From [README.md](https://api.github.com/repos/VolodymyrBaydalka/docxjs/contents/README.md) · [Find projects using docx-preview →](https://dashboard.exa.ai/playground/search?q=docx-preview%20GitHub%20projects)

### Docxtemplater

[GitHub](https://github.com/open-xml-templating/docxtemplater) · [npm](https://www.npmjs.com/package/docxtemplater) · [Docs](https://docxtemplater.com/docs/get-started-node/)

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
- Capabilities: [From the Docxtemplater docs](https://docxtemplater.com/docs/get-started-node/)

**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.

**Watch out for**

- **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.

```sh
npm install --save docxtemplater pizzip
```

**pwndoc/pwndoc** (2.9K stars)

[pwndoc/pwndoc](https://github.com/pwndoc/pwndoc) 

```javascript
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;
}

```

[backend/src/lib/report-generator.js](https://github.com/pwndoc/pwndoc/blob/3be29ba9557bde8d36324f3b0d6b94b8afc7dc61/backend/src/lib/report-generator.js#L37-L134) · [More projects using Docxtemplater →](https://dashboard.exa.ai/playground/search?q=JavaScript%20TypeScript%20projects%20using%20docxtemplater%20to%20export%20Word%20reports%2C%20fill%20templates%2C%20convert%20HTML%20or%20extract%20uploaded%20document%20text&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```javascript
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);

```

From [Get started docs](https://docxtemplater.com/docs/get-started-node/)

### html-to-docx

[GitHub](https://github.com/privateOmega/html-to-docx) · [npm](https://www.npmjs.com/package/html-to-docx) · [Docs](https://api.github.com/repos/privateOmega/html-to-docx/contents/README.md)

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
- Capabilities: [From the html-to-docx docs](https://api.github.com/repos/privateOmega/html-to-docx/contents/README.md)

**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.

**Watch out for**

- **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.

```sh
npm install html-to-docx file-saver
```

**jnMetaCode/agency-orchestrator** (2.5K stars)

[jnMetaCode/agency-orchestrator](https://github.com/jnMetaCode/agency-orchestrator) 

```javascript
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' };
}

```

[src/export/convert.ts](https://github.com/jnMetaCode/agency-orchestrator/blob/8fa9963e4f835efeb5e4481a861689dc99d5ce8d/src/export/convert.ts#L42-L51) · [More projects using html-to-docx →](https://dashboard.exa.ai/playground/search?q=JavaScript%20TypeScript%20projects%20using%20html-to-docx%20to%20export%20Word%20reports%2C%20fill%20templates%2C%20convert%20HTML%20or%20extract%20uploaded%20document%20text&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```javascript
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');

```

From [example-node.js](https://api.github.com/repos/privateOmega/html-to-docx/git/blobs/9b2ecae247f2cad1a2670b65a06452a79b5f6ecd)

### @turbodocx/html-to-docx

[GitHub](https://github.com/TurboDocx/html-to-docx) · [npm](https://www.npmjs.com/package/@turbodocx/html-to-docx) · [Docs](https://api.github.com/repos/TurboDocx/html-to-docx/git/blobs/c51d3af521c33e06b940912de9255aadbc6336e4)

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
- Capabilities: [From the @turbodocx/html-to-docx docs](https://api.github.com/repos/TurboDocx/html-to-docx/git/blobs/c51d3af521c33e06b940912de9255aadbc6336e4)

**Strengths**

- **Actively maintained fork.** TurboDocx continues the original html-to-docx project with the help of its contributors.

**Watch out for**

- **SVG conversion needs Node.js.** In the browser, SVG images embed natively and need a recent Office release to display.

```sh
npm install @turbodocx/html-to-docx
```

**FuturixAI-and-Quantum-Works/Prism-Legal-OS** (227 stars)

[FuturixAI-and-Quantum-Works/Prism-Legal-OS](https://github.com/FuturixAI-and-Quantum-Works/Prism-Legal-OS) 

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

```

[backend/src/modules/documents/documents.docx.ts](https://github.com/FuturixAI-and-Quantum-Works/Prism-Legal-OS/blob/fdb81bc0e66b3a8cfbe4437eab07287b769def8a/backend/src/modules/documents/documents.docx.ts#L77-L105) · [More projects using @turbodocx/html-to-docx →](https://dashboard.exa.ai/playground/search?q=%40turbodocx/html-to-docx%20GitHub%20projects)

**Quickstart**

```javascript
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);

```

From [README.md](https://api.github.com/repos/TurboDocx/html-to-docx/git/blobs/c51d3af521c33e06b940912de9255aadbc6336e4)

### docx-templates

[GitHub](https://github.com/guigrpa/docx-templates) · [npm](https://www.npmjs.com/package/docx-templates) · [Docs](https://api.github.com/repos/guigrpa/docx-templates/git/blobs/a0a84128fcdb6e7514f8b8ff329bf0d5db4c93dc)

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
- Capabilities: [From the docx-templates docs](https://api.github.com/repos/guigrpa/docx-templates/git/blobs/a0a84128fcdb6e7514f8b8ff329bf0d5db4c93dc)

**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.

**Watch out for**

- **Template code runs untranspiled.** Write template code that the target browsers support without a transpiler.

```sh
npm install docx-templates
```

**Quickstart**

```javascript
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)

```

From [README.md](https://api.github.com/repos/guigrpa/docx-templates/git/blobs/a0a84128fcdb6e7514f8b8ff329bf0d5db4c93dc) · [Find projects using docx-templates →](https://dashboard.exa.ai/playground/search?q=docx-templates%20GitHub%20projects)

### easy-template-x

[GitHub](https://github.com/alonrbar/easy-template-x) · [npm](https://www.npmjs.com/package/easy-template-x) · [Docs](https://api.github.com/repos/alonrbar/easy-template-x/git/blobs/0feeeb2ab921d8afc350723fbc6a7470fd283357)

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
- Capabilities: [From the easy-template-x docs](https://api.github.com/repos/alonrbar/easy-template-x/git/blobs/0feeeb2ab921d8afc350723fbc6a7470fd283357)

**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.

**Watch out for**

- **Loops need paired tags.** Mark each loop with an opening tag that starts with # and a closing tag that starts with a slash.

```sh
npm install easy-template-x
```

**rwilson504/PCFControls** (192 stars)

[rwilson504/PCFControls](https://github.com/rwilson504/PCFControls) 

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

```

[DocxTemplatesCanvas/DocxTemplatesCanvas/index.ts](https://github.com/rwilson504/PCFControls/blob/4c782af7df3cce9303263ddb226910368eac4953/DocxTemplatesCanvas/DocxTemplatesCanvas/index.ts#L82-L97) · [More projects using easy-template-x →](https://dashboard.exa.ai/playground/search?q=easy-template-x%20GitHub%20projects)

**Quickstart**

```javascript
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);

```

From [README.md](https://api.github.com/repos/alonrbar/easy-template-x/git/blobs/0feeeb2ab921d8afc350723fbc6a7470fd283357)

## FAQ

### What is docx.js?

[docx](#docx) is a TypeScript and JavaScript library that generates Word documents through a declarative API. It runs in Node.js and in the browser.

### What is docx-preview?

[docx-preview](#docx-preview) renders a Word document into HTML inside a web page. Its output follows what HTML can display rather than the exact Word layout.

### What is Docxtemplater?

[Docxtemplater](#docxtemplater) generates Word documents from a template by replacing placeholders with data. Its templates support loops and conditions, and people without programming skills can edit them in Word.

### What is Mammoth.js?

[Mammoth](#mammoth) converts a Word document into HTML built from the document's semantic styles. Its extractRawText function returns the plain text without formatting.

### Can html-to-docx run directly in a browser?

The unscoped html-to-docx package states that direct browser use does not work.

### Does Mammoth preserve Word table borders?

Mammoth ignores formatting of the table itself, including borders.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best JavaScript DOCX libraries docx Docxtemplater html-to-docx Mammoth code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
