Releases RSS Feed
Compatibility : nodejs and browser

Summary (version 3.8.3) Buy image module

This module exposes a tag to add an image from a tag.

This module is available as part of the docxtemplater PRO plan.


This version is only compatible with docxtemplater version 3

Here is a compatibility table :

image-module docxtemplater
version 3.7.x version >=3.15.1
version 3.6.x version >=3.15.1
version 3.5.x version >=3.9.0
version 3.4.x version 3.9.x
version 3.3.x version 3.9.x
version 3.2.x version 3.9.x
version 3.1.0 version 3.1.0


You will need docxtemplater npm install docxtemplater

Install this module with npm install --save "$url"


It is possible to retrieve data from any data source (synchronously or asynchronously).

For example :

  • from base64 data
  • from the filesystem
  • from a url like :
  • from an Amazon S3 stored image

The tag should be prefixed by % to be parsed as an image. So for example, you could use :{%image} which will take the data from the image key, or {%secondImage} to take the data from the secondImage key.

Usage (nodejs)

The below example is in nodejs, to read the image data from the filesystem :

var ImageModule = require("docxtemplater-image-module");

var opts = {};
opts.centered = false;
opts.getImage = function (tagValue, tagName) {
  return fs.readFileSync(tagValue);

opts.getSize = function (img, tagValue, tagName) {
  return [150, 150];

var imageModule = new ImageModule(opts);

var zip = new PizZip(content);
var doc = new Docxtemplater(zip, { modules: [imageModule] });
doc.setData({ image: "examples/image.png" }).render();

var buffer = doc
  .generate({ type: "nodebuffer", compression: "DEFLATE" });

fs.writeFile("test.docx", buffer);

Usage (browser)

In the browser, this shows how to get the image from a URL :

  <script src="node_modules/docxtemplater/build/docxtemplater.js"></script>
  <script src="node_modules/pizzip/dist/pizzip.js"></script>
  <script src="node_modules/pizzip/vendor/FileSaver.js"></script>
  <script src="node_modules/pizzip/dist/pizzip-utils.js"></script>
  <script src="build/imagemodule.js"></script>
    PizZipUtils.getBinaryContent("examples/image-example.docx", function (
    ) {
      if (error) {
      var opts = {};
      opts.centered = false;
      opts.getImage = function (tagValue, tagName) {
        return new Promise(function (resolve, reject) {
          PizZipUtils.getBinaryContent(tagValue, function (error, content) {
            if (error) {
              return reject(error);
            return resolve(content);
      opts.getSize = function (img, tagValue, tagName) {
        return [150, 150];

        // To use this feature, you have to be using docxtemplater async
        // (if you are calling setData(), you are not using async).
        return new Promise(function (resolve, reject) {
          var image = new Image();
          image.src = url;
          image.onload = function () {
            resolve([image.width, image.height]);
          image.onerror = function (e) {
            console.log("img, tagValue, tagName : ", img, tagValue, tagName);
            alert("An error occured while loading " + tagValue);

      var imageModule = new ImageModule(opts);

      var zip = new PizZip(content);
      var doc = new docxtemplater(zip, { modules: [imageModule] });

      doc.resolveData({ image: "examples/image.png" }).then(function () {
        var out = doc.getZip().generate({
          type: "blob",
        saveAs(out, "generated.docx");

After installing the module, you can use a working demo by running node sample.js.

To understand what img, tagValue, tagName mean, lets take an example :

If your template is :


and your data:

  "myImage": "sampleImage.png"
  • tagValue will be equal to "sampleImage.png"
  • tagName will be equal to "myImage"
  • img will be what ever the getImage function returned

One of the most useful cases of this is to set the images to be the size of that image.

For this, you will need to install the npm package 'image-size' then, write:

opts = { centered: false };
opts.getImage = function (tagValue) {
  return fs.readFileSync(tagValue, "binary");
opts.getSize = function (img) {
  sizeOf = require("image-size");
  var sizeObj = sizeOf(img);
  return [sizeObj.width, sizeObj.height];
imageModule = new ImageModule(opts);
// ...

Centering images

You can center the images using opts.centered = true or by using {%%image} instead of {%image} in your documents

Avoid images bigger than their container

If you include some images inside tables, it is possible that you get some images that are not shown completely because they are bigger than their container.

To circunvent this issue, you can, starting from the image-module version 3.6.0, do the following to never overflow the containerWidth and keep the aspect ratio

opts = {};
opts.getSize = function (buffer, value, tagName, context) {
  sizeOf = require("image-size");
  var sizeObj = sizeOf(img);
  const maxWidth = context.part.containerWidth;
  const ratio = sizeObj.width / sizeObj.height;
  let newWidth = Math.min(maxWidth, sizeObj.width);
  let newHeight = parseInt(newWidth / ratio, 10);
  return [newWidth, newHeight];
imageModule = new ImageModule(opts);

Async support

It is possible to get images asynchronously by returning a Promise in the getImage function and use the docxtemplater async api.

Here is an example in node that allows you to retrieve values from an URL and use a fixed width, and keep the aspect ratio.

const fs = require("fs");
const Docxtemplater = require("docxtemplater");
const https = require("https");
const Stream = require("stream").Transform;

const ImageModule = require("./es6");
const PizZip = require("pizzip");

const content = fs.readFileSync("demo_template.docx");

const data = { image: "" };

const opts = {};
opts.getImage = function (tagValue, tagName) {
  console.log(tagValue, tagName);
  // tagValue is "" and tagName is "image"
  return new Promise(function (resolve, reject) {
    getHttpData(tagValue, function (err, data) {
      if (err) {
        return reject(err);

opts.getSize = function (img, tagValue, tagName) {
  console.log(tagValue, tagName);
  // img is the value that was returned by getImage
  // This is to force the width to 600px, but keep the same aspect ratio
  const sizeOf = require("image-size");
  const sizeObj = sizeOf(img);
  const forceWidth = 600;
  const ratio = forceWidth / sizeObj.width;
  return [
    // calculate height taking into account aspect ratio
    Math.round(sizeObj.height * ratio),

const imageModule = new ImageModule(opts);

const zip = new PizZip(content);
const doc = new Docxtemplater(zip, { modules: [imageModule] });

  .then(function () {
    console.log("data resolved");
    const buffer = doc
      .generate({ type: "nodebuffer", compression: "DEFLATE" });

    fs.writeFileSync("test.docx", buffer);
  .catch(function (error) {
    console.log("An error occured", error);

function getHttpData(url, callback) {
    .request(url, function (response) {
      if (response.statusCode !== 200) {
        return callback(
          new Error(
            `Request to ${url} failed, status code: ${response.statusCode}`

      const data = new Stream();
      response.on("data", function (chunk) {
      response.on("end", function () {
      response.on("error", function (e) {

Size and path based on placeholder

You can have customizable image loader using the template's placeholder name.

opts.getImage = function (tagValue, tagName) {
  if (tagName === "logo")
    return fs.readFileSync(__dirname + "/logos/" + tagValue);

  return fs.readFileSync(__dirname + "/images/" + tagValue);

The same thing can be used to customize image size.

opts.getSize = function (img, tagValue, tagName) {
  if (tagName === "logo") return [100, 100];

  return [300, 300];

Size with angular-parser

You can also use angular expressions to set image sizes :

In your template, write :

{%image | size:200:100}

First argument is the width, second argument is the height.

In your code, you would write the following :

const expressions = require("angular-expressions");
expressions.filters.size = function (input, width, height) {
  return {
    data: input,
    size: [width, height],
function angularParser(tag) {
  const expr = expressions.compile(tag.replace(/’/g, "'"));
  return {
    get(scope) {
      return expr(scope);

opts.getImage = function (tagValue) {
  if (tagValue.size && {
    return base64DataURLToArrayBuffer(;
  return base64DataURLToArrayBuffer(tagValue);
opts.getSize = function (_, tagValue) {
  if (tagValue.size && {
    return tagValue.size;
  return [150, 150];

const doc = new Docxtemplater(zip, {
  modules: [new ImageModule(opts)],
  parser: angularParser,

Base64 include

You can use base64 images with the following code

function base64DataURLToArrayBuffer(dataURL) {
  const base64Regex = /^data:image\/(png|jpg|svg|svg\+xml);base64,/;
  if (!base64Regex.test(dataURL)) {
    return false;
  const stringBase64 = dataURL.replace(base64Regex, "");
  let binaryString;
  if (typeof window !== "undefined") {
    binaryString = window.atob(stringBase64);
  } else {
    binaryString = Buffer.from(stringBase64, "base64").toString("binary");
  const len = binaryString.length;
  const bytes = new Uint8Array(len);
  for (let i = 0; i < len; i++) {
    const ascii = binaryString.charCodeAt(i);
    bytes[i] = ascii;
  return bytes.buffer;
const imageOpts = {
  getImage(tag) {
    return base64DataURLToArrayBuffer(tag);
  getSize() {
    return [100, 100];
const doc = new Docxtemplater(zip, { modules: [new ImageModule(imageOpts)] });

Retrieve image from <canvas>

It is possible to retrieve image from a canvas value, by customizing the getImage option.

opts.getImage = function (tagValue, tagName) {
  var canvas = document.getElementById("myCanvas");
  var ctx = canvas.getContext("2d");
  ctx.arc(100, 75, 50, 0, 2 * Math.PI);
  return base64DataURLToArrayBuffer(canvas.toDataURL());

Note that you can change that function so that depending on the tagvalue, either the image is loaded from canvas or from a URL.

SVG support

SVGs can be added, but this format is only readable on newer Word version : Microsoft Word, PowerPoint, Outlook, and Excel on the Office 365 subscription.

See this article for details about this feature.

When SVG is not supported in your reader (libreoffice, google-docs, Word 2013), you will see the image "SVG unsupported" instead.

You can configure the image that is shown as a fallback if SVG is not supported, by defining the getSVGFallback method. You can use this method to convert the SVG to png so that all docx readers are able to see the SVG. In the below example, I use graphicsmagick to do the conversion : sudo apt-get install -y graphicsmagick

opts.getSVGFallback = function (svgFile, sizePixel) {
  const result = require("child_process").spawnSync(
    ["convert", "SVG:-", "-resize", sizePixel.join("x"), "PNG:-"],
      input: new Buffer(svgFile),
  if (result.status !== 0) {
    /* eslint-disable-next-line no-console */
        "result.stderr": result.stderr.toString(),
    throw new Error("Error while executing graphicsmagick");
  return new Buffer(result.stdout);

In the browser, you can use the following to transform the SVG's into PNG :

opts.getSVGFallback = function (svgFile, sizePixel) {
  function arrayBufferToString(buffer) {
    let binary = "";
    const bytes = new Uint8Array(buffer);
    const len = bytes.byteLength;
    for (let i = 0; i < len; i++) {
      binary += String.fromCharCode(bytes[i]);
    return binary;

  return new Promise(function (resolve, reject) {
    function svgUrlToPng(svgUrl) {
      const svgImage = document.createElement("img"); = "absolute"; = "-9999px";
      const width = sizePixel[0];
      const height = sizePixel[1];
      svgImage.width = width;
      svgImage.height = height;
      svgImage.onload = function () {
        const canvas = document.createElement("canvas");
        canvas.width = width;
        canvas.height = height;
        const canvasCtx = canvas.getContext("2d");
        canvasCtx.drawImage(svgImage, 0, 0, width, height);
        const imgData = canvas.toDataURL("image/png");
      svgImage.onerror = function () {
        reject(new Error("Could not transform svg to png"));
      svgImage.src = "data:image/svg+xml;utf8," + svgUrl;
        "<svg xmlns=''"


For docx, it is possible to add captions with the following code :

opts.getProps = function(img, tagValue, tagName) {
    // return null; // if you don't want to change the props for a given tagValue
    return {
        caption: {
            text: "My custom caption",
opts.getImage = function(tagValue, tagName) {
  return fs.readFileSync(tagValue);
opts.getSize = function(img, tagValue, tagName) {
  return [150, 150];
var imageModule = new ImageModule(opts);


For docx, it is possible to change the alignment of a block image with the following code :

opts.getProps = function(img, tagValue, tagName) {
    // return null; // if you don't want to change the props for a given tagValue
    return {
        align: "right",
opts.getImage = function(tagValue, tagName) {
  return fs.readFileSync(tagValue);
opts.getSize = function(img, tagValue, tagName) {
  return [150, 150];
var imageModule = new ImageModule(opts);


For the imagereplacer to work, the image tag: {%image} needs to be in its own <w:p>, so that means that you have to put a new line after and before the tag.

Powerpoint notice

If you put images in a box that also contains some other text (content, title, or even whitespace , you will get an error :

To fix this error, you have to create a box that contains the {%...} and only this text, no other whitespace nor content.

For example, the following template will fail, because the shape containing the text {%image} also contains "Some content" and "Other content".


For example, the following template will succeed, because there are 3 different shapes, and the shape containing the {%image} tag contains no other text. Note that the width/height of the generated image will be the same as the one from the shape.


Building in the browser

You can build a release for the browser with the following commands

npm install
npm run preversion

You will have build/imagemodule.js.

Max width and max height

It is quite likely that you would want to limit the width and the height of your images, to do this, you could use the following code in your getSize function

opts.getSize = function(img, tagValue, tagName) {
  console.log(tagValue, tagName);
  // img is the value that was returned by getImage
  // This is to limit the width and height of the resulting image
  const maxWidth = 1000;
  const maxHeight = 800;

  const sizeOf = require("image-size");
  const sizeObj = sizeOf(img);

  const aspectRatio = sizeObj.width / sizeObj.height;
  const widthRatio = sizeObj.width / maxWidth:
  const heightRatio = sizeObj.height / maxHeight
  if (widthRatio < 1 && heightRatio < 1) {
     // Do not scale up images that are smaller than maxWidth,maxHeight
     return [sizeObj.width, sizeOf.height];
  let finalWidth, finalHeight;
  if (widthRatio > heightRatio) {
     // Width will be equal to maxWidth because width is the most
     // "limiting"
     finalWidth = maxWidth;
     finalHeight = sizeObj.height / widthRatio;
  else {
      // Height will be equal to maxHeight because height is the most
      // "limiting"
      finalHeight = maxHeight;
      finalWidth = sizeObj.width / heightRatio;

  return [



Update to retrieve containerHeight and containerWidth for pptx textboxes and pptx tables.

For docx tables, containerHeight cannot be retrieved because the height depends on the rendering of the fonts and the content of the table, so it cannot be retrieved.


Don't fail when placing the {%image} tag inside a table element.


Bugfix to make Image replacement work in async mode (you need access to both modules image and xlsx)


Add support for ImageModule together with XLSXModule to insert images with {%image} (you need access to both modules)


Do not fail when using the tag {%image} on "generic" shapes, eg those defined in the slideLayout


  • Do not console.log errors, as they are now properly handled by docxtemplater in async mode with loops (with docxtemplater 3.17.7)

  • Avoid corruption on XLSX file when it contains images (the images would be removed by the document)


Use SEQ Figure instead of SEQ Illustration for Captions


Declare supportedFileTypes, which allows to use this module with the new docxtemplater constructor which was introduced in docxtemplater 3.17.


Better bugfix to remove unused images (works with other modules)


Bugfix No section found appeared :

  • when using document with tags inside properties (for Title, Subject, Keywords, …)
  • when using a document generated from onedrive (online office version)


Add getSVGFallback option to allow to convert the svg to png in JS


Bugfix when using image module together with pptx-subtemplate module, the images were removed


Bugfix to allow to have inline loop of inline images

Improve error message when putting block image inside inline loop


(docx) Add support for captions with module.getProps function.

(docx) Add support for aligning block images to the left or the right with module.getProps function.


Fix issue "No section found" when having an image in a footer


Add possibility to retrieve the containerWidth to be able to use 100% of the containerWidth for example

Add possibility to change deviceWidth and getDxaWidth to change the dpi


  • Bugfix : do not remove images inside vfill
  • Remove usage of new Buffer


Expect to have error when using centered image in a paragraph which contains other text.

When using centered: true option, images containing %% now will show up as normal images (uncentered).


Add part.extPx and part.offsetPx to be able to know the size of the placeholder in pptx in pixel unit.


Fix corruption when having centered image inside table and return no img


Change the way this.opts.centered works.

Before, you would have to write : {%image} for inline images and {%%image} for centered images, and if you used the centered:true option, you would only be able to write centered images (with any of {%image} or {%%image}). Now when you specify opts.centered : true, the standard behavior is just swapped ({%image} for centered images and {%%image} for inline images).

However, in the future, opts.centered : true will be removed and this means that you should rather just change the prefix, like this :

const imageModule = new ImageModule(options);
imageModule.prefix = {
  normal: "%%",
  centered: "%",

Also, this fixes a bug with SVG that were not shown when using "centered" images.


Bugfix for pptx. Before this release, if the document contained <a:extLst>, the error Images should be placed in new Text Boxes, that are not part of any slide layout was sometimes wrongfully thrown.


Bugfix in asyncmode, errors are now correctly thrown


Bugfix image module loops in async mode. Before this bugfix, images inside loops where sometimes always using the same image.

If you use the HTML module, you should update to 3.13.5 of the HTML module.


Bugfix SVG : async rendering should also work with base64 svgs

If you use the image module with the HTML module, please also update the HTML module to 3.14.4


Auto remove images that are no more needed when using slides module or when using a loop.

This makes the size of the generated docx smaller, and might make the rendering a little bit slower.


  • Update browser build to use XMLSerializer instead of xmldom

  • Use requiredAPIVersion


Make it possible to change prefix and normal prefix :

const imageModule = new ImageModule(options);
imageModule.prefix = {
  normal: ":image ",
  centered: ":centered ",


  • Move docxtemplater from devDependencies to dependencies

Explanation : On some versions of npm (notably 5.8.0), when having a package containing docxtemplater-image-module, the installation will generate a tree of node_modules that puts the module on a level where it has no access to docxtemplater. By explicitly asking it as a dependency, this issue is avoided.


  • Make module compatible with docxtemplater version 3.5 and below.

Explanation : Recently, the scopemanager API (internal API) has changed, this new version of the footnotes module makes the module work with both versions newer than 3.6 and older than 3.6 of docxtemplater.


Add SVG support (but this format is only readable on newer Word version : Microsoft Word, PowerPoint, Outlook, and Excel on the Office 365 subscription).


Add meta context argument to custom parser with information about the tag for each types of tags


  • Fix issue "size is not defined"


  • Add clearer error message if getSize returns float or not an array of two integers


  • Add fallback to calling nullGetter if getValue returns falsey value


  • Fix "Maximum call stack size exceeeded" when using huge arraybuffers


  • Fix corruption error because of duplicate docPr. The shown error is usually : HRESULT 0x80004005 Location: Part: /word/document.xml, Line: 0, Column: 0

  • Add async support (by returning a Promise in the getImage function).


  • Fix error in browser "Buffer is not defined"


  • Fix regression in 3.2.0 : It should work with Buffer type


  • Throw error if using unsupported filetype (SVG)

  • Throw error if using image in a default box ("Images should be placed in new Text Boxes, that are not part of any slide layout")


Mark package as private in package.json


Fix corruption when reusing multiple times the docPrId

Reuse Target when possible


Do not add relationship for files docProps/app.xml and docProps/core.xml


Fix unit tests


Files are no longer corrupted when using the option "center"


The image module now throws an error if the given size is invalid.


  • Breaking : The image module no longer swallows error thrown by options.getImage and options.getSize. It is the implementors responsibility to not throw any errors, or the error will be passed. You can return a falsy value in getImage to not render an image at all.


  • Fix issue with PPTX : Before, you had to add to your options : {fileType: "pptx"} in the module options passed as argument in the constructor of the module. Now, the fileType is retrieved from the main docxtemplater.


  • Add support for PPTX.
  • Add centering of images with {%%image} syntax


  • This version is compatible with docxtemplater 3.0.

Edgar Hipp

I'm the creator of docxtemplater. I work on making docxtemplater great since 2013.