Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

cnptechnology-docxtemplater

.docx generator working with templates and data (like Mustache)

docx, templates, generation, microsoft word

readme

docxtemplater

Join the chat at https://gitter.im/open-xml-templating/docxtemplater

Build Status Download count Current tag Issues closed

docxtemplater logo

docxtemplater is a library to generate docx/pptx documents from a docx/pptx template. It can replace {placeholders} with data and also supports loops and conditions. The templates can be edited by non-programmers, eg for example your clients.

Note: The CLI will soon be moved to another repository : keep posted on https://github.com/open-xml-templating/docxtemplater-cli

Features

Demo Site

Quickstart in Node

Installation: npm install docxtemplater

var fs = require('fs');
var Docxtemplater = require('docxtemplater');

//Load the docx file as a binary
var content = fs
    .readFileSync(__dirname + "/input.docx", "binary");

var doc = new Docxtemplater(content);

//set the templateVariables
doc.setData({
    "first_name":"Hipp",
    "last_name":"Edgar",
    "phone":"0652455478",
    "description":"New Website"
});

//apply them (replace all occurences of {first_name} by Hipp, ...)
doc.render();

var buf = doc.getZip()
             .generate({type:"nodebuffer"});

fs.writeFileSync(__dirname+"/output.docx",buf);

You can download input.docx and put it in the same folder than your script.

Quickstart in the browser

Installation

JS download

You can directly download built versions from github : https://github.com/open-xml-templating/docxtemplater-build/tree/master/build

If you download the JS from there, you should use new Docxgen() instead of new Docxtemplater(), because I do not want to bring in a breaking change on a minor version change in the docxtemplater-build repository.

Bower

bower install --save docxtemplater

If you download the JS from there, you should use new Docxgen() instead of new Docxtemplater(), because I do not want to bring in a breaking change on a minor version change in the docxtemplater-build repository.

Build it yourself

I recommend you to use the npm scripts I wrote (which can be found in the package.json).

git clone git@github.com:edi9999/docxtemplater.git && cd docxtemplater
# git checkout v2.0.0 # Optional
npm install
npm run compile
# Optionally :
# npm run browserify
# npm run uglify:lib

Docxtemplater will be exported to window.Docxtemplater for easy usage (on some systems, it might export it in window.docxtemplater (see https://github.com/edi9999/docxtemplater/issues/118)\)

Your version of docxtemplater will be in /build (minified and non minified options) and already include all dependencies

Html demo

Create the following html

<html>
    <script src="build/docxtemplater.js"></script>
    <script src="vendor/FileSaver.min.js"></script>
    <script src="vendor/jszip-utils.js"></script>
    <!--
    Mandatory in IE 6, 7, 8 and 9.
    -->
    <!--[if IE]>
        <script type="text/javascript" src="examples/vendor/jszip-utils-ie.js"></script>
    <![endif]-->
    <script>
    var loadFile=function(url,callback){
        JSZipUtils.getBinaryContent(url,callback);
    }
    loadFile("examples/tagExample.docx",function(err,content){
        if (err) { throw e};
        doc=new Docxtemplater(content);
        doc.setData( {"first_name":"Hipp",
            "last_name":"Edgar",
            "phone":"0652455478",
            "description":"New Website"
            }
        ) //set the templateVariables
        doc.render() //apply them (replace all occurences of {first_name} by Hipp, ...)
        out=doc.getZip().generate({type:"blob"}) //Output the document using Data-URI
        saveAs(out,"output.docx")
    })
    </script>
</html>

Documentation

The full documentation of the latest version can be found on read the docs.

See CHANGELOG.md for information about how to migrate from older versions.

Similar libraries

They are a few similar libraries that work with docx, here’s a list of those I know a bit about:

  • docx4j :JAVA, this is probably the biggest docx library out there. They is no built in templating engine, but you can generate your docx yourself programmatically
  • docx.js: Javascript in the browser, you can create (not modify) your docx from scratch, but only do very simple things such as adding non formatted text
  • xlsx-templater : its working quite well, does the same as here but for xlsx

Modules

Functionality can be added with modules. They is yet no doc for the modules because it is not completely mature yet, but you can open an issue if you have any question about it.

Here is the list of existing modules:

Professional Support

I can give your company support for installing, extending, answering support questions, or maintainning your app that runs docxtemplater. You can find my email address on my profile

changelog

master

2.1.5

  • Fix stacktrace not showing up (#245)

2.1.4

  • Fixed a memory leak when using large document (10Mb document.xml) (#237)
  • Add fileTypeConfig options in setOptions to define your own fileType config (#235)

2.1.3

  • {@rawXml} has been fixed for pptx

2.1.2

  • Add possibility to close loopTag with {/} #192

2.1.1

  • Bug fix : Some times, docxtemplater could eat lots of memory due to the new "compilation" feature that was only experimental. As this feature is not yet used, it was completely removed from the codebase.
  • Performance : The code has been made a little bit faster.

2.1.0

  • Speed Improvements : docxtemplater had a regression causing it to be slow for loops. The regression would cause the code to run in O(n²) instead of O(n) where n is the length of the loops (with {#users}{name}{/users}. The bug is now fixed, and docxtemplater gained a lot of speed for users of lengthy loops.

2.0.0

  • Breaking : To choose between docx or pptx, you now have to pass docx.setOptions({fileType:'docx'}) where the fileTypes are one of 'pptx', 'docx' (default is 'docx')
  • Using es6 instead of coffeescript to code (code is still compiled to es5, to be usable with node v0.{10,12} or in the browser)
  • Add finalize step in render function to throw an error if a tag is unclosed
  • Module API has been updated, notably the tagXml property doesn't exist anymore, you should use the properties in fileTypeConfig
  • You should check if your modules have updated for the new module API, for instance, you should use version 1.0 of the docxtemplater image module

For example :

var xmlTemplater = this.manager.getInstance("xmlTemplater");
var tagXml = xmlTemplater.fileTypeConfig.tagsXmlArray[0];

1.2.1

  • It is now possible to use tags inside of docx equations

1.2.0

  • This release adds error management, all errors that are thrown by docxtemplater are now typed and contain additional properties.

1.1.6

  • fix : When using loops with images inside, the modulemanager was not updated and would continue to return 'image' for the type of the tag even if the type changed

1.1.5

  • feature : it is now possible to set the nullgetter for simple tags and for raw xml tags.

1.1.4

  • bugfix for the modulemanager : it was not in sync in some cases

1.1.3

  • They now is a default value for rawtags {@rawXml}, which is '' (this will delete the paragraph)

1.1.2

  • bugfix (There was still '{' and '}' hardcoded)

1.1.1

  • It is now possible to output the delimiters in the output (for example output "Mark } Z" with the template {name}
  • scopeManager now doesn't return the string 'undefined' when the parser returns null. That behaviour is moved to the xmlTemplater class

1.1.0

  • docxtemplater is now much faster to process loops #131
  • docutils should not be used any more except for DocUtils.defaults (eg docutils is deprecated)
  • Module maintainers: please don't rely on docUtils anymore, except for docUtils.defaults
  • Some templates would output corrupt templates, this should not happen anymore (if it still does, please open an issue)

Upgrade guide :

  • If you use modules (image-module, chart-module, or others) its best to update those because they shouldn't use DocUtils anymore

1.0.8

  • Add ScopeManager.loopOverValue

1.0.7

  • {@rawXml} works in pptx
  • Created new docxtemplater.com website
  • Using mocha instead of jasmine-node
  • New FAQ section in docs

1.0.6

  • Corrupt documents when <w:t>}{/body}</w:t>

1.0.5

  • New events for moduleManager : xmlRendering and xmlRendered

1.0.4

  • pptx generation was repaired 2be10b69d47e8c4ba0f541e4d201b29ef6281505
  • header generation works with any amount of headers/footers
  • slide generation works with any amount of slides

1.0.3

  • docx.setOptions({delimiters:{start:”[“,end:”]”}}) now works e2d06dedd88860d2dac3d598b590bf81e2d113a6

1.0.2

  • allowing same tag as start and end delimiter (eg @user@ instead of {user}) 32b9a7645f659ae835fd695e4d8ea99cc6bbec94

1.0.1

  • made it possible to use objects to loop over (eg {#user} {name} {/user}) 97411cb3537be08f48ff707ac34d6aac8b008c50

From 0.7.x to 1

  • docxtemplater doesn’t depend on fs anymore, for transparency and security reasons.
  • loadFromFile has been removed. You now just have to pass the content to Docxtemplater’s constructor.
  • setTags has been renamed to setData
  • applyTags has been renamed to render
  • the constructor has changed: eg new Docxtemplater(content,options) will now call JSzip.load(content,options).
  • To pass options (such as the parser), you will have to call setOptions
  • The output function has been removed. You should now call getZip().generate(options) where the options are documented here: https://stuk.github.io/jszip/documentation/api_jszip/generate.html
  • the qrcode module has been removed, and will be developped in an other package that will be attached to docxtemplater

From 0.6.0 to 0.7.0

The QrCode Option had a security issue. If you don’t upgrade according to this, the functionality should continue to work but the leak will still be there. If you are running in the browser, the vulnerability will not affect you (no access to the filesystem). If the users can’t change the qrCodes or their value, you’re safe too.

If you set qrCode:true, you are affected. The Command Line is not affected as of v0.7.0 (but was on 0.6.3 and less). However the command line as of v0.7.0 is not more able to load images over the filesystem.

You should set qrCode to a function now, according to https://docxtemplater.readthedocs.io/en/latest/configuration.html#image-replacing.