Search code examples
javascriptjquerydatatablecrystal-reports

How to use jquery datatable custom button to export crystal report pdf


Exporting Crystal Reports to PDF is working fine if that is done via form submission to the controller method, but not working when the method is called from a jquery datatable custom button. Please go through my codes and help how to download the pdf by clicking a jquery datatable custom button.

Controller method:

public ActionResult ExportToPDF(string p1, string p2, string p3, string p4)
    {
        List<ViewModels.SomeVM> someVMs = DBTasks.GetSomeVMs(p1, p2, p3, p4);

        ReportDocument rd = new ReportDocument();
        rd.Load(Path.Combine(Server.MapPath("~/Reports"), "Something.rpt"));
        rd.SetDataSource(someVMs);
        //rd.SetParameterValue("@p1", p1);
        //rd.SetParameterValue("@p2", p2);
        //rd.SetParameterValue("@p3", p3);
        //rd.SetParameterValue("@p4", p4);

        Response.Buffer = false;
        Response.ClearContent();
        Response.ClearHeaders();

        Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
        stream.Seek(0, SeekOrigin.Begin);

        return File(stream, "application/pdf", "Something.pdf");
    }

Using form submission this works fine.

Form code in View:

@using (Html.BeginForm("ExportToPDF", "ControllerName", FormMethod.Get))
{
    @Html.DropDownList("p1", (SelectList)ViewBag.p1List, "Select P1")
    @Html.DropDownList("p2", (SelectList)ViewBag.p2List, "Select P2")
    @Html.DropDownList("p3", (SelectList)ViewBag.p3List, "Select P3")
    @Html.DropDownList("p4", (SelectList)ViewBag.p4List, "Select P4")
    <input type="submit" value="Show" id="showButton" />
}

But I want to do this using jquery custom button. Please help me correct the below code.

jQuery datatable buttons configuration:

// Show buttons for Export and Copy
    "buttons": [
        {
            text: 'Export',
            action: function (e, dt, node, config) {
                $.ajax({
                    "url": "/ControllerName/ExportToPDF",
                    "type": "GET",
                    "data": {
                        "p1": $("#p1").val(),
                        "p2": $("#p2").val(),
                        "p3": $("#p3").val(),
                        "p4": $("#p4").val()
                    }
                });
            }
        },
        {
            extend: 'copyHtml5',
            text: 'Copy',
            titleAttr: 'Copy'
        },
]

Solution

  • 1) make a function and just call that function in button action, to avoid mess and also can call from elsewhere

            {
                text: 'Export',
                action: function (e, dt, node, config) {
                   downloadpdf();
                }
    

    return the url of your pdf and then do this way

    function downloadpdf(){
          $.ajax({
              "url": "/ControllerName/ExportToPDF",
              "type": "GET",
              "data": {// your data
               },
              xhrFields: {
                responseType: 'blob'
              },
       beforeSend: function ()
        {
             // loader start
            App.blockUI({animate: true}); 
        },
        error: function () {
            App.unblockUI();
    
        },
        success: function (objJson) {
                App.unblockUI();
                var a = document.createElement('a');
                var url = window.URL.createObjectURL(data);
                a.href = url;
                a.download = 'myfile.pdf'; //  name you want to give
                a.click();
                window.URL.revokeObjectURL(url);
            }
        });
    }
    

    2) there is another way by creating a form, and submiting it and then its not ajax, i used it for exporting csv and excel,

       $('<form>', {
            "id": "mypdf",
            "html": '<input type="hidden" name="ids" value="test" />', // any extra params
            "action": 'ExportToPDF',
            "method":'POST'
        }).appendTo(document.body).submit();
    
        $('#exportcsvform').remove();
    

    and in your controller

    public function actionExportcsv() {
            header('content-type: application/pdf');
            header('Content-Disposition: attachment;filename="export.pdf"');
    
            // code for your pdf
    
            exit();
        }
    

    there is another way by iframe, which you can also use , by creating an iframe and open your pdf link in iframe