Download Word Document Template using JavaScript- Dynamics 365 CE

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

Solution
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 = formContext.data.entity.getId();
    var globalContext = Xrm.Utility.getGlobalContext();
    var path = globalContext.getClientUrl() + "/_grid/print/print_data.aspx";

    //query template record based name
Xrm.WebApi.online.retrieveMultipleRecords("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();
                        req.open("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);
                                        return;
                                    }
                                   
                                    //download file
                                    var a = document.createElement("a");
                                    document.body.appendChild(a);
                                    a.style = "display: none";
                                    a.href = downloadurl;
                                    a.download = filename;
                                    a.click();
                                    URL.revokeObjectURL(downloadurl);
                                    Xrm.Utility.closeProgressIndicator();
                                 }
                                else {
                                    Console.Write("An Error occurred generating the word document." + err.message);
                                }
                            }
                        };
                        req.send(request);
                    }
                },
                function (error) {
                   Console.Write(error.message);
                });
}

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 !!

One thought on “Download Word Document Template using JavaScript- Dynamics 365 CE

Leave a Reply