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

Announcements

News and Announcements icon
Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Convert Rdl file into PDf format in button Click

(0) ShareShare
ReportReport
Posted on by 1,347

Hi,
How to generate "rdl" file into "pdf" from a custom ribbon button click event ,I know we can export a report to pdf format but the requirement is to directly attach pdf file in email to reduce the clicks.

*This post is locked for comments

I have the same question (0)
  • Suggested answer
    Mahendar Pal Profile Picture
    45,095 on at

    Hi,

    Did you check this threads, similar type of question is already answered here:

    community.dynamics.com/.../151236

    community.dynamics.com/.../205829

    Hope it will help you.

    Thanks

  • Iswarya Profile Picture
    1,347 on at

    Hi,

    Thanks for your reply, i referred those links, my problem is Email and pdf attachment creating successfully , when open attached pdf i got "Failed load Pdf Document" Error How to resolve this issue please help me to do this

  • Suggested answer
    gupta.ambar2009@gmail.com Profile Picture
    797 on at

    Please implement below code, its a working code for me

    function runReportToPrint(selectedRecords) {

       try {

           debugger

           var selectedid = null;

           var reportid = null;

           var req = new XMLHttpRequest();

           var reportName = "Invoice Report Detail";

           req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/reports?$select=reportid&$filter=filename eq '" + reportName + ".rdl'", true);

           req.setRequestHeader("OData-MaxVersion", "4.0");

           req.setRequestHeader("OData-Version", "4.0");

           req.setRequestHeader("Accept", "application/json");

           req.setRequestHeader("Content-Type", "application/json; charset=utf-8");

           req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");

           req.onreadystatechange = function () {

               if (this.readyState === 4) {

                   req.onreadystatechange = null;

                   if (this.status === 200) {

                       debugger;

                       var results = JSON.parse(this.response);

                       if (results != null) {

                           reportid = results.value[0]["reportid"];

                           //if (selectedRecords != null && selectedRecords.length > 0) {

                           //    for (var i = 0; i < selectedRecords.length; i++) {

                           //        selectedid = selectedRecords[i];

                           //        var params = getReportingSessionhomegrid(reportName, reportid, selectedid);

                           //        var newPth = Xrm.Page.context.getClientUrl() + "/Reserved.ReportViewerWebControl.axd?ReportSession=" + params[0] + "&Culture=1033&CultureOverrides=True&UICulture=1033&UICultureOverrides=True&ReportStack=1&ControlID=" + params[1] + "&OpType=Export&FileName=" + reportName + "&ContentDisposition=OnlyHtmlInline&Format=PDF";

                           //        setTimeout(function () { window.open(newPth, "_self"); }, 1000);

                           //    }

                           if (selectedRecords != null && selectedRecords.length == 1) {

                               selectedid = selectedRecords[0];

                               var params = getReportingSessionhomegrid(reportName, reportid, selectedid);

                               var newPth = Xrm.Page.context.getClientUrl() + "/Reserved.ReportViewerWebControl.axd?ReportSession=" + params[0] + "&Culture=1033&CultureOverrides=True&UICulture=1033&UICultureOverrides=True&ReportStack=1&ControlID=" + params[1] + "&OpType=Export&FileName=" + reportName + "&ContentDisposition=OnlyHtmlInline&Format=PDF";

                               setTimeout(function () { window.open(newPth, "_self"); }, 1000);

                           }

                           else if (selectedRecords != null && selectedRecords.length == 0) {

                               alert("Please select a record.");

                           }

                           else if (selectedRecords != null && selectedRecords.length > 1) {

                               alert("Please select only one record .");

                           }

                           else {

                               var params = getReportingSession(reportName, reportid);

                               var newPth = Xrm.Page.context.getClientUrl() + "/Reserved.ReportViewerWebControl.axd?ReportSession=" + params[0] + "&Culture=1033&CultureOverrides=True&UICulture=1033&UICultureOverrides=True&ReportStack=1&ControlID=" + params[1] + "&OpType=Export&FileName=" + reportName + "&ContentDisposition=OnlyHtmlInline&Format=PDF";

                               window.open(newPth, "_self");

                           }

                       } else {

                           Xrm.Utility.alertDialog(this.statusText);

                       }

                   }

               }

           };

           req.send();

       } catch (ex) {

           throw ex;

       }

    }

    function getReportingSession(reportName, reportGuid) {

       var selectedIds = Xrm.Page.data.entity.getId();

       selectedIds = selectedIds.replace('{', '');

       selectedIds = selectedIds.replace('}', '');

       var pth = Xrm.Page.context.getClientUrl() + "/CRMReports/rsviewer/QuirksReportViewer.aspx";

       var retrieveEntityReq = new XMLHttpRequest();

       retrieveEntityReq.open("POST", pth, false);

       retrieveEntityReq.setRequestHeader("Accept", "*/*");

       retrieveEntityReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

       retrieveEntityReq.send("id=%7B" + reportGuid + "%7D&uniquename=" + Xrm.Page.context.getOrgUniqueName() + "&iscustomreport=true&reportnameonsrs=&reportName=" + reportName + "&isScheduledReport=false&p:invoiceid=" + selectedIds);

       var x = retrieveEntityReq.responseText.lastIndexOf("ReportSession=");

       var y = retrieveEntityReq.responseText.lastIndexOf("ControlID=");

       var ret = new Array();

       ret[0] = retrieveEntityReq.responseText.substr(x + 14, 24);

       ret[1] = retrieveEntityReq.responseText.substr(x + 10, 32);

       return ret;

    }

    function getReportingSessionhomegrid(reportName, reportGuid, selectedrecordid) {

       // var selectedIds = Xrm.Page.data.entity.getId();

       selectedrecordid = selectedrecordid.replace('{', '');

       selectedrecordid = selectedrecordid.replace('}', '');

       var pth = Xrm.Page.context.getClientUrl() + "/CRMReports/rsviewer/QuirksReportViewer.aspx";

       var retrieveEntityReq = new XMLHttpRequest();

       retrieveEntityReq.open("POST", pth, false);

       retrieveEntityReq.setRequestHeader("Accept", "*/*");

       retrieveEntityReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

       retrieveEntityReq.send("id=%7B" + reportGuid + "%7D&uniquename=" + Xrm.Page.context.getOrgUniqueName() + "&iscustomreport=true&reportnameonsrs=&reportName=" + reportName + "&isScheduledReport=false&p:invoiceid=" + selectedrecordid);

       var x = retrieveEntityReq.responseText.lastIndexOf("ReportSession=");

       var y = retrieveEntityReq.responseText.lastIndexOf("ControlID=");

       var ret = new Array();

       ret[0] = retrieveEntityReq.responseText.substr(x + 14, 24);

       ret[1] = retrieveEntityReq.responseText.substr(x + 10, 32);

       return ret;

    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    function runReportToPrintReceipt() {

       try {

           debugger;

           var reportName;

           var chequeamount = Xrm.Page.getAttribute("cm_chequeamount").getValue();

           if (chequeamount != null) {

               reportName = "Receipt_Cheque";

           }

           else {

               reportName = "Receipt_Cash";

           }

           var selectedid = null;

           var reportid = null;

           var req = new XMLHttpRequest();

           req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/reports()?$select=reportid&$filter=filename eq '" + reportName + ".rdl'", true);

           req.setRequestHeader("OData-MaxVersion", "4.0");

           req.setRequestHeader("OData-Version", "4.0");

           req.setRequestHeader("Accept", "application/json");

           req.setRequestHeader("Content-Type", "application/json; charset=utf-8");

           req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");

           req.onreadystatechange = function () {

               if (this.readyState === 4) {

                   req.onreadystatechange = null;

                   if (this.status === 200) {

                       debugger;

                       var results = JSON.parse(this.response);

                       if (results != null) {

                           //reportid = "EEE6E34A-5F1B-E711-8102-5065F38B06F1";

                           var reportid = results.value[0]["reportid"];

                           var params = getReportingSessionReceipt(reportName, reportid);

                           var newPth = Xrm.Page.context.getClientUrl() + "/Reserved.ReportViewerWebControl.axd?ReportSession=" + params[0] + "&Culture=1033&CultureOverrides=True&UICulture=1033&UICultureOverrides=True&ReportStack=1&ControlID=" + params[1] + "&OpType=Export&FileName=" + reportName + "&ContentDisposition=OnlyHtmlInline&Format=PDF";

                           window.open(newPth, "_self");

                       }

                   } else {

                       Xrm.Utility.alertDialog(this.statusText);

                   }

               }

           };

           req.send();

       } catch (ex) {

           throw ex;

       }

    }

    function getReportingSessionReceipt(reportName, reportGuid) {

       var selectedIds = Xrm.Page.data.entity.getId();

       selectedIds = selectedIds.replace('{', '');

       selectedIds = selectedIds.replace('}', '');

       var pth = Xrm.Page.context.getClientUrl() + "/CRMReports/rsviewer/QuirksReportViewer.aspx";

       var retrieveEntityReq = new XMLHttpRequest();

       retrieveEntityReq.open("POST", pth, false);

       retrieveEntityReq.setRequestHeader("Accept", "*/*");

       retrieveEntityReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

       retrieveEntityReq.send("id=%7B" + reportGuid + "%7D&uniquename=" + Xrm.Page.context.getOrgUniqueName() + "&iscustomreport=true&reportnameonsrs=&reportName=" + reportName + "&isScheduledReport=false&p:ReceiptID=" + selectedIds);

       var x = retrieveEntityReq.responseText.lastIndexOf("ReportSession=");

       var y = retrieveEntityReq.responseText.lastIndexOf("ControlID=");

       var ret = new Array();

       ret[0] = retrieveEntityReq.responseText.substr(x + 14, 24);

       ret[1] = retrieveEntityReq.responseText.substr(x + 10, 32);

       return ret;

    }

  • Iswarya Profile Picture
    1,347 on at

    Hi,

    thanks for your response. i tried your code but again the same thing happen "Couldn’t open PDF"

    My Code is below Please check and help me

    var reportName = "QuoteWithHeader"; //Please specify your report name.

    var reportId = null;

    var fileName = "PDF01"; //Please specify a file which you want to save.

    var fromFieldId = null;

    var fromFieldEntityName = null;

    var toFieldId = null;

    var toFieldEntityName = null;

    var emailId = null;

    //This function is need to be called from action side e.g. Ribbon button click.

    function EmailReport() {

       debugger;

       //This function does not work in add mode of form.

       var type = Xrm.Page.ui.getFormType();

       if (type != 1) {

           GetIds(); // Set ids in global variables.

           CreateEmail(); //Create Email

       }

    }

    //Gets the fromFieldId and toFieldEntityName used to set Email To & From fields

    function GetIds() {

       debugger; 

       //test user id

       fromFieldId = "9F2C0324-3E8B-45DC-A326-990DB225AC5C";

       fromFieldEntityName = "systemuser";//Please specify entity name for which you have specified above Guid. Most probably it's systemuser.

       toFieldId = "1BB88677-DB82-E711-8123-5065F38CF781";

       toFieldEntityName = "contact";//Please specify entity name for which you have specified above Guid.

    }

    //Create Email and link it with Order as Reagrding field

    function CreateEmail() {

       debugger;

       var id = Xrm.Page.data.entity.getId();

       id = id.replace('{', "");

       id = id.replace('}', "");

       var entityLogicalName = Xrm.Page.data.entity.getEntityName();

       var regardingObjectId = new Sdk.EntityReference(entityLogicalName, id);

       var email = new Sdk.Entity("email");

       email.addAttribute(new Sdk.String("subject", "Your Booking"));

       email.addAttribute(new Sdk.Lookup("regardingobjectid", regardingObjectId));

       var fromParties = PrepareActivityParty(fromFieldId, fromFieldEntityName);

       email.addAttribute(new Sdk.PartyList("from", fromParties));

       var toParties = PrepareActivityParty(toFieldId, toFieldEntityName);

       email.addAttribute(new Sdk.PartyList("to", toParties));

       Sdk.Async.create(email, EmailCallBack, function (error) { alert(error.message); });

       GetReportId();

    }

    //This method get entity's id and logical name and return entitycollection of it.

    function PrepareActivityParty(partyId, partyEntityName) {

       debugger;

       var activityParty = new Sdk.Entity("activityparty");

       activityParty.addAttribute(new Sdk.Lookup("partyid", new Sdk.EntityReference(partyEntityName, partyId)));

       var activityParties = new Sdk.EntityCollection();

       activityParties.addEntity(activityParty);

       return activityParties;

    }

    // Email Call Back function

    function EmailCallBack(result) {

       debugger;

       emailId = result;

     //  GetReportId();

    }

    //This method will get the reportId based on a report name

    function GetReportId() {

       debugger; 

       var context = Xrm.Page.context;

       var serverUrl = context.getClientUrl();

       var ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";

       var retrieveResult = new XMLHttpRequest();

       retrieveResult.open("GET", ODataPath + "/ReportSet?$select=Name,ReportId&$filter=Name eq'" + reportName + "'", false);

       retrieveResult.setRequestHeader("Accept", "application/json");

       retrieveResult.setRequestHeader("Content-Type", "application/json; charset=utf-8?");

       retrieveResult.send();

       if (retrieveResult.readyState == 4 /* complete */) {

           if (retrieveResult.status == 200) {

               var retrieved = this.parent.JSON.parse(retrieveResult.responseText).d;

               var Result = retrieved.results;

               if (typeof Result !== "undefined") {

                   reportId = Result[0].ReportId;

                   var params = GetReportingSession(reportName, reportId);

                   EncodePdf(params);

               }

           }

       }

    }

    //Gets the report contents

    function GetReportingSession(rName, rId) {

       debugger;  

       var orgUniqueName = Xrm.Page.context.getOrgUniqueName();

       var selectedIds = Xrm.Page.data.entity.getId();

       selectedIds = selectedIds.replace('{', '');

       selectedIds = selectedIds.replace('}', '');

       var pth = Xrm.Page.context.getClientUrl() + "/CRMReports/rsviewer/QuirksReportViewer.aspx";

       var retrieveEntityReq = new XMLHttpRequest();

       retrieveEntityReq.open("POST", pth, false);

       retrieveEntityReq.setRequestHeader("Accept", "*/*");

       retrieveEntityReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

       retrieveEntityReq.send("id=%7B" + rId + "%7D&uniquename=" + orgUniqueName + "&iscustomreport=true&reportnameonsrs=&reportName=" + rName + "&isScheduledReport=false&p:quoteid=" + selectedIds);

       var x = retrieveEntityReq.responseText.lastIndexOf("ReportSession=");

       var y = retrieveEntityReq.responseText.lastIndexOf("ControlID=");

       var ret = new Array();

       ret[0] = retrieveEntityReq.responseText.substr(x + 14, 24);

       ret[1] = retrieveEntityReq.responseText.substr(x + 10, 32);

       return ret;

     

    }

    function EncodePdf(params) {

       debugger;

       var retrieveEntityReq = new XMLHttpRequest();

       var pth = Xrm.Page.context.getClientUrl() + "/Reserved.ReportViewerWebControl.axd?ReportSession=" + params[0] + "&Culture=1033&CultureOverrides=True&UICulture=1033&UICultureOverrides=True&ReportStack=1&ControlID=" + params[1] + "&OpType=Export&FileName=Public&ContentDisposition=OnlyHtmlInline&Format=PDF";

       retrieveEntityReq.open('GET', pth, true);

       retrieveEntityReq.setRequestHeader("Accept", "*/*");

       retrieveEntityReq.responseType = "arraybuffer";

       retrieveEntityReq.onload = function (e) {

           if (this.status == 200) {

               var uInt8Array = new Uint8Array(this.response);

               var base64 = Encode64(uInt8Array);

               CreateEmailAttachment(base64);

           }

       };

       retrieveEntityReq.send();

    }

    var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    function Encode64(input) {

       debugger;

       var output = new StringMaker();

       var chr1, chr2, chr3;

       var enc1, enc2, enc3, enc4;

       var i = 0;

       while (i < input.length) {

           chr1 = input[i++];

           chr2 = input[i++];

           chr3 = input[i++];

           enc1 = chr1 >> 2;

           enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);

           enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);

           enc4 = chr3 & 63;

           if (isNaN(chr2)) {

               enc3 = enc4 = 64;

           } else if (isNaN(chr3)) {

               enc4 = 64;

           }

           output.append(keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4));

       }

       return output.toString();

    }

    var StringMaker = function () {

       this.parts = [];

       this.length = 0;

       this.append = function (s) {

           this.parts.push(s);

           this.length += s.length;

       }

       this.prepend = function (s) {

           this.parts.unshift(s);

           this.length += s.length;

       }

       this.toString = function () {

           return this.parts.join('');

       }

    }

    //Create attachment for the created email

    function CreateEmailAttachment(encodedPdf) {

       debugger;

       //Get order number to name a newly created PDF report

       var QuoteNumber = Xrm.Page.getAttribute("quotenumber");

       var emailEntityReference = new Sdk.EntityReference("email", emailId);

       var newFileName = fileName + ".pdf";

       if (QuoteNumber != null)

           newFileName = fileName + QuoteNumber.getValue() + ".pdf";

       var activitymimeattachment = new Sdk.Entity("activitymimeattachment");

       activitymimeattachment.addAttribute(new Sdk.String("body", encodedPdf));

       activitymimeattachment.addAttribute(new Sdk.String("subject", "File Attachment"));

       activitymimeattachment.addAttribute(new Sdk.String("objecttypecode", "email"));

       activitymimeattachment.addAttribute(new Sdk.String("filename", newFileName));

       activitymimeattachment.addAttribute(new Sdk.Lookup("objectid", emailEntityReference));

       activitymimeattachment.addAttribute(new Sdk.String("mimetype", "application/pdf"));

       Sdk.Async.create(activitymimeattachment, ActivityMimeAttachmentCallBack, function (error) { alert(error.message); });

    }

    //ActivityMimeAttachment CallBack function

    function ActivityMimeAttachmentCallBack(result) {

       debugger;

       Xrm.Utility.openEntityForm("email", emailId);

    }

  • gupta.ambar2009@gmail.com Profile Picture
    797 on at

    Hello Iswarya ,

    I can see you have done code changes in function developed by you ,and its hard to understand the issue without debugging.

    what i suggest you ,please use my code which i have posted and just rename the rdl file name and check. and "selectedRecords" is  a parameter passed in the function which you pass from ribbon button using crm parameter  in java script function  

  • Iswarya Profile Picture
    1,347 on at

    Hi,

    I tried your code , I just implement this code for quote entity and give parameter as

    Crm Parameter = SelectedControlSelectedItemIds

    value  = SelectedControlSelectedItemIds

    like below screenshot

    pdfparameter.png

    when debugging the code , it satisfy this line and throw alert, please tell me what record I have to select

    else if (selectedRecords != null && selectedRecords.length == 0) {

    alert("Please select a record.");

    }

     

     below I paste entire code :

     

    function EmailReport(selectedRecords) {

     

       try {

     

           debugger

     

           var selectedid = null;

     

           var reportid = null;

     

           var req = new XMLHttpRequest();

     

           var reportName = "QuoteWithHeader";

     

           var context = Xrm.Page.context;

           var serverUrl = context.getClientUrl();

           var ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";

           var retrieveResult = new XMLHttpRequest();

     

     

           retrieveResult.open("GET", ODataPath + "/ReportSet?$select=Name,ReportId&$filter=Name eq'" + reportName + "'", false);

     

           retrieveResult.setRequestHeader("Accept", "application/json");

           retrieveResult.setRequestHeader("Content-Type", "application/json; charset=utf-8?");

           retrieveResult.send();

     

           if (retrieveResult.readyState == 4 /* complete */) {

               if (retrieveResult.status == 200) {

                   var retrieved = this.parent.JSON.parse(retrieveResult.responseText).d;

                   var Result = retrieved.results;

                   if (typeof Result !== "undefined") {

     

                       reportid = Result[0].ReportId;

                      

     

                           if (selectedRecords != null && selectedRecords.length == 1) {

     

                               selectedid = selectedRecords[0];

     

                               var params = getReportingSessionhomegrid(reportName, reportid, selectedid);

     

                               var newPth = Xrm.Page.context.getClientUrl() + "/Reserved.ReportViewerWebControl.axd?ReportSession=" + params[0] + "&Culture=1033&CultureOverrides=True&UICulture=1033&UICultureOverrides=True&ReportStack=1&ControlID=" + params[1] + "&OpType=Export&FileName=" + reportName + "&ContentDisposition=OnlyHtmlInline&Format=PDF";

     

                               setTimeout(function () { window.open(newPth, "_self"); }, 1000);

     

                           }

     

                     

         else if (selectedRecords != null && selectedRecords.length == 0) {

     

                               alert("Please select a record.");

     

                           }

     

                           else if (selectedRecords != null && selectedRecords.length > 1) {

     

                               alert("Please select only one record .");

     

                           }

     

                           else {

     

                               var params = getReportingSession(reportName, reportid);

     

                               var newPth = Xrm.Page.context.getClientUrl() + "/Reserved.ReportViewerWebControl.axd?ReportSession=" + params[0] + "&Culture=1033&CultureOverrides=True&UICulture=1033&UICultureOverrides=True&ReportStack=1&ControlID=" + params[1] + "&OpType=Export&FileName=" + reportName + "&ContentDisposition=OnlyHtmlInline&Format=PDF";

     

                               window.open(newPth, "_self");

     

                           }

     

                       } else {

     

                           Xrm.Utility.alertDialog(this.statusText);

     

                       }

     

                   }

     

               }

     

       

     

       } catch (ex) {

     

           throw ex;

     

       }

     

    }

     

    function getReportingSession(reportName, reportGuid) {

     

       var selectedIds = Xrm.Page.data.entity.getId();

     

       selectedIds = selectedIds.replace('{', '');

     

       selectedIds = selectedIds.replace('}', '');

     

       var pth = Xrm.Page.context.getClientUrl() + "/CRMReports/rsviewer/QuirksReportViewer.aspx";

     

       var retrieveEntityReq = new XMLHttpRequest();

     

       retrieveEntityReq.open("POST", pth, false);

     

       retrieveEntityReq.setRequestHeader("Accept", "*/*");

     

       retrieveEntityReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

     

       retrieveEntityReq.send("id=%7B" + reportGuid + "%7D&uniquename=" + Xrm.Page.context.getOrgUniqueName() + "&iscustomreport=true&reportnameonsrs=&reportName=" + reportName + "&isScheduledReport=false&p:quoteid=" + selectedIds);

     

       var x = retrieveEntityReq.responseText.lastIndexOf("ReportSession=");

     

       var y = retrieveEntityReq.responseText.lastIndexOf("ControlID=");

     

       var ret = new Array();

     

       ret[0] = retrieveEntityReq.responseText.substr(x + 14, 24);

     

       ret[1] = retrieveEntityReq.responseText.substr(x + 10, 32);

     

       return ret;

     

    }

     

    function getReportingSessionhomegrid(reportName, reportGuid, selectedrecordid) {

     

       // var selectedIds = Xrm.Page.data.entity.getId();

     

       selectedrecordid = selectedrecordid.replace('{', '');

     

       selectedrecordid = selectedrecordid.replace('}', '');

     

       var pth = Xrm.Page.context.getClientUrl() + "/CRMReports/rsviewer/QuirksReportViewer.aspx";

     

       var retrieveEntityReq = new XMLHttpRequest();

     

       retrieveEntityReq.open("POST", pth, false);

     

       retrieveEntityReq.setRequestHeader("Accept", "*/*");

     

       retrieveEntityReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

     

       retrieveEntityReq.send("id=%7B" + reportGuid + "%7D&uniquename=" + Xrm.Page.context.getOrgUniqueName() + "&iscustomreport=true&reportnameonsrs=&reportName=" + reportName + "&isScheduledReport=false&p:quoteid=" + selectedrecordid);

     

       var x = retrieveEntityReq.responseText.lastIndexOf("ReportSession=");

     

       var y = retrieveEntityReq.responseText.lastIndexOf("ControlID=");

     

       var ret = new Array();

     

       ret[0] = retrieveEntityReq.responseText.substr(x + 14, 24);

     

       ret[1] = retrieveEntityReq.responseText.substr(x + 10, 32);

     

       return ret;

     

    }

     

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

     

    function runReportToPrintReceipt() {

     

       try {

     

           debugger;

     

           var QuoteWithHeader;

     

           //var chequeamount = Xrm.Page.getAttribute("cm_chequeamount").getValue();

     

           //if (chequeamount != null) {

     

           //   reportName = "Receipt_Cheque";

     

           //}

     

           //else {

     

           //   reportName = "Receipt_Cash";

     

           //}

     

           var selectedid = null;

     

           var reportid = null;

     

           var req = new XMLHttpRequest();

     

           req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/reports()?$select=reportid&$filter=name eq '" + reportName + ".rdl'", true);

     

           req.setRequestHeader("OData-MaxVersion", "4.0");

     

           req.setRequestHeader("OData-Version", "4.0");

     

           req.setRequestHeader("Accept", "application/json");

     

           req.setRequestHeader("Content-Type", "application/json; charset=utf-8");

     

           req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");

     

           req.onreadystatechange = function () {

     

               if (this.readyState === 4) {

     

                   req.onreadystatechange = null;

     

                   if (this.status === 200) {

     

                       debugger;

     

                       var results = JSON.parse(this.response);

     

                       if (results != null) {

     

                           //reportid = "EEE6E34A-5F1B-E711-8102-5065F38B06F1";

     

                           var reportid = results.value[0]["reportid"];

     

                         var params = getReportingSessionReceipt(reportName, reportid);

     

                           var newPth = Xrm.Page.context.getClientUrl() + "/Reserved.ReportViewerWebControl.axd?ReportSession=" + params[0] + "&Culture=1033&CultureOverrides=True&UICulture=1033&UICultureOverrides=True&ReportStack=1&ControlID=" + params[1] + "&OpType=Export&FileName=" + reportName + "&ContentDisposition=OnlyHtmlInline&Format=PDF";

     

                           window.open(newPth, "_self");

     

                       }

     

                   } else {

     

                       Xrm.Utility.alertDialog(this.statusText);

     

                   }

     

               }

     

           };

     

           req.send();

     

       } catch (ex) {

     

           throw ex;

     

       }

     

    }

     

    function getReportingSessionReceipt(reportName, reportGuid) {

     

       var selectedIds = Xrm.Page.data.entity.getId();

     

       selectedIds = selectedIds.replace('{', '');

     

       selectedIds = selectedIds.replace('}', '');

     

       var pth = Xrm.Page.context.getClientUrl() + "/CRMReports/rsviewer/QuirksReportViewer.aspx";

     

       var retrieveEntityReq = new XMLHttpRequest();

     

       retrieveEntityReq.open("POST", pth, false);

     

       retrieveEntityReq.setRequestHeader("Accept", "*/*");

     

       retrieveEntityReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

     

       retrieveEntityReq.send("id=%7B" + reportGuid + "%7D&uniquename=" + Xrm.Page.context.getOrgUniqueName() + "&iscustomreport=true&reportnameonsrs=&reportName=" + reportName + "&isScheduledReport=false&p:ReceiptID=" + selectedIds);

     

       var x = retrieveEntityReq.responseText.lastIndexOf("ReportSession=");

     

       var y = retrieveEntityReq.responseText.lastIndexOf("ControlID=");

     

       var ret = new Array();

     

       ret[0] = retrieveEntityReq.responseText.substr(x + 14, 24);

     

       ret[1] = retrieveEntityReq.responseText.substr(x + 10, 32);

     

       return ret;

     

    }




     

     

  • Suggested answer
    gupta.ambar2009@gmail.com Profile Picture
    797 on at

    ohh i got your point .

    it will work if you call this function from home grid ,since from there you can select one or more value .

    if you are implementing this from form then use simply  Xrm.Page.data.entity.getId()  and do not  pass any parameter.  

  • Verified answer
    gupta.ambar2009@gmail.com Profile Picture
    797 on at

    below is the code ,if you are calling from from .

    function runReportToPrint() {

       try {

           debugger

           var selectedid = null;

           var reportid = null;

           var req = new XMLHttpRequest();

           var reportName = "Invoice Report Detail";

           req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/reports?$select=reportid&$filter=filename eq '" + reportName + ".rdl'", true);

           req.setRequestHeader("OData-MaxVersion", "4.0");

           req.setRequestHeader("OData-Version", "4.0");

           req.setRequestHeader("Accept", "application/json");

           req.setRequestHeader("Content-Type", "application/json; charset=utf-8");

           req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");

           req.onreadystatechange = function () {

               if (this.readyState === 4) {

                   req.onreadystatechange = null;

                   if (this.status === 200) {

                       debugger;

                       var results = JSON.parse(this.response);

                       if (results != null) {

                           reportid = results.value[0]["reportid"];

                               var params = getReportingSession(reportName, reportid);

                               var newPth = Xrm.Page.context.getClientUrl() + "/Reserved.ReportViewerWebControl.axd?ReportSession=" + params[0] + "&Culture=1033&CultureOverrides=True&UICulture=1033&UICultureOverrides=True&ReportStack=1&ControlID=" + params[1] + "&OpType=Export&FileName=" + reportName + "&ContentDisposition=OnlyHtmlInline&Format=PDF";

                               window.open(newPth, "_self");

                       } else {

                           Xrm.Utility.alertDialog(this.statusText);

                       }

                   }

               }

           };

           req.send();

       } catch (ex) {

           throw ex;

       }

    }

    function getReportingSession(reportName, reportGuid) {

       var selectedIds = Xrm.Page.data.entity.getId();

       selectedIds = selectedIds.replace('{', '');

       selectedIds = selectedIds.replace('}', '');

       var pth = Xrm.Page.context.getClientUrl() + "/CRMReports/rsviewer/QuirksReportViewer.aspx";

       var retrieveEntityReq = new XMLHttpRequest();

       retrieveEntityReq.open("POST", pth, false);

       retrieveEntityReq.setRequestHeader("Accept", "*/*");

       retrieveEntityReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

       retrieveEntityReq.send("id=%7B" + reportGuid + "%7D&uniquename=" + Xrm.Page.context.getOrgUniqueName() + "&iscustomreport=true&reportnameonsrs=&reportName=" + reportName + "&isScheduledReport=false&p:invoiceid=" + selectedIds);

       var x = retrieveEntityReq.responseText.lastIndexOf("ReportSession=");

       var y = retrieveEntityReq.responseText.lastIndexOf("ControlID=");

       var ret = new Array();

       ret[0] = retrieveEntityReq.responseText.substr(x + 14, 24);

       ret[1] = retrieveEntityReq.responseText.substr(x + 10, 32);

       return ret;

    }

  • Iswarya Profile Picture
    1,347 on at

    Hi,

    thanks for your suggestion, when debug I got this path

    var newPth ="https://crmdemosep.crm8.dynamics.com/Reserved.ReportViewerWebControl.axd?ReportSession=l><html><head><script ty&Culture=1033&CultureOverrides=True&UICulture=1033&UICultureOverrides=True&ReportStack=1&ControlID= html><html><head><script type='&OpType=Export&FileName=QuoteWithHeader&ContentDisposition=OnlyHtmlInline&Format=PDF"

     window.open(newPth, "_self"); => the new window not open.(ribbon button click I just pass  this " window.open("https://www.google.com");" for testing purpose its working. but when pass our newPth not open window)

     

     

     

     

  • Iswarya Profile Picture
    1,347 on at

    Hi,

    when I debug

    var x = retrieveEntityReq.responseText.lastIndexOf("ReportSession=");

    var y = retrieveEntityReq.responseText.lastIndexOf("ControlID=");

    responseText Value is

    "<!DOCTYPE html><html><head><script type='text/javascript'>window.location.href = '/_common/error/errorhandler.aspx?BackUri=https%3a%2f%2fcrmdemosep.crm8.dynamics.com%2fform%2fClientApiWrapper.aspx%3fver%3d1839998229&ErrorCode=0x8004832C&Parm0=%0d%0a%0d%0a&Parm1=&RequestUri=%2fCRMReports%2frsviewer%2fQuirksReportViewer.aspx&user_lcid=1033';</script></head><body></body></html>"

    I could not get report session parameters.

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

Introducing the 2026 Season 1 community Super Users

Congratulations to our 2026 Super Stars!

Meet the Microsoft Dynamics 365 Contact Center Champions

We are thrilled to have these Champions in our Community!

Congratulations to the April Top 10 Community Leaders

These are the community rock stars!

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
ScottDurow Profile Picture

ScottDurow 2

#2
GJones Profile Picture

GJones 1

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans