web
You’re offline. This is a read only version of the page.
close
Skip to main content
Community site session details

Community site session details

Session Id :
Customer experience | Sales, Customer Insights,...
Suggested answer

Merge Word Templates on Export

(0) ShareShare
ReportReport
Posted on by 10

I am working on a project to export Word templates.  I have about two dozen custom templates and I was able to use the example coding from this thread (https://stackoverflow.com/questions/44525991/dynamics-crm-365-downloading-a-word-document-template-via-a-button-on-the-ribb) to build an interface to download one template at a time when the user checks a box associated with each template.  The user now would like to combine selected templates into a single Word file upon export.  Is possible to extend the export method (var formdata = "exportType=MergeWordTemplate&selectedRecords=" + encodeURIComponent(JSON.stringify(IDS)) + "&associatedentitytypecode=" + currentEntityTypeCode + "&TemplateId=" + wordTemplateId + "&TemplateType=" + templateType;) to include multiple templates?  I've tried a number of different ways without success.  I was also not able to find this exportType method defined anywhere.  Any help is appreciated.

My current code:

// JavaScript Document
this.ExecuteWordMerge = function (executionContext, wordtemplateid, entitytypecodeint, templatetype, fieldforfilename, filenameoverride, fieldname) {
var formContext = executionContext.getFormContext(); // get formContext
var FieldName = fieldname;
var filecheck = formContext.getAttribute(FieldName).getValue();
if (filecheck == 1) {
try{
Xrm.Page.ui.clearFormNotification("worderror");
var globalContext = Xrm.Utility.getGlobalContext();
var clientUrl = globalContext.getClientUrl();
// Xrm.page is deprecated Xrm.Page.context.getClientUrl()
var funcpath = clientUrl + "/_grid/print/print_data.aspx";
var IDS = formContext.data.entity.getId(); // get the entity id for the current record
if (typeof IDS !== "object") {
var tids = IDS;
IDS = new Array();
IDS.push(tids);
}
var wordTemplateId = wordtemplateid;//"f1f7b994-543b-e711-8106-c4346bac2908" test data;
var currentEntityTypeCode = entitytypecodeint;//"10063" test data;
var templateType = (templatetype || 9940); //9940 is global and 9941 is personal
var fieldForFileName = (fieldforfilename || "");
var formdata = "exportType=MergeWordTemplate&selectedRecords=" + encodeURIComponent(JSON.stringify(IDS)) +
"&associatedentitytypecode=" + currentEntityTypeCode + "&TemplateId=" + wordTemplateId + "&TemplateType=" + templateType;
var req = new XMLHttpRequest();
req.open("POST", funcpath, 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) {//200 range okay
var mimetype = (2 === 2) ? "application/vnd.openxmlformats-officedocument.wordprocessingml.document" : "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
var blob = new Blob([req.response], { type: mimetype });
var fileNameTemplate = req.getResponseHeader('content-disposition').split('filename=')[1].replace(/'/g, "");
var dloadurl = URL.createObjectURL(blob);
var filename = (fieldForFileName !== "" && formContext.getAttribute(fieldForFileName) !== null && formContext.getAttribute(fieldForFileName).getValue() !== "") ?
formContext.getAttribute(fieldForFileName).getValue() : fileNameTemplate;
filename = filenameoverride || filename;
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = dloadurl;
a.download = filename;
a.click();
URL.revokeObjectURL(dloadurl);
//window.location = dloadurl;//we can use just this instead of creating an anchor but we don't get to the name the file
}
else {
formContext.ui.setFormNotification("An Error occurred generating the word document, please contact support if the issue persists,code: " + this.status, "ERROR", "worderror");
}
}

};
req.send(formdata);
}
catch (err) {
formContext.ui.setFormNotification("An Error occurred generating the word document, please contact support if the issue persists. " + err.message, "ERROR", "worderror");
}
}
}

Reply
I have the same question (0)
  • Suggested answer
    Michael J Thomas Profile Picture
    10 on at
    RE: Merge Word Templates on Export

    That was not quite the problem that I was trying to solve.  I needed to export multiple documents at the same time.  I ended up building an array of the document information and looping over the array to export docs.  I ran into an issue with the XMLHTTPRequest only exporting the last document in the array multiple times.  I found this post to insert an iterating function inside the array using the array designation and it solved the problem.

    stackoverflow.com/.../how-to-handle-simultaneous-javascript-xmlhttprequests

    So my code basically ended up as follows:

    // JavaScript Document
    this.ExportWord = function (primaryControl) 
    {
      var formContext = primaryControl; // get formContext
      var currentEntityTypeCode = "10037";
      var templateType = "9940";
      Xrm.Page.ui.clearFormNotification("worderror");
      var globalContext = Xrm.Utility.getGlobalContext();
        var IDS = formContext.data.entity.getId(); // get the entity id for the current record
      if (typeof IDS !== "object") 
      {
         var tids = IDS;
         IDS = new Array();
         IDS.push(tids);
       }
       //Define the Fields for Each Document Template
    	var DocListArray = [];
    	var filecheck = formContext.getAttribute("new_applicationpackage").getValue();//Determine if Document has been checked by user
    	if (filecheck == 1) 
    	{
    	  DocListArray.push({wordtemplateid:"6134f68d-6e1b-ea11-a811-000d3a31cf04", fieldname:"new_applicationpackage", fieldforfilename: "Application Package.docx", filenameoverride: "Application Package.docx"});
    	}
    	filecheck = formContext.getAttribute("new_docclosinginstructions").getValue();//Determine if Document has been checked by user
    	if (filecheck == 1) 
    	{
    	  DocListArray.push({wordtemplateid:"3167f43a-1dea-e911-a860-000d3a372186", fieldname:"new_docclosinginstructions", fieldforfilename: "Closing Instructions - Standard.docx", filenameoverride: "Closing Instructions - Standard.docx"});
    	}
    	var len = DocListArray.length;
    	var req = new Array();
    for (var i = 0; i < len; i  ) 
    	{ 
           try
    	   {
             var wordTemplateId = DocListArray[i].wordtemplateid;
             var fieldForFileName = DocListArray[i].fieldforfilename;
             var clientUrl = globalContext.getClientUrl();
      		 var funcpath = clientUrl   "/_grid/print/print_data.aspx";
    		 var formdata = "exportType=MergeWordTemplate&selectedRecords="   encodeURIComponent(JSON.stringify(IDS))   "&associatedentitytypecode="   currentEntityTypeCode   "&TemplateId="   wordTemplateId   "&TemplateType="   templateType;
    		 (function(i) {
    			 req[i] = new XMLHttpRequest();
    			 req[i].open("POST", funcpath, true);
    			 req[i].responseType = "arraybuffer";
    			 req[i].setRequestHeader("Accept", "text/html,application/xhtml xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
    			 req[i].setRequestHeader("Accept-Language", "en-US,en;q=0.8");
    			 req[i].setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    			 req[i].onreadystatechange = function (oEvent) 
    			   {
    				 if (req[i].readyState == 4) 
    				   {/* complete */
    					 //req.onreadystatechange = null;
    					 if (req[i].status >= 200 && req[i].status <= 299) 
    					   {//200 range okay
    						 var mimetype = (2 === 2) ? "application/vnd.openxmlformats-officedocument.wordprocessingml.document" : "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    						 var blob = new Blob([req[i].response], { type: mimetype });
    						 var fileNameTemplate = req[i].getResponseHeader('content-disposition').split('filename=')[1].replace(/'/g, "");
    						 var dloadurl = URL.createObjectURL(blob);
    						 //var filename = (fieldForFileName !== "" && fieldForFileName !== null && fieldForFileName !== "") ? fieldForFileName : fileNameTemplate;
    						 filename = DocListArray[i].filenameoverride;
    						 var a = document.createElement("a");
    						 document.body.appendChild(a);
    						 a.style = "display: none";
    						 a.href = dloadurl;
    						 a.download = filename;
    						 a.click();
    						 URL.revokeObjectURL(dloadurl);
    						 //window.location = dloadurl;//we can use just this instead of creating an anchor but we don't get to the name the file
    					   }
    					 else 
    					   {
    						 formContext.ui.setFormNotification("An Error occurred generating the word document, please contact support if the issue persists,code: "   this.status, "ERROR", "worderror");
    					   }
    					}
    				};
    				req[i].send(formdata);
    		     })(i);
            }
            catch (err) {
                formContext.ui.setFormNotification("An Error occurred generating the word document, please contact support if the issue persists. "   err.message, "ERROR", "worderror");
            }		
          }
        }

    Thanks for the help!

  • ashish12 Profile Picture
    3,079 on at
    RE: Merge Word Templates on Export

    stackoverflow.com/.../dynamics-crm-365-downloading-a-word-document-template-via-a-button-on-the-ribb

  • Community Member Profile Picture
    on at
    RE: Merge Word Templates on Export

    ok, I think that impossible, or you can search deeply about this issue, good luck for your search and if you get it, please share it with us :)

  • Michael J Thomas Profile Picture
    10 on at
    RE: Merge Word Templates on Export

    Thanks Ossama.  I have reviewed that thread and a couple of similar re-postings using that method.  I have my program working and am able to export a single Word template without issue using a slightly modified version of that code.  The customer wants to enhance the process by exporting multiple templates into a single Word file.  They have about 20 custom templates and export anywhere from one to all 20 given a particular situation.  I can iterate the code above to export multiple templates as single files, but I can't find a way to merge them into a single file.  

    I'm trying to find the basis for the code line:

    var formdata = "exportType=MergeWordTemplate&selectedRecords=" + encodeURIComponent(JSON.stringify(IDS)) +

    "&associatedentitytypecode=" + currentEntityTypeCode + "&TemplateId=" + wordTemplateId + "&TemplateType=" + templateType;

    I can't find anything describing this in order to see if I can include multiple template definitions - or if there is some other method to merge the documents.

    Thanks for the help.

  • Suggested answer
    Community Member Profile Picture
    on at
    RE: Merge Word Templates on Export

    See  this thread:

    stackoverflow.com/.../dynamics-crm-365-downloading-a-word-document-template-via-a-button-on-the-ribb

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Andrés Arias – Community Spotlight

We are honored to recognize Andrés Arias as our Community Spotlight honoree for…

Leaderboard > Customer experience | Sales, Customer Insights, CRM

#1
Daniyal Khaleel Profile Picture

Daniyal Khaleel 147

#2
DAnny3211 Profile Picture

DAnny3211 134

#3
Abhilash Warrier Profile Picture

Abhilash Warrier 70 Super User 2025 Season 2

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans