---
title: "NodeJS Docx Templater"
date: 2022-11-29T13:21:47.000Z
author: Z.SHINCHVEN
tags: [docx, Node.js, docx template]
canonical: https://atlassc.net/2022/11/29/nodejs-docxtemplater
---
[docxtemplater](https://docxtemplater.com/) is a library to generate docx files from a docx template with `{tag}`, it is written in [TypeScript](https://github.com/guigrpa/docx-templates).

The open source version supports:
- {tag} replacement
- Conditions
- Loops
- Change delimiters

Other features like `chart`, `image insert` and `pptx/xlsx` supports are provided in [paid versions](https://docxtemplater.com/pricing/).

## Node Usage

### Installation

```bash
npm i docxtemplater pizzip
```

### Usage

```js
const PizZip = require("pizzip");
const Docxtemplater = require("docxtemplater");

const fs = require("fs");
const path = require("path");

// Load the docx file as binary content
const content = fs.readFileSync(
    path.resolve(__dirname, "input.docx"),
    "binary"
);

const zip = new PizZip(content);

const doc = new Docxtemplater(zip, {
    paragraphLoop: true,
    linebreaks: true,
});

// Render the document (Replace {first_name} by John, {last_name} by Doe, ...)
doc.render({
    first_name: "John",
    last_name: "Doe",
    phone: "0652455478",
    description: "New Website",
});

const buf = doc.getZip().generate({
    type: "nodebuffer",
    // compression: DEFLATE adds a compression step.
    // For a 50MB output document, expect 500ms additional CPU time
    compression: "DEFLATE",
});

// buf is a nodejs Buffer, you can either write it to a
// file or res.send it with express for example.
fs.writeFileSync(path.resolve(__dirname, "output.docx"), buf);
```

## References

- [Official site](https://docxtemplater.com/)
- [GitHub](https://github.com/open-xml-templating/docxtemplater)
- [npm](https://www.npmjs.com/package/docxtemplater)

## Alternatives

- [docx-templates](https://www.npmjs.com/package/docx-templates) - supports image insert for free.
