Today I will show how to "Generate a PDF file of an open record in just one click." The image below will give you a clear understanding about what we are going to discuss.



The idea to solve this problem was simple: First develop a SSRS Report and save it as PDF. Here are the steps required to follow to solve this requirement:
  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 are done with SSRS Report and Button we will create a Java script file and the code will be,

Method to get the SessionID and ControlID for the SSRSReport
  1. getReportingSession: function()
  2. {
  3. var selectedIds = Xrm.Page.data.entity.getId();
  4. var reportName = "NameofReport.rdl";
  5. var reportGuid = getReportGuidByName("NameofReport"); //OR Report GUID - Replace with your report GUID
  6. var pth = Xrm.Page.context.getClientUrl() + "/CRMReports/rsviewer/QuirksReportViewer.aspx";
  7. var retrieveEntityReq = new XMLHttpRequest();
  8. retrieveEntityReq.open("POST", pth, false);
  9. retrieveEntityReq.setRequestHeader("Accept", "*/*");
  10. retrieveEntityReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  11. retrieveEntityReq.send("id=%7B" + reportGuid + "%7D&uniquename=" + Xrm.Page.context.getOrgUniqueName() + "&iscustomreport=true&reportnameonsrs=&reportName=" + reportName + "&isScheduledReport=false&p:parameterNamespecified in ssrs report=" + selectedIds);
  12. var x = retrieveEntityReq.responseText.lastIndexOf("ReportSession=");
  13. var y = retrieveEntityReq.responseText.lastIndexOf("ControlID=");
  14. var ret = new Array();
  15. ret[0] = retrieveEntityReq.responseText.substr(x + 14, 24);
  16. ret[1] = retrieveEntityReq.responseText.substr(x + 10, 32);
  17. return ret;
  18. }
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
  1. runReportToPrint: function()
  2. {
  3. var params = getReportingSession();
  4. 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";
  5. window.open(newPth, "_self");
  6. }
Hope this would help you in your custom development. If you have any Query related to the code please mention in comments section below.