Download Word Document Template using JavaScript- Dynamics 365 CE

We got one requirement where we wanted to download Word Document based on the word template after validating some conditions. I am going to share sample code which can be used to download word document based on the template name.

We create a flyout button similar to existing word template flyout and hide out of the box flyout button. While working code, I found similar code here which helped me for downloading file but the file was corrupted after download so I am sharing code which worked for me.

You can refer our earlier post for creating flyout button and passing parameters.

function DownloadWT(formContext, entityTypeCode)
    //display notification
    Xrm.Utility.showProgressIndicator("Exporting to Word");
    var filename= "Demo.docx"//replace file name here
    var templateType = 9940;
    var Query=  Query = "?$select=documenttemplateid&$filter=name eq 'WORD TEMPLATE NAME'";//replace it accordingly
    var id =;
    var globalContext = Xrm.Utility.getGlobalContext();
    var path = globalContext.getClientUrl() + "/_grid/print/print_data.aspx";

    //query template record based name"documenttemplate", Query).then(
                function success(results) {
                    if (results.entities.length > 0) {
                        var wordTemplateId = results.entities[0]["documenttemplateid"];
                        var request = "exportType=MergeWordTemplate&selectedRecords=" + encodeURIComponent(JSON.stringify(id)) +
                            "&associatedentitytypecode=" + entityTypeCode + "&TemplateId=" + wordTemplateId + "&TemplateType=" + templateType;
                        var req = new XMLHttpRequest();
              "POST", path, true);
                        req.responseType = "arraybuffer";
                        req.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
                        req.setRequestHeader("Accept-Language", "en-US,en;q=0.8");
                        req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                        req.onreadystatechange = function () {
                            if (this.readyState == 4) {/* complete */
                                req.onreadystatechange = null;
                                if (this.status >= 200 && this.status <= 299) {
                                    var mimetype = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                                    var blob = new Blob([req.response], { type: mimetype });
                                    var downloadurl = URL.createObjectURL(blob);
                                    if (navigator.msSaveOrOpenBlob) {
                                        navigator.msSaveOrOpenBlob(blob, filename);
                                    //download file
                                    var a = document.createElement("a");
                           = "display: none";
                                    a.href = downloadurl;
                           = filename;
                                else {
                                    Console.Write("An Error occurred generating the word document." + err.message);
                function (error) {

In above code I am passing two parameter from ribbon command bar:
1. formContext – This is get form contact to access form control, we can pass PrimaryControl as CrmParameter from button command.
2. entityTypeCode – This parameter is for the entity code, we can get it CrmParameter –PrimaryEntityTypeCode.

We can pass these parameter in the Java Script action for our button. After getting these parameter we can query template based on the name and download it using above code.

Hope it will help someone!
Keep learning, Keep sharing !!

3 thoughts on “Download Word Document Template using JavaScript- Dynamics 365 CE

  1. Satish Srinivas

    i still get the corrupted msg. i did add a query part for the template to get the one that is activated as mine had a few more in draft status. but not sure why this is happening post wave 2


Leave a Reply