Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print Crystal Report Directly in ASP.NET C#

I am populating data in Crystal Report using SQL Server stored procedures. I was able to achieve my desired printing output using parameters passing and formatting each column using formula in CR.

In printing reports, the usual process is it will preview the created / generated output in Crystal Report Viewer, then, there are the print, export options where it will convert first the report to PDF to proceed to the printing functions

What I want is when I click the print button, It will automatically lead to printing procedures.

I was lead to this link for the answer How to print crystal report directly to a client machine using C# Asp.net

using oReportDocument.PrintToPrinter(1,true,0,0); 

code, others also suggesting to fill the dataset in page init, but I am seem lost on how to do it.

This is my currently working code (the usual printing process where it will lead you first to the Crystal Report preview.

public partial class Report_MonthlySalesReportPrint : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
    ReportDocument report = new ReportDocument();

    protected void Page_Load(object sender, EventArgs e)
    {
        con.Open();

        //Parameters to be passed as needed in formulas in Report
        string RP = Session["RP"].ToString();
        DateTime cms = Convert.ToDateTime(Session["CurrentMonthStart"].ToString());
        string Loc = Session["Location"].ToString();
        string MonthCurrent = Session["MonthCurrent"].ToString();
        string YearCurrent = Session["YearCurrent"].ToString();
        string MonthPrevious = Session["MonthPrevious"].ToString();
        string YearPrevious = Session["YearPrevious"].ToString();
        string MonthLastYear = Session["MonthLastYear"].ToString();
        string YearLastYear = Session["YearLastYear"].ToString();

        report.Load(Server.MapPath("MSRC.rpt"));

        CrystalReportViewer1.ReportSource = report;
        CrystalReportViewer1.ReuseParameterValuesOnRefresh = true;
        CrystalReportViewer1.DataBind();

        report.SetParameterValue(0, MonthLastYear);
        report.SetParameterValue(1, MonthCurrent);
        report.SetParameterValue(2, MonthPrevious);
        report.SetParameterValue(3, RP);
        report.SetParameterValue(4, Loc);
        report.SetParameterValue(5, cms);
        report.SetParameterValue(6, YearCurrent);
        report.SetParameterValue(7, YearPrevious);
        report.SetParameterValue(8, YearLastYear);

        report.PrintToPrinter(1, true, 0, 0);
        con.Close();
    }
}

UPDATED:

I just needed this to update for clarification purposes that the accepted answer below will work only on server side. Meaning when user is accessing the server remotely, the code will not work.

like image 870
rickyProgrammer Avatar asked Apr 07 '15 08:04

rickyProgrammer


3 Answers

       using System.Drawing.Printing;
       using Crystal Decisions.CrystalReports.Engine;
       using Crystal Decisions.Shared;
       protected void Page_Load(object sender, EventArgs e)
       {
         void();
       }
       public void()
       {
         try
        {
         ReportDocument crystalReport = new ReportDocument();
         crystalReport.Load(Server.MapPath("~/CrystalReport2.rpt"));
         DataSet dsCustomers = GetData("select * from visitor_details where  id ='" + Session["sessionvid"] + "' and  plant ='" + Session["sessionplant"] + "'");

         DataTable dataTable = dsCustomers.Tables[0];   crystalReport.Database.Tables["visitor_details"].SetDataSource((DataTable)dataTable);
          CrystalReportViewer2.ReportSource = crystalReport;
          CrystalReportViewer2.Zoom(100);
          //crystalReportViewer1.ExportReport() ;
          CrystalReportViewer2.RefreshReport();
          crystalReport.PrintOptions.PrinterName = GetDefaultPrinter();
          crystalReport.PrintToPrinter(1, false, 0, 0);
        }
        catch
        {
            Response.Write("<script LANGUAGE='JavaScript' >alert('connect printer settings')</script>");
        }

}

like image 200
balajibran Avatar answered Sep 21 '22 21:09

balajibran


This works for me. You can create your own PageSettings if needed, else just use an emtpy one.

If you want to open a print dialogue, simply use PrintDialog;

using System.Windows.Forms;

//...

ReportClass report = new ReportClass();
report.FileName = @"C:/Layout.rpt";
report.Load();
report.SetDataSource(YourSource);

PrinterSettings settings = new PrinterSettings();

PrintDialog pdialog = new PrintDialog();
if (pdialog.ShowDialog() == DialogResult.OK)
{
    settings = pdialog.PrinterSettings;
}

report.PrintToPrinter(settings, new PageSettings() { }, false);
like image 31
Dion V. Avatar answered Sep 20 '22 21:09

Dion V.


1. CLIENT-SIDE PRINTING

This is the most ideal method in printing in a Web-based application as most users will be certainly accessing the server remotely.

Put this javascript code inside the head tag of your .aspx page where the crystal report viewer resides.

     <script type="text/javascript">


                function Print() {
                      var dvReport = document.getElementById("dvReport");
                      var frame1 = dvReport.getElementsByTagName("iframe")[0];
                      if (navigator.appName.indexOf("Internet Explorer") != -1) {
                          frame1.name = frame1.id;
                          window.frames[frame1.id].focus();
                          window.frames[frame1.id].print();
                      }
                      else {
                          var frameDoc = frame1.contentWindow ? frame1.contentWindow : frame1.contentDocument.document ? frame1.contentDocument.document : frame1.contentDocument;
                          frameDoc.print();
                      }
                  }
            </script>

With the same page, in the body tag put this

  <body>
        <form id="form1" runat="server">
        <asp:Button ID="btnPrint" runat="server" Text="Print Directly" OnClientClick="Print()"></asp:Button>

          <div id="dvReport">
            <CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" AutoDataBind="true" ToolPanelView="None" EnableDatabaseLogonPrompt="false"  />


          </div>
        </form>
    </body>

-- take note of the button in there. it should be outside the div that enclosed the crystal report viewer. This will surely work. see Full discussion on this method: http://www.aspsnippets.com/Articles/Print-Crystal-Report-on-Client-Side-on-Button-Click-using-JavaScript-in-ASPNet.aspx


2. SERVER SIDE PRINTING

The most suggested answers here is the printToPrinter() Function. This method is done on server-side, hence, it is limited when you are accessing the server of your Web-based application / website remotely, unless the client can map or have the access with the server printer.


Please read this for further info: http://aspalliance.com/509_Automatically_Printing_Crystal_Reports_in_ASPNET.3

like image 39
rickyProgrammer Avatar answered Sep 19 '22 21:09

rickyProgrammer