Click here to Skip to main content
15,885,194 members
Articles / Programming Languages / C#
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
4.93/5 (7 votes)
8 May 2014CPOL1 min read 46.3K   4.8K   19   14
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:

HTML
<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".

C#
<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.

C#
[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):

C#
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)


Written By
Web Developer DatumSquare IT Services
Pakistan Pakistan
Working as Associate Team Lead in DatumSquare IT Services Lahore. Web development is basic field

Comments and Discussions

 
QuestionConnection to data Pin
Member 1349457030-Oct-17 16:29
Member 1349457030-Oct-17 16:29 
QuestionHow to use the code example Pin
abramhum.c.l6-Aug-17 18:03
abramhum.c.l6-Aug-17 18:03 
QuestionGood Exmple... Pin
vfpdude18-Apr-16 6:01
vfpdude18-Apr-16 6:01 
Questionhow to add parameter and json data in Ajax to display report? Pin
phairainam29-Nov-15 17:14
phairainam29-Nov-15 17:14 
QuestionParameter issue Pin
Simon_Di24-Apr-15 9:12
Simon_Di24-Apr-15 9:12 
AnswerRe: Parameter issue Pin
youngseagul21-May-15 3:34
professionalyoungseagul21-May-15 3:34 
GeneralRe: Parameter issue Pin
Simon_Di9-Jun-15 12:15
Simon_Di9-Jun-15 12:15 
GeneralRe: Parameter issue Pin
Simon_Di17-Jun-15 5:55
Simon_Di17-Jun-15 5:55 
GeneralRe: Parameter issue Pin
robertxfile1-Sep-15 13:22
robertxfile1-Sep-15 13:22 
GeneralRe: Parameter issue Pin
Vishnutm21-Mar-16 21:33
Vishnutm21-Mar-16 21:33 
Questionstill crystal report loading in new page for me Pin
Member 351903010-Sep-14 2:22
Member 351903010-Sep-14 2:22 
GeneralMy vote of 5 Pin
Renju Vinod8-May-14 23:24
professionalRenju Vinod8-May-14 23:24 
QuestionNice but Pin
Faisalabadians8-May-14 21:10
Faisalabadians8-May-14 21:10 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun8-May-14 20:12
Humayun Kabir Mamun8-May-14 20:12 

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

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