Download Word Document Template Using JavaScript - Dynamics 365 CE

Requirement


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

Solution

 
We create a flyout button similar to existing word template flyout and hide the out of the box flyout button. While working on the code, I found similar code here which helped me for downloading files but the file was corrupted after download so I am sharing code which worked for me.
 
You can refer to my other article to add Flyout in Dynamics 365 CE
  1. function DownloadWT(formContext, entityTypeCode)  
  2. {  
  3.     //display notification  
  4.     Xrm.Utility.showProgressIndicator("Exporting to Word");  
  5.     var filename= "Demo.docx"//replace file name here  
  6.     var templateType = 9940;  
  7.     var Query=  Query = "?$select=documenttemplateid&$filter=name eq 'WORD TEMPLATE NAME'";//replace it accordingly  
  8.     var id = formContext.data.entity.getId();  
  9.     var globalContext = Xrm.Utility.getGlobalContext();  
  10.     var path = globalContext.getClientUrl() + "/_grid/print/print_data.aspx";  
  11.    
  12.     //query template record based name  
  13. Xrm.WebApi.online.retrieveMultipleRecords("documenttemplate", Query).then(  
  14.                 function success(results) {  
  15.                     if (results.entities.length > 0) {  
  16.                         var wordTemplateId = results.entities[0]["documenttemplateid"];  
  17.                         var request = "exportType=MergeWordTemplate&selectedRecords=" + encodeURIComponent(JSON.stringify(id)) +  
  18.                             "&associatedentitytypecode=" + entityTypeCode + "&TemplateId=" + wordTemplateId + "&TemplateType=" + templateType;  
  19.                    
  20.                         var req = new XMLHttpRequest();  
  21.                         req.open("POST", path, true);  
  22.                         req.responseType = "arraybuffer";  
  23.                         req.setRequestHeader("Accept""text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");  
  24.                         req.setRequestHeader("Accept-Language""en-US,en;q=0.8");  
  25.                         req.setRequestHeader("Content-Type""application/x-www-form-urlencoded");  
  26.                         req.onreadystatechange = function () {  
  27.                             if (this.readyState == 4) {/* complete */  
  28.                                 req.onreadystatechange = null;  
  29.                                 if (this.status >= 200 && this.status <= 299) {  
  30.                                     var mimetype = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";  
  31.                                     var blob = new Blob([req.response], { type: mimetype });  
  32.                                     var downloadurl = URL.createObjectURL(blob);  
  33.                                     if (navigator.msSaveOrOpenBlob) {  
  34.                                         navigator.msSaveOrOpenBlob(blob, filename);  
  35.                                         return;  
  36.                                     }  
  37.                                       
  38.                                     //download file  
  39.                                     var a = document.createElement("a");  
  40.                                     document.body.appendChild(a);  
  41.                                     a.style = "display: none";  
  42.                                     a.href = downloadurl;  
  43.                                     a.download = filename;  
  44.                                     a.click();  
  45.                                     URL.revokeObjectURL(downloadurl);  
  46.                                     Xrm.Utility.closeProgressIndicator();  
  47.                                  }  
  48.                                 else {  
  49.                                     Console.Write("An Error occurred generating the word document." + err.message);  
  50.                                 }  
  51.                             }  
  52.                         };  
  53.                         req.send(request);  
  54.                     }  
  55.                 },  
  56.                 function (error) {  
  57.                    Console.Write(error.message);  
  58.                 });  
  59. }  
In the above code I am passing two parameters from ribbon command bar:
  • formContext – This is get form contact to access form control, we can pass PrimaryControl as CrmParameter from button command.
  • 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. Now when we will click on the button where we have associated this code will get progress indicator like below and after some time it will download template for us.
 
 
Hope it will help someone!

Keep learning, Keep sharing !!


Similar Articles
HIMBAP
We are expert in Microsoft Power Platform.