{"id":4090,"date":"2021-02-17T11:24:08","date_gmt":"2021-02-17T11:24:08","guid":{"rendered":"https:\/\/himbap.com\/blog\/?p=4090"},"modified":"2021-02-17T11:24:08","modified_gmt":"2021-02-17T11:24:08","slug":"download-word-document-template-using-javascript-dynamics-365-ce","status":"publish","type":"post","link":"https:\/\/himbap.com\/blog\/?p=4090","title":{"rendered":"Download Word Document Template using JavaScript- Dynamics 365 CE"},"content":{"rendered":"<p><strong>Requirement<\/strong><br \/>\nWe 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.<\/p>\n<p><strong>Solution<\/strong><br \/>\nWe create a flyout button similar to existing word template flyout and hide out of the box flyout button. While working code, I found <a href=\"https:\/\/stackoverflow.com\/questions\/44525991\/dynamics-crm-365-downloading-a-word-document-template-via-a-button-on-the-ribb\">similar code here which helped me<\/a> for downloading file but the file was corrupted after download so I am sharing code which worked for me.  <\/p>\n<p><a href=\"https:\/\/himbap.com\/blog\/?p=4092\">You can refer our earlier post for creating flyout button and passing parameters.<\/a><\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nfunction DownloadWT(formContext, entityTypeCode)\r\n{\r\n    \/\/display notification\r\n    Xrm.Utility.showProgressIndicator(&quot;Exporting to Word&quot;);\r\n    var filename= &quot;Demo.docx&quot;\/\/replace file name here\r\n    var templateType = 9940;\r\n    var Query=  Query = &quot;?$select=documenttemplateid&amp;$filter=name eq 'WORD TEMPLATE NAME'&quot;;\/\/replace it accordingly\r\n    var id = formContext.data.entity.getId();\r\n    var globalContext = Xrm.Utility.getGlobalContext();\r\n    var path = globalContext.getClientUrl() + &quot;\/_grid\/print\/print_data.aspx&quot;;\r\n\r\n    \/\/query template record based name\r\nXrm.WebApi.online.retrieveMultipleRecords(&quot;documenttemplate&quot;, Query).then(\r\n                function success(results) {\r\n                    if (results.entities.length &gt; 0) {\r\n                        var wordTemplateId = results.entities[0][&quot;documenttemplateid&quot;];\r\n                        var request = &quot;exportType=MergeWordTemplate&amp;selectedRecords=&quot; + encodeURIComponent(JSON.stringify(id)) +\r\n                            &quot;&amp;associatedentitytypecode=&quot; + entityTypeCode + &quot;&amp;TemplateId=&quot; + wordTemplateId + &quot;&amp;TemplateType=&quot; + templateType;\r\n                \r\n                        var req = new XMLHttpRequest();\r\n                        req.open(&quot;POST&quot;, path, true);\r\n                        req.responseType = &quot;arraybuffer&quot;;\r\n                        req.setRequestHeader(&quot;Accept&quot;, &quot;text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8&quot;);\r\n                        req.setRequestHeader(&quot;Accept-Language&quot;, &quot;en-US,en;q=0.8&quot;);\r\n                        req.setRequestHeader(&quot;Content-Type&quot;, &quot;application\/x-www-form-urlencoded&quot;);\r\n                        req.onreadystatechange = function () {\r\n                            if (this.readyState == 4) {\/* complete *\/\r\n                                req.onreadystatechange = null;\r\n                                if (this.status &gt;= 200 &amp;&amp; this.status &lt;= 299) {\r\n                                    var mimetype = &quot;application\/vnd.openxmlformats-officedocument.wordprocessingml.document&quot;;\r\n                                    var blob = new Blob([req.response], { type: mimetype });\r\n                                    var downloadurl = URL.createObjectURL(blob);\r\n                                    if (navigator.msSaveOrOpenBlob) {\r\n                                        navigator.msSaveOrOpenBlob(blob, filename);\r\n                                        return;\r\n                                    }\r\n                                   \r\n                                    \/\/download file\r\n                                    var a = document.createElement(&quot;a&quot;);\r\n                                    document.body.appendChild(a);\r\n                                    a.style = &quot;display: none&quot;;\r\n                                    a.href = downloadurl;\r\n                                    a.download = filename;\r\n                                    a.click();\r\n                                    URL.revokeObjectURL(downloadurl);\r\n                                    Xrm.Utility.closeProgressIndicator();\r\n                                 }\r\n                                else {\r\n                                    Console.Write(&quot;An Error occurred generating the word document.&quot; + err.message);\r\n                                }\r\n                            }\r\n                        };\r\n                        req.send(request);\r\n                    }\r\n                },\r\n                function (error) {\r\n                   Console.Write(error.message);\r\n                });\r\n}\r\n<\/pre>\n<p>In above code I am passing two parameter from ribbon command bar:<br \/>\n1. <strong>formContext <\/strong>&#8211; This is get form contact to access form control, we can pass <strong>PrimaryControl <\/strong>as CrmParameter from button command.<br \/>\n2. <strong>entityTypeCode <\/strong>&#8211; This parameter is for the entity code, we can get it CrmParameter &#8211;<strong>PrimaryEntityTypeCode<\/strong>.<\/p>\n<p>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.<\/p>\n<p>Hope it will help someone!<br \/>\n<strong>Keep learning, Keep sharing !!<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>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&#8230; <a href=\"https:\/\/himbap.com\/blog\/?p=4090\">Read more &raquo;<\/a><\/p>\n","protected":false},"author":1,"featured_media":4110,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[21,402,522],"tags":[866,871,868,867,869,870],"_links":{"self":[{"href":"https:\/\/himbap.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/4090"}],"collection":[{"href":"https:\/\/himbap.com\/blog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/himbap.com\/blog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/himbap.com\/blog\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/himbap.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=4090"}],"version-history":[{"count":7,"href":"https:\/\/himbap.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/4090\/revisions"}],"predecessor-version":[{"id":4359,"href":"https:\/\/himbap.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/4090\/revisions\/4359"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/himbap.com\/blog\/index.php?rest_route=\/wp\/v2\/media\/4110"}],"wp:attachment":[{"href":"https:\/\/himbap.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=4090"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/himbap.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=4090"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/himbap.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=4090"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}