// This function gets the reporting session.
function getReportingSession(){
var selectedIds = Xrm.Page.data.entity.getId();
var reportName = "NameofReport.rdl";
var reportGuid = "00000000-0000-0000-0000-000000000000"// Replace with your report GUID
var pth = Xrm.Page.context.getClientUrl() + "/CRMReports/rsviewer/QuirksReportViewer.aspx";
//Note: In version 9.0, use reportviewer.aspx in place of QuirksReportViewer.aspx with.
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;
}
// This function encodes the PDF.
function encodePdf(ret){
var ret = getReportingSession();
var retrieveEntityReq = new XMLHttpRequest();
retrieveEntityReq.arguments=this.arguments;
var pth = window.parent.Xrm.Page.context.getClientUrl() + "/Reserved.ReportViewerWebControl.axd?ReportSession=" + ret[0] + "&Culture=1033&CultureOverrides=True&UICulture=1033&UICultureOverrides=True&ReportStack=1&ControlID=" + ret[1] + "&OpType=Export&FileName=Public&ContentDisposition=OnlyHtmlInline&Format=PDF";
retrieveEntityReq.open("GET", pth, true);
retrieveEntityReq.setRequestHeader("Accept", "*/*");
retrieveEntityReq.responseType = "arraybuffer";
retrieveEntityReq.onreadystatechange = function () {
if (retrieveEntityReq.readyState == 4){
if(retrieveEntityReq.status == 200) {
var binary = "";
var bytes = new Uint8Array(this.response);
for (var i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i]);
}
var bdy = btoa(binary);
createNoteWithAttachment(bdy,this.arguments);
}
}
};
retrieveEntityReq.send();
}
//Here this function attach the report as pdf in the existing task id.
function createNoteWithAttachment(bdy){
var annotation = new Object();
var taskid = "00000000-0000-0000-0000-000000000000" //Input the task id for which you want to create the notes as pdf attachment.
annotation.ObjectId = {
Id: propertyBag.taskid,
LogicalName: "task"
};
annotation.Subject = "Test Subject";
annotation.FileName = "Test File Name";+".pdf"
annotation.DocumentBody = bdy;
annotation.MimeType = "application/pdf";
SDK.REST.createRecord(annotation, "Annotation", function(result) {
var newEntityId = result.AnnotationId;
}, function(error) {
Xrm.Utility.alertDialog(error.message);
});
}