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

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Dynamics CRM 2016 Online how to execute Report, generate PDF and email?

(0) ShareShare
ReportReport
Posted on by 1,505

Hi All,

I am using Dynamic CRM 2016 online. For quote, On approval, I want the system to generate a PDF of quote report, attach the PDF and email it to the Customer.

Better I would like, When approver, clicks on the approve button, the system should auto generate a PDF of quote report, attach the PDF and email it to the Customer, without any further input from the user. If its not possible, I may have to put button on quote form.

Thanks. and waiting for your valuable comments.

*This post is locked for comments

I have the same question (0)
  • Verified answer
    BharatPremji Profile Picture
    2,485 on at

    Hi,

    Not sure this will completely answer your question but I have done something similar in CRM 2015 online.  The code below generates a PDF from an SSRS report and attaches it to a Note on the Quote.  I have put the code on a button in the ribbon and called the runReportToPrint function:

    var reportName = "Invoice.rdl";  //Name of your invoice report
    var reportGuid = "16ACCA48-F2AC-E511-80FE-C4346BC576E8"; //GUID of your invoice report


    function runReportToPrint() {

    var invoicenumber = Xrm.Page.getAttribute("invoicenumber").getValue()
    if (invoicenumber != null) {
    invoicenumber = invoicenumber.substring(4, 9);
    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=" + invoicenumber + "&ContentDisposition=OnlyHtmlInline&Format=PDF";
    window.open(newPth, "_self");
    encodePdf(params);
    }
    else {
    alert("Invoice ID is Missing");
    }
    }

    function getReportingSession() {
    var recordId = Xrm.Page.data.entity.getId();
    recordId = recordId.replace('{', '').replace('}', '');

    var strParameterXML = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'><entity name='invoice'><all-attributes /><filter type='and'><condition attribute='invoiceid' operator='eq' value='" + recordId + "' /> </filter></entity></fetch>";
    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:CRM_invoice=" + strParameterXML);

    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(responseSession) {

    var retrieveEntityReq = new XMLHttpRequest();
    var pth = Xrm.Page.context.getClientUrl() + "/Reserved.ReportViewerWebControl.axd?ReportSession=" + responseSession[0] + "&Culture=1033&CultureOverrides=True&UICulture=1033&UICultureOverrides=True&ReportStack=1&ControlID=" + responseSession[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 && 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);
    createNote(bdy);
    }
    };

    retrieveEntityReq.send();
    }

    function createNote(data) {

    var note = {};

    var recordId = Xrm.Page.data.entity.getId();
    recordId = recordId.replace('{', '').replace('}', '');

    var invoicenumber = Xrm.Page.getAttribute("invoicenumber").getValue()
    invoicenumber = invoicenumber.substring(4, 9);

    var refInvoice = new Object();
    refInvoice.LogicalName = "invoice";
    refInvoice.Id = recordId;

    note.ObjectId = refInvoice;
    note.ObjectTypeCode = refInvoice.LogicalName;

    note.Subject = "Invoice: " + invoicenumber;
    note.MimeType = "application/pdf";
    note.DocumentBody = data;
    note.FileName = invoicenumber + ".pdf";

    XrmServiceToolkit.Rest.Create(
    note,
    "AnnotationSet",
    function (result) {
    //Alert user
    alert("Note Created");
    //Refresh data so user sees newly created note
    Xrm.Page.data.refresh(false);

    },
    function (error) {
    alert(error.message);
    },
    true
    );
    }

    You could use most of this code and change the createNote function to create an email record instead.

    Note: this code uses the XrmServiceToolkit library

    Hope that helps

    Bharat

  • Bhuvaneswary Rajasekaran Profile Picture
    405 on at

    Hi Aleem,

    you can use the Bharat's code for generating the pdf and creating attachment. Upon successful creation of attachment, update a dummy two option field to yes. Write a plugin on update of dummy two option field. Try to retrieve the latest attachment and write logic to send email. At the end update the dummy two option field to No. You can use action but you have to ensure that plugin is not triggered before attachment was created. 

    Thanks

    Bhuvi

  • ClixSol Profile Picture
    1,505 on at

    Hello Bharat's.

    Thanks for your response.

    i'm trying to implement it on Invoice and getting the error:

    "An error has occurred.

    Try this action again. If the problem continues, check the Microsoft Dynamics CRM Community for solutions or contact your organization's Microsoft Dynamics CRM Administrator. Finally, you can contact Microsoft Support. "

    Can you help to fix this.

    thanks

  • Suggested answer
    Community Member Profile Picture
    on at

    Hi Aleem,

    I have wrote a blog on this similar requirement.

    Try to follow my blog.

    crmpankaj.blogspot.in/.../send-pdf-file-as-attachment-in-mail.html

  • ClixSol Profile Picture
    1,505 on at

    Hello Bharat's,

    Is this solution feasible for Reports in MS CRM online?

    I could not get report session parameters.

    Please share your thoughts.

  • BharatPremji Profile Picture
    2,485 on at

    Hi Aleem,

    Yes, this code definitely works in CRM Online.

    Did you change these 2 variables to match the report name and GUID in your system:

    var reportName = "Invoice.rdl";  //Name of your invoice report

    var reportGuid = "16ACCA48-F2AC-E511-80FE-C4346BC576E8"; //GUID of your invoice report

    Also, what browser are you using, this works in IE but I have heard it may not work correctly in Chrome.

    Bharat

    PS, thanks Pankaj, your blog was my starting point

  • ClixSol Profile Picture
    1,505 on at

    Hi Bharat,

    Yes i'm trying in IE.

    The PDF attachment gets created but cannot be opened. The error message thrown is - Adobe Acrobat could not open "FileName.pdf" because it is either not a supported file type or because the file has been damaged.

    I am trying this on CRM 2016 Online. Any suggestions?

    When I debug the code I get responseBody given below for this code:

    var recordId = Xrm.Page.data.entity.getId();
    recordId = recordId.replace('{', '').replace('}', '');
    var strParameterXML = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'><entity name='invoice'><all-attributes /><filter type='and'><condition attribute='invoiceid' operator='eq' value='" + recordId + "' /> </filter></entity></fetch>";
    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:CRM_invoice=" + strParameterXML);
    var x = retrieveEntityReq.responseText.lastIndexOf("ReportSession=");
    var y = retrieveEntityReq.responseText.lastIndexOf("ControlID=");


    responseBody:

    <!DOCTYPE html>
    <html>
    <head>
    <script type='text/javascript'>
    window.location.href = '/_common/error/errorhandler
    .aspx?BackUri=https%3a%2f%2forganization.crm.dynamics.com%2fmain.aspx%3fetc%3d1090%26extraqs%3d%253fetc
    %253d1090%2526id%253d%25257b24B4AD0B-CE4C-E611-80FD-3863BB2E92C8%25257d%26pagemode%3diframe%26pagetype
    %3dentityrecord&ErrorCode=0x8004832C&Parm0=%0d%0a%0d%0a&Parm1=%28rsItemNotFound%29&RequestUri=%2fCRMReports
    %2frsviewer%2fQuirksReportViewer.aspx&user_lcid=1033';</script>
    </head>
    <body>
    </body>
    </html>

     

    I could not get report session parameters.

    Please share your thoughts.

    Thanks,

    Aleem

  • BharatPremji Profile Picture
    2,485 on at

    Hi Aleem,

    The problem may be with the way you have developed the report in Visual Studio

    Try creating a very simple Invoice Report with only a few fields, maybe something like this as your DataSource, note the use of enableprefiltering:

     

    <fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">

    <entity name="invoice" enableprefiltering="1">
    <attribute name="invoicenumber" />
    <attribute name="name" />
    <attribute name="totalamount" />
    <attribute name="customerid" />
    <attribute name="statuscode" />
    <attribute name="invoiceid" />
    <attribute name="createdon" />
    <attribute name="description" />
    <order attribute="name" descending="false" />
    </entity>
    </fetch>

     

    In your parameters section create a parameter called CRM_invoice.  Data Type should be Text 

    Add a fieds to the report and upload into CRM, change the report name and guid parameters to match this new report.  Then try running the code.

    I had a lot of problems initially thinking it was report session errors but it was actually the report itself that wasnt correct

    Bharat

  • Verified answer
    ClixSol Profile Picture
    1,505 on at

    Hi Bharat,

    Thank you very much for your suggestion.
    I create a simple Report.
    And change four variables in my system: 
    1. var reportName = "Invoice.rdl";  //Name of my invoice report
    2. var reportGuid = "fd140aaf-4df4-11dd-bd17-0019b9312238"; //GUID of my report

    3. var strParameterXML = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'><entity name='invoice'><all-attributes /><filter type='and'><condition attribute='invoiceid' operator='eq' value='" + recordId + "' /> </filter></entity></fetch>"; //Fetch Query of report

    4. CRM_invoice //Report Parameter Name

    It worked.

  • BharatPremji Profile Picture
    2,485 on at

    Excellent.

    You should now be able to build the report up slowly.

    If you want to add the Invoice line items, create a dataset with the following fetch statement (take out/add fields you need)

    <fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">

    <entity name="invoicedetail">

    <attribute name="productid" />

    <attribute name="productdescription" />

    <attribute name="priceperunit" />

    <attribute name="quantity" />

    <attribute name="uomid" />

    <attribute name="extendedamount" />

    <attribute name="isproductoverridden" />

    <attribute name="invoicedetailid" />

    <attribute name="actualdeliveryon" />

    <attribute name="tax" />

    <attribute name="description" />

    <link-entity name="invoice" from="invoiceid" to="invoiceid" alias="inv" enableprefiltering="1">

    </link-entity>

    </entity>

    </fetch>

    You can then simply add a table into the report and point it to this dataset

    Bharat

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…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans