Click here to Skip to main content
Click here to Skip to main content

Running Crystal Reports in MVC 4 using PDF.js and PDF Viewer

, 8 May 2014
Rate this:
Please Sign up or sign in to vote.
How to run Crystal reports in MVC 4 using PDF.js and PDF viewer
Sample Image - maximum width is 600 pixels

Introduction

The basic purpose of this tip is to show Crystal reports in MVC 4 using razor, pdf.js and PDF viewer.

Background

This tip uses MVC 4 razor syntax, Crystal Reports, SAP business object DLLs, and pdf.js. PDF.js is a Portable Document Format (PDF) viewer that is built with HTML5. PDF.js is community-driven and supported by Mozilla Labs. Its goal is to create a general-purpose, web standards-based platform for parsing and rendering PDFs. So, all rights are reserved with their respected creators. You can get details of pdf.js from https://github.com/mozilla/pdf.js.

Using the Code

All the code present in the source folder is very simple. Here are a few steps:

Step 1

I have two divs in index.cshtml page:

<div>
<button class="btn yellow" style="width: 253px;" id="RunReportBtn" onclick="RunReport()"> Run Reports
</button>
</div>
<div>
<div class="reportsDiv" id="reportsDiv">
</div
</div>

Step 2

Here is the Ajax GET method that can also be used to send parameters for Crystal reports.

After success, I refresh Div and change its source using “RefreshReport” action which returns partial view "_ReportsDisplay".

<script>
            function RunReport() {
                $.ajax({
                    url: '/Home/ShowReport',
                    type: 'GET',
                    success: function (response) {
                        //debugger;
                        if (response.result == "-2") {
                            alert('Error during display of report');
                        }
                        else {
                            $('#reportsDiv').load('Home/RefreshReport');
                        }
                    },
                    error: function (xhr, status, error) {
                        displayErrorMessage('Error during display of report');
                    }
                });
            }

</script>

Step 3

Please study the code in _ReportsDisplay.cshtml and ReportView.cshtml, it is simple HTML.

Step 4

This action returns pdf as inline content.

[HttpGet]
        public ActionResult ShowReport()
        {
            bool isValid = true;
            string jsonErrorCode = "0";
            string strReportName = "generic.rpt";
            string msg = "";
            string strFromDate = DateTime.Now.AddDays(-30).ToString("mm/dd/yyyy");
            string strToDate = DateTime.Now.ToString("mm/dd/yyyy");
            try
            {
                if (isValid)
                {
                    ReportDocument rd = new ReportDocument();
                    string strRptPath = System.Web.HttpContext.Current.Server.MapPath("~/") + "App_Data//" + strReportName;
                    var rptSource = GetStudents();
                    rd.Load(strRptPath);
                    if (rptSource != null && rptSource.GetType().ToString() != "System.String")
                        rd.SetDataSource(rptSource);
                    if (!string.IsNullOrEmpty(strFromDate))
                        rd.SetParameterValue("fromDate", strFromDate);
                    if (!string.IsNullOrEmpty(strToDate))
                        rd.SetParameterValue("toDate", strFromDate);
                    rd.ExportToHttpResponse(ExportFormatType.PortableDocFormat, 
                    System.Web.HttpContext.Current.Response, false, "crReport");
                }
                else
                {
                    Response.Write("<H2>Report not found</H2>");
                }
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                jsonErrorCode = "-2";
            }

            return Json(new { result = jsonErrorCode, err = msg }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult RefreshReport()
        {
            return PartialView("_ReportsDisplay");
        }
        private List<Student> GetStudents()
        {
            return new List<Student>() { 
            new Student(){StudentID=1,StudentName="Abid Hussain"},
            new Student(){StudentID=2,StudentName="Muhammad Ibraheem"}
            };
        }
    }        

Step 5

I have changed one line in viewer.js (contents/pdfjs1030/web/viewer.js):

var DEFAULT_URL = 'showreport';

Note

Contents of Pdfjs1030 folder are property of https://github.com/mozilla/pdf.js.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

youngseagul
Web Developer DatumSquare IT Services
Pakistan Pakistan
Working as Associate Team Lead in DatumSquare IT Services Lahore. Web development is basic field
Follow on   Twitter   LinkedIn

Comments and Discussions

 
GeneralMy vote of 5 PinprofessionalRenju Vinod8-May-14 23:24 
QuestionNice but PinmemberFaisalabadians8-May-14 21:10 
GeneralMy vote of 5 PinmemberHumayun Kabir Mamun8-May-14 20:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140827.1 | Last Updated 8 May 2014
Article Copyright 2014 by youngseagul
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid