Click here to Skip to main content
12,697,076 members (29,638 online)
Click here to Skip to main content
Add your own
alternative version

Stats

20.8K views
3.1K downloads
18 bookmarked
Posted

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

, 8 May 2014 CPOL
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

You may also be interested in...

Comments and Discussions

 
QuestionGood Exmple... Pin
vfpdude18-Apr-16 7:01
membervfpdude18-Apr-16 7:01 
Questionhow to add parameter and json data in Ajax to display report? Pin
phairainam29-Nov-15 18:14
memberphairainam29-Nov-15 18:14 
QuestionParameter issue Pin
Simon_Di24-Apr-15 10:12
memberSimon_Di24-Apr-15 10:12 
AnswerRe: Parameter issue Pin
youngseagul21-May-15 4:34
professionalyoungseagul21-May-15 4:34 
GeneralRe: Parameter issue Pin
Simon_Di9-Jun-15 13:15
memberSimon_Di9-Jun-15 13:15 
GeneralRe: Parameter issue Pin
Simon_Di17-Jun-15 6:55
memberSimon_Di17-Jun-15 6:55 
GeneralRe: Parameter issue Pin
robertxfile1-Sep-15 14:22
memberrobertxfile1-Sep-15 14:22 
GeneralRe: Parameter issue Pin
Vishnutm21-Mar-16 22:33
memberVishnutm21-Mar-16 22:33 
Questionstill crystal report loading in new page for me Pin
Member 351903010-Sep-14 3:22
memberMember 351903010-Sep-14 3:22 
GeneralMy vote of 5 Pin
Renju Vinod9-May-14 0:24
professionalRenju Vinod9-May-14 0:24 
QuestionNice but Pin
Faisalabadians8-May-14 22:10
memberFaisalabadians8-May-14 22:10 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun8-May-14 21:12
memberHumayun Kabir Mamun8-May-14 21: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.

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