Hello Power Addicts, welcome back to my blog. Today I am going to share a JavScript function which you can readily use it on event in your app to download a pre-populated Word Document Template available in your environment with the selected record details. There are lots of articles available to achieve this task. However two main reasons why I am sharing my own version of the solution are because:

  • The downloaded word document was corrupted and hence not usable.
  • Solutions which leverage Power Automate Flows involved manual mapping of all the fields in the template with the required fields which overwhelmed me with the whole process.

Here is the code snippet:

// pass PrimaryControl as CrmParameter for formContext parameter
//pass PrimaryEntityTypeCode as CrmParameter for entityTypeCode parameter
function DownloadDocumentTemplate(formContext, entityTypeCode) {
    //display notification
    Xrm.Utility.showProgressIndicator("Downloading");
    var filename = "Save As File Name.docx" /*the template will be downloaded and saved with this name. Replace this with the desired file name*/
    var templateType = 9940;
    var Query = "?$select=documenttemplateid&$filter=name eq 'My Document Template'"; /*This is the name of the Word Document Template available in the CRM which is to be downloaded. 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=%5B%22" + id + "%22%5D&associatedentitytypecode=" + entityTypeCode + "&TemplateId=" + wordTemplateId + "&TemplateType=" + templateType;
                console.log(request);
                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) {
                        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);
                            var a = document.createElement("a");
                            document.body.appendChild(a);
                            if (navigator.msSaveOrOpenBlob) {
                                navigator.msSaveOrOpenBlob(blob, filename);
                                return;
                            } else {
                                a.href = downloadurl;
                                a.download = filename;
                                a.click();
                            }
                            Xrm.Utility.closeProgressIndicator();
                        }
                        else {
                            Console.Write("An Error occurred exporting the word document." + err.message);
                        }
                    }
                };
                req.send(request);
            }
        },
        function (error) {
            Console.Write(error.message);
        });
}

Hope you find this helpful!