Wednesday 6 January 2016

Generate PDF File using java script in Microsoft Dynamics CRM 2015 online in just 1 click .

Hi All,
Today I Back with my New requirement to "Generate a PDF file of an open record in Just 1 Click "
The Image Below will give you the clear understanding what was real requirement was.

To solve this requirement we need to follow some steps :-

1. You need to create an SSRS Report for your Record by passing "RecordId" as parameter.
2. Get the ReportSession and ControlId for the called report.
3. Open the Report as a PDF Format.

After the SSRs Report has been Added in CRM Instance. You need to add a Button on Form Ribbon.

Once we done with SSRs Report and Button we will create a  java script file and code will be

Method to get the SessionID and ControlID for the SSRSReport getReportingSession: function () {
        var selectedIds = Xrm.Page.data.entity.getId();
        var reportName = "NameofReport.rdl";
        var reportGuid = getReportGuidByName("NameofReport");   //OR Report GUID - Replace with your report GUID

        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:parameterNamespecified in ssrs report=" + 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;
    }
**Replace the Value which is specified with the Red Color in the code.

After we have received the Session Array we will call a method which will download the PDF file to our Local drive. Code is here.
Method to Download PDF. runReportToPrint: function () {       

        var params = getReportingSession();

        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=public&ContentDisposition=OnlyHtmlInline&Format=PDF";

        window.open(newPth, "_self");
    }
Hope this would help you in your custom development!!!
If you have any Query related the code!! Please leave the Comment!!!