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.
- function DownloadWT(formContext, entityTypeCode)
- {
-
- Xrm.Utility.showProgressIndicator("Exporting to Word");
- var filename= "Demo.docx"
- var templateType = 9940;
- var Query= Query = "?$select=documenttemplateid&$filter=name eq 'WORD TEMPLATE NAME'";
- var id = formContext.data.entity.getId();
- var globalContext = Xrm.Utility.getGlobalContext();
- var path = globalContext.getClientUrl() + "/_grid/print/print_data.aspx";
-
-
- 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;
- }
-
-
- 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 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 !!