Wednesday, February 10, 2016

How to call report in MVC Report.aspx with custom print button

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ReportPage.aspx.cs" Inherits="UI.Report.ReportPage" %>

<%@ Register Assembly="Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"
    Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>

<html>
<head id="Head1" runat="server">
 
    <script src="Content/js/bootstrap.js"></script>
    <script src="Content/js/jquery.min.js"></script>


    <title>View Report</title>
</head>

<style type="text/css">
    html, body, form {
        margin: 0;
        padding: 0;
        height: 100%;
        overflow: hidden;
        font-family: Verdana, Tahoma, Arial;
        font-size: small;
    }

    .spinner {
        position: fixed;
        top: 50%;
        left: 50%;
        margin-left: -50px; /* half width of the spinner gif */
        margin-top: -50px; /* half height of the spinner gif */
        text-align: center;
        z-index: 1234;
        overflow: auto;
        width: 150px; /* width of the spinner gif */
        height: 62px; /*height of the spinner gif +2px to fix IE8 issue */
        background-color: #E1E1D7;
        border: 1px solid black;
    }

    .HighlightDiv img {
        background-color: transparent;
        border-top-width: 1px;
        border-right-width: 1px;
        border-bottom-width: 1px;
        border-left-width: 1px;
        border-top-color: transparent;
        border-right-color: transparent;
        border-bottom-color: transparent;
        border-left-color: transparent;
        border-top-style: solid;
        border-right-style: solid;
        border-bottom-style: solid;
        border-left-style: solid;
        cursor: default;
    }

    .HighlightDiv:hover img {
        background-color: #DDEEF7;
        border-top-width: 1px;
        border-right-width: 1px;
        border-bottom-width: 1px;
        border-left-width: 1px;
        border-top-color: #336699;
        border-right-color: #336699;
        border-bottom-color: #336699;
        border-left-color: #336699;
        border-top-style: solid;
        border-right-style: solid;
        border-bottom-style: solid;
        border-left-style: solid;
        cursor: pointer;
    }
    .dirRTL{
        direction:rtl;
    }
</style>

<body  >
     
    <form id="frmReportViewer" runat="server">
        <asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true"
            EnablePartialRendering="true" runat="server">
        </asp:ScriptManager>
        <div id="divMain">
            <rsweb:ReportViewer ID="TransportationReportViewer" runat="server" ProcessingMode="Remote"  Height="700px" CssClass="dirRTL"
            Width="1024px" >
        </rsweb:ReportViewer>

            <iframe id="frmPrint" name="frmPrint" runat="server" style="display: none"></iframe>
        </div>
        <div id="spinner" class="spinner" style="display: none;">
            <table align="center" valign="middle" style="height: 100%; width: 100%">
                <tr>
                    <td>
                        <img id="img-spinner"  src="../Content/img/InProgess.gif" alt="Printing" /></td>
                    <td><span style="font-family: Verdana; font-weight: bold; font-size: 10pt; width: 86px;">Printing...</span></td>
                </tr>
            </table>
        </div>
           
   
    </form>

<script  type="text/javascript">



    $(document).ready(function () {
        $("#spinner").bind("ajaxSend", function () {
            $(this).show();
        }).bind("ajaxStop", function () {
            $(this).hide();
        }).bind("ajaxError", function () {
            $(this).hide();
        });
        //$(function () {
        //    showDatePicker();
        //});
        $(function () {
            showPrintButton();
        });
    });

    //$("#TransportationReportViewer_ctl04_ctl00").click(function () {
    //    //   window.setTimeout("printPDF(this);", 3000);
    //    alert('riyad');
    //    window.setTimeout("showPrintButton();", 1000);
    //});

    $(document).on("click", "#TransportationReportViewer_ctl04_ctl00", function () {
        $("#TransportationReportViewer_ctl04_ctl00").attr('value', 'طباعة الطلب');
        window.setTimeout("showPrintButton();", 1000);
    });

    $("#TransportationReportViewer_ctl04_ctl00").attr('value', 'طباعة الطلب');
 

    function showDatePicker() {

        var parameterRow = $("#ParametersRowrvREXReport");
        var innerTable = $(parameterRow).find("table").find("table");
        var span = innerTable.find("span:contains('From Date (dd/mm/yyyy):')");
        if (span) {
            var innerRow = $(span).parent().parent();
            var innerCell = innerRow.find("td").eq(1);
            var textFrom = innerCell.find("input[type=text]");
            innerCell = innerRow.find("td").eq(4);
            var textTo = innerCell.find("input[type=text]");

            $(textFrom).datepicker({
                defaultDate: "+1w",
                dateFormat: 'dd/mm/yy',
                changeMonth: true,
                numberOfMonths: 1,
                onClose: function (selectedDate) {
                    $(textTo).datepicker("option", "minDate", selectedDate);
                }
            });
            $(textFrom).focus(function (e) {
                e.preventDefault();
                $(textFrom).datepicker("show");
            });
            $(textTo).datepicker({
                defaultDate: "+1w",
                dateFormat: 'dd/mm/yy',
                changeMonth: true,
                numberOfMonths: 1,
                onClose: function (selectedDate) {
                    $(textFrom).datepicker("option", "maxDate", selectedDate);
                }
            });
            $(textTo).focus(function () {
                $(textTo).datepicker("show");
            });
        }
    }

    //Function that is called on Successful AJAX method call.  These are referenced in the "CallServerMethodBeforePrint" function that is created from code behind and will exist in the final rendering of the page.
    function ServerCallSucceeded(result, context) {
        var iFrameURL = "<%=iFrameURL%>";
        window.frames['frmPrint'].document.location.href = iFrameURL;
        window.frames['frmPrint'].focus();
        var timeout = window.setTimeout("window.frames[\"frmPrint\"].focus();window.frames[\"frmPrint\"].print();", 500);
        window.setTimeout("ServerCallAfterPrint(this)", 2000);
    }

    function ServerCallSucceededAfterPrint(result, context) {
    }

    //Function that is called on failure or error in AJAX method call. These are referenced in the "CallServerMethodBeforePrint" function that is created from code behind and will exist in the final rendering of the page.
    function ServerCallFailed(result, context) {
    }

    function ServerCallBeforePrint(btn) {
        $('#spinner').show();
        var context = new Object();
        //example of passing multiple args
        context.flag = new Array('1');
        //This "CallServerMethodBeforePrint" function is created from code behind and will exist in the final rendering of the page
        CallServerMethodBeforePrint(context.flag, context);
    }

    function ServerCallAfterPrint(btn) {
        var context = new Object();
        //example of passing multiple args
        context.flag = new Array('2');
        //This "CallServerAfterPrint" function is created from code behind and will exist in the final rendering of the page
        CallServerAfterPrint(context.flag, context);
        $('#spinner').hide();
    }

    function printPDF(btn) {
        ServerCallBeforePrint(btn);
    }

    function showPrintButton() {
        var table = $("table[title='Refresh']");
        var parentTable = $(table).parents('table');
        var parentDiv = $(parentTable).parents('div').parents('div').first();
        var btnPrint = $("<input type='button' id='btnPrint' name='btnPrint' value='Print' style=\"font-family:Verdana;font-size:8pt;width:86px\"/>");
        var btnClose = $("<input type='button' id='btnClose' name='btnClose'value='Close' style=\"font-family:Verdana;font-size:8pt;width:86px\"/>");
        btnPrint.click(function () {
            printPDF(this);
        });
        btnClose.click(function () {
            window.close();
        });
        if (parentDiv.find("input[value='Print']").length == 0) {
            parentDiv.append('<table cellpadding="0" cellspacing="0" toolbarspacer="true" style="display:inline-block;width:6px;"><tbody><tr><td></td></tr></tbody></table>');
            parentDiv.append('<div id="customDiv" class=" " style="display:inline-block;font-family:Verdana;font-size:8pt;vertical-align:inherit;"><table cellpadding="0" cellspacing="0"><tbody><tr><td><span style="cursor:pointer;" class="HighlightDiv" onclick="javascript:printPDF(this);" ><img src="../Content/img/Print.png" alt="Print Report" title="Print Report" width="18px" height="18px" style="margin-top:4px"/></span></td></tr></tbody></table></div>');
            parentDiv.append('<table cellpadding="0" cellspacing="0" toolbarspacer="true" style="display:inline-block;width:10px;"><tbody><tr><td></td></tr></tbody></table>');
            parentDiv.append('<div id="customDiv" class=" " style="display:inline-block;font-family:Verdana;font-size:8pt;vertical-align:inherit;"><table cellpadding="0" cellspacing="0" style="display:inline;"><tbody><tr><td><span style="cursor:pointer;" class="HighlightDiv" onclick="javascript:window.close();"></span></td></tr></tbody></table></div>');
        }
    }
    function cfnReportsViewer_ViewReport(selectedTreeKeyGuidValue, ReportName, VenueExamCounter) {
        var windowWidth = 1000;
        var windowHeight = 800;
        var left = (screen.width / 2) - (windowWidth / 2);
        var top = (screen.height / 2) - (windowHeight / 2);
        var myForm = document.getElementById("frmReportViewer");
        if (myForm) {
            myForm.target = "PopupReport";
        }
        $("#hfAccessObjectGuid").val(selectedTreeKeyGuidValue);
        $("#hfReportName").val(ReportName);
        $("#hfVenueExamCounter").val(VenueExamCounter);
        var thePopup = window.open("about:blank", "PopupReport", 'scrollbars=yes,status=yes,toolbar=yes,menubar=no,location=no,resizable=no,fullscreen=yes, width=' + windowWidth + ', height=' + windowHeight + ', top=' + top + ', left=' + left);
        window.setTimeout(document.getElementById("frmReportViewer").submit(), 500);
        return false;
    }
</script>

</body>
</html>
---------------------------------------------------------------------------------------------------
Code Behind



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Reporting.WebForms;
using Microsoft.Reporting.WebForms.Internal;
using System.Drawing.Printing;
using System.IO;
using System.Drawing.Imaging;
using System.Globalization;
using System.Text;
using System.Collections.Specialized;
using System.Drawing;

using System.Configuration;
using System.ComponentModel;
//using System.Drawing.Printing;

namespace UI.Report
{
    public partial class ReportPage : System.Web.UI.Page, ICallbackEventHandler
    {
        private string _reportName;
        private string _sessionPDFFileName;
        protected string iFrameURL;

        protected void Page_Load(object sender, EventArgs e)
        {
            _reportName = "ReportName";
            _sessionPDFFileName = Session.SessionID.ToString() + ".pdf";
            //Attach pdf to the iframe
            string url = HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + HttpContext.Current.Request.ApplicationPath + _sessionPDFFileName;
            iFrameURL = url;
            RegisterClientsCallBackReference();
            RegisterClientCallBackAfterPrint();

           

            if (!IsPostBack)
            {
                RenderReport();
            }
            else
            {
                this.TransportationReportViewer.ShowReportBody = true;
               // RenderReport();
            }


        }

        private ReportParameter[] GetHCResultRepParameters()
        {
            ReportParameter[] RptParameters = null;
            var orderID = "";
            if (null != Request.QueryString["orderID"]) orderID = Request.QueryString["orderID"].ToString();
            RptParameters = new Microsoft.Reporting.WebForms.ReportParameter[1];
            RptParameters[0] = !string.IsNullOrEmpty(orderID) ?
                new Microsoft.Reporting.WebForms.ReportParameter("orderID", orderID, false) :
                new Microsoft.Reporting.WebForms.ReportParameter("orderID", new string[] { null }, false);
            return RptParameters;
        }

       
        //--------------------------------------------------------------------------------------
        #region PrintButton
        protected void ShowPrintButton()
        {

            string script = "<SCRIPT LANGUAGE='JavaScript'> ";
            script += "showPrintButton()";
            script += "</SCRIPT>";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowStatus", "javascript:showPrintButton();", true);

        }

        protected void SavePDF()
        {
            string _reportPath = Request.PhysicalApplicationPath + "\\UPLOADS\\";
            Warning[] warnings;
            string[] streamids;
            string mimeType;
            string encoding;
            string extension;
            this.TransportationReportViewer.LocalReport.ReportPath = _reportName;
            System.Diagnostics.Trace.WriteLine(_reportName);

            byte[] bytes = this.TransportationReportViewer.ServerReport.Render("PDF", "", out mimeType, out encoding, out extension, out streamids, out warnings);
            //save the pdf byte to the folder
            if (!File.Exists(Server.MapPath(_sessionPDFFileName)))
            {
                using (StreamWriter sw = new StreamWriter(File.Create(Server.MapPath(_sessionPDFFileName))))
                {
                    sw.Write("");
                }
            }
            FileStream fs = new FileStream(Server.MapPath(_sessionPDFFileName), FileMode.Create);
            byte[] data = new byte[fs.Length];
            fs.Write(bytes, 0, bytes.Length);
            fs.Close();
        }

        protected void TransportationReportViewer_ReportRefresh(object sender, CancelEventArgs e)
        {
            ShowPrintButton();
        }

        public string AjaxCall(string name)
        {
            System.Diagnostics.Trace.WriteLine(_sessionPDFFileName);
            //if (name == "2") //Delete file- After print
            //{
            if (File.Exists(_sessionPDFFileName))
            {
                //frmPrint.Attributes["src"] = "";
                File.Delete(_sessionPDFFileName);
            }
            //}
            //else 
            if (name == "1") //Create file- before print
            {
                SavePDF();
            }
            return name;
            ////var ajaxcall = Request.Form["ajaxcall"];
            //if (name != null)
            //{
            //    if (File.Exists(Server.MapPath(_sessionPDFFileName)))
            //    {
            //        //frmPrint.Attributes["src"] = "";
            //        File.Delete(Server.MapPath(_sessionPDFFileName));
            //    }
            //    else
            //    {
            //        SavePDF();
            //    }
            //}
            //return name;
        }

        string returnValue;

        string ICallbackEventHandler.GetCallbackResult()
        {
            return returnValue;
        }

        void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument)
        {
            returnValue = AjaxCall(eventArgument);
        }

        private void RegisterClientsCallBackReference()
        {

            String myClientsCallBack = Page.ClientScript.GetCallbackEventReference(this, "arg", "ServerCallSucceeded", "context", "ServerCallFailed", true);
            //Could also call this wtihout the callback succeeded or failed methods:
            String myCompleteClientFunction = @"function CallServerMethodBeforePrint(arg, context)
                                      { " +
                                            myClientsCallBack + @"; 
                                      }";
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "TheScriptToCallServer", myCompleteClientFunction, true);

        }

        private void RegisterClientCallBackAfterPrint()
        {
            String myClientAfterPrintCallBack = Page.ClientScript.GetCallbackEventReference(this, "arg", "ServerCallSucceededAfterPrint", "context", "ServerCallFailed", true);

            String myAfterPrintCompleteClientFunction = @"function CallServerAfterPrint(arg, context)
                                      { " +
                                            myClientAfterPrintCallBack + @"; 
                                      }";
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "TheScriptToCallServerAfterPrint", myAfterPrintCompleteClientFunction, true);
        }

        #endregion

        public void RenderReport()
        {
            var querystring = string.Empty;
            if (null != Request.QueryString["reportName"]) querystring = Request.QueryString["reportName"].ToString();
            if (!string.IsNullOrEmpty(querystring))
            {
                this.TransportationReportViewer.Visible = true;
                this.TransportationReportViewer.ServerReport.ReportServerUrl = new System.Uri(ConfigurationManager.AppSettings["Report_URL"]);
                string strReport = "/Masajed Sector/" + querystring;
                this.TransportationReportViewer.ServerReport.ReportPath = strReport;
                _reportName = strReport;


                if (querystring == "notesDismissal")
                {
                    this.TransportationReportViewer.ServerReport.SetParameters(GetHCResultRepParameters());
                    this.TransportationReportViewer.ShowParameterPrompts = true;
                }

                if (querystring == "notesDismissalSpecialOrder")
                {
                    this.TransportationReportViewer.ServerReport.SetParameters(GetHCResultRepParameters());
                    this.TransportationReportViewer.ShowParameterPrompts = false;
                }
                this.TransportationReportViewer.ServerReport.Refresh();
                this.TransportationReportViewer.PageCountMode = PageCountMode.Actual;
                //ShowPrintButton();

                if (querystring == "RptListofBooks")
                {
                    this.TransportationReportViewer.ShowParameterPrompts = true;
                    this.TransportationReportViewer.ShowReportBody = true;
                }
                if (querystring == "RptRequesterOrderBooks")
                {
                    this.TransportationReportViewer.ShowParameterPrompts = true;
                    this.TransportationReportViewer.ShowReportBody = true;
                }
                if (querystring == "OrderStatistics_Departmentwise")
                {
                    this.TransportationReportViewer.ShowParameterPrompts = true;
                    this.TransportationReportViewer.ShowReportBody = true;
                }
                if (querystring == "OrderStatistics_Jobwise")
                {
                    this.TransportationReportViewer.ShowParameterPrompts = true;
                    this.TransportationReportViewer.ShowReportBody = true;
                }
                if (querystring == "RptOrderStatisticDeptJobwise")
                {
                    this.TransportationReportViewer.ShowParameterPrompts = true;
                    this.TransportationReportViewer.ShowReportBody = true;
                }
                if (querystring == "OrderStatistics_Bookwise")
                {
                    this.TransportationReportViewer.ShowParameterPrompts = true;
                    this.TransportationReportViewer.ShowReportBody = true;
                }
                if (querystring == "OrderStatistics_Bookwise")
                {
                    this.TransportationReportViewer.ShowParameterPrompts = true;
                    this.TransportationReportViewer.ShowReportBody = true;
                }
                if (querystring == "BookStock")
                {
                    this.TransportationReportViewer.ShowParameterPrompts = true;
                    this.TransportationReportViewer.ShowReportBody = true;
                }
                

            }
            
        }

    }

    
}

No comments:

Post a Comment