Demo
Readme
Changelog
Releases RSS Feed
Compatibility : nodejs and browser

Summary (version 3.4.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.

README

This version is only compatible with docxtemplater version 3

Here is a compatibility table :

image-module docxtemplater
version 3.1.0 version 3.1.0
version 1.0.4 version 2.1.5
version 1.0.0 version 2.0.0

Installation:

You will need docxtemplater npm install docxtemplater

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

Usage

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

For example :

  • from base64 data
  • from the filesystem
  • from a url like : https://docxtemplater.com/xt-pro-white.png
  • from an Amazon S3 stored image

Your docx should contain the text: {%image}

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 JSZip(content);
var docx = new Docxtemplater()
    .attachModule(imageModule)
    .loadZip(zip)
    .setData({ image: 'examples/image.png' })
    .render();

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

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

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

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

            // FOR IMAGE COMING FROM A URL (IF TAGVALUE IS AN ADRESS) :
            // 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);
                    reject(e);
                }
            });
        }

        var imageModule = new ImageModule(opts);

        var zip = new JSZip(content);
        var doc = new docxtemplater()
            .loadZip(zip)
            .attachModule(imageModule)
            .compile();

        doc.resolveData({image:'examples/image.png'}).then(function() {
            console.log('ready');
            doc.render();
            var out = doc.getZip().generate({
                type:"blob",
                mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
            });
            saveAs(out, "generated.docx");
        })
    });
    </script>
</html>

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 :

{%myImage}

and your data:

{
    "myImage":'sampleImage.png'
}

tagValue will be equal to "sampleImage.png", tagName will be equal to "myImage" and 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');
   sizeObj = sizeOf(img);
   console.log(sizeObj);
   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

Async support

It is possible to get images asynchronously by returning a Promise in the getImage function and use the docxtemplater async api : http://docxtemplater.readthedocs.io/en/latest/async.html

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 JSZip = require("jszip");

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

const data = { image: "https://docxtemplater.com/xt-pro.png" };

const opts = {};
opts.getImage = function(tagValue, tagName) {
    console.log(tagValue, tagName);
    // tagValue is "https://docxtemplater.com/xt-pro-white.png" and tagName is "image"
    return new Promise(function(resolve, reject) {
        getHttpData(tagValue, function(err, data) {
            if (err) {
                return reject(err);
            }
            resolve(data);
        });
    });
};

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 ration
    const sizeOf = require("image-size");
    const sizeObj = sizeOf(img);
    console.log(sizeObj);
    const forceWidth = 600;
    const ratio = forceWidth / sizeObj.width;
    return [
        forceWidth,
        // calculate height taking into account aspect ratio
        sizeObj.height * ratio,
    ];
};

const imageModule = new ImageModule(opts);

const zip = new JSZip(content);
const doc = new DocxTemplater()
    .loadZip(zip)
    .attachModule(imageModule)
    .compile();

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

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

function getHttpData(url, callback) {
    https
        .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) {
                data.push(chunk);
            });
            response.on("end", function() {
                callback(null, data.read());
            });
            response.on("error", function(e) {
                callback(e);
            });
        })
        .end();
}

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];
};

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 = new Buffer(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];
    },
};
doc.attachModule(new ImageModule(imageOpts));

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 https://support.office.com/en-us/article/edit-svg-images-in-microsoft-office-2016-69f29d39-194a-4072-8c35-dbe5e7ea528c for details about this feature

Notice

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 is one of the default boxes (content, title, …) , you will get following error :

Images should be placed in new Text Boxes, that are not part of any slide layout

To fix this error, you have to create a new smaller box that contains the {%...} tag.

For example, the following template will fail

Fail

For example, the following template will succeed

Succeed

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.

CHANGELOG

3.4.3

Bugfix in asyncmode, errors are now correctly thrown

3.4.2

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.

3.4.1

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

3.4.0

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.

3.3.4

  • Update browser build to use XMLSerializer instead of xmldom

  • Use requiredAPIVersion

3.3.3

Make it possible to change prefix and normal prefix :

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

3.3.2

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

3.3.1

  • Make module compatible with docxtemplater version 3.5 and below.

Explanation : Recently, the scopemananger 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.

3.3.0

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

3.2.8

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

3.2.7

  • Fix issue "size is not defined"

3.2.6

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

3.2.5

  • Add fallback to calling nullGetter if getValue returns falsey value

3.2.4

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

3.2.3

  • 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).

3.2.2

  • Fix error in browser "Buffer is not defined"

3.2.1

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

3.2.0

  • 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")

3.1.6

Mark package as private in package.json

3.1.5

Fix corruption when reusing multiple times the docPrId

Reuse Target when possible

3.1.4

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

3.1.3

Fix unit tests

3.1.2

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

3.1.1

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

3.1.0

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

3.0.2

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

3.0.1

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

3.0.0

  • This version is compatible with docxtemplater 3.0.

Edgar Hipp

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