Introduction
This tip shows how to use Crystal Reports to print without using the print preview control with any report ".rpt".
Background
Unfortunately over the years, Crystal Reports have become a monster to both understand and use.
I have used this code for a few years now and it works with any type of report created with CR12 to print embedded reports in projects.
This sub could be put in any class as long it will expose itself to the project.
Make sure the report is included and embedded in your project.
internal void setConSQLRPT(CrystalReports.Engine.ReportDocument rptReport, string strReportName)
{
string strServer = My.Computer.Name;
string DBInstance = "SQLExpress";
ConnectionInfo connection = new ConnectionInfo();
connection.DatabaseName = "MYDB";
connection.AllowCustomConnection = true;
connection.ServerName = strServer + @"\" + DBInstance;
connection.IntegratedSecurity = false;
connection.Type = ConnectionInfoType.SQL;
connection.UserID = "USERNAMEINDB";
connection.Password = "XXXXX";
TableLogOnInfo logOnInfo = new TableLogOnInfo();
logOnInfo.ReportName = strReportName;
foreach (CrystalDecisions.CrystalReports.Engine.Table myTable in rptReport.Database.Tables) {
logOnInfo = myTable.LogOnInfo;
logOnInfo.ConnectionInfo = connection;
myTable.ApplyLogOnInfo(logOnInfo);
myTable.TestConnectivity();
}
}
using CrystalDecisions;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
CrystalDecisions.CrystalReports.Engine.ReportDocument mwPRT;
mwPRT = new EmbeddedReportName();
setConSQLRPT(mwPRT, "EmbeddedReportName.rpt");
mwPRT.Refresh();
mwPRT.SetParameterValue("CompanyName", Value1);
mwPRT.SetParameterValue("Fontalign", Value2);
mwPRT.SetParameterValue("Font", Value3);
mwPRT.SetParameterValue("FontSize", (float)Value4);
System.Drawing.Printing.PrinterSettings oPrinterSettings = new System.Drawing.Printing.PrinterSettings();
oPrinterSettings.PrinterName = "Brother MFC-6490CW";
mwPRT.PrintOptions.PrinterName = oPrinterSettings.PrinterName;
mwPRT.PrintToPrinter(1, false, 1, 99);
mwPRT.Close();
Voila, a printed report.
You can even use SQL queries from your own code and pass in the result to the embedded report instead of relying on CR to create the result, could be much faster to print if the query is already done within your method, depending on the complexity of the query.
If anyone is interested to know how, I will edit later.