Home > Crystal Report > How to print crystal reports using .Net

How to print crystal reports using .Net

The following code is a console application (.Net 1 or 2) which loads a crystal report file and set the database setting to a defined ORACLE database (9i, or 10g) and print the report to a local or network printer.

Step1: Create a console application

moz-screenshot

Step2: I used Crystal XI for thsi application and thats what I recommend

Add reference to

  • CrystalDecisions.CrystalReports.Engine (11.5.33)
  • CrystalDecisions.Shared (11.5.33)

 

Step3: Copy the following code to Module1, and change the report name and required parameters (highlighted with bold text).

 

Source code:

 

Module Module1
 

  Public _PrinterAddress As String = Nothing
  Public _ServiceName As String = Nothing
  Public _UserName As String = Nothing
  Public _Password As String = Nothing
  Public _ReportPath As String = Nothing
  Public Const _ReportName As String = “Report.RPT
  Public _ReportDocument As CrystalDecisions.CrystalReports.Engine.ReportDocument

 

  Sub Main()
    Try
      Console.WriteLine(“Application started.” & Environment.NewLine)
      Console.Write(“Enter Printer Network Address:”)
      _PrinterAddress = Console.ReadLine     
      Console.Write(“Enter Oracle Service Name:”)
      _ServiceName = Console.ReadLine
      Console.Write(“Enter Oracle Username:”)
      _UserName = Console.ReadLine
      Console.Write(“Enter Oracle Password:”)
      _Password = Console.ReadLine
      Console.Write(“Enter Oracle Report Path:”)
      _ReportPath = Console.ReadLine
      If LoadReportFile() Then
        SetDatabaseLogonForReport(_ReportDocument)
        AddReportParameters()
        PrintToPrinter()
      End If
      _ReportDocument = Nothing
      Console.WriteLine(“Application end.”)
      Console.Read()
    Catch ex As Exception
      Console.WriteLine(ex.Message)
      Console.WriteLine(ex.StackTrace)
    End Try
  End Sub

  Function GetActiveDatabaseConnection() As Boolean
    While _ServiceName = Nothing
      Console.Write(“Enter Oracle Service Name:”)
      _ServiceName = Console.ReadLine
    End While
    While _UserName = Nothing
      Console.Write(“Enter Oracle Username:”)
      _UserName = Console.ReadLine
    End While
    While _Password = Nothing
      Console.Write(“Enter Oracle Password:”)
      _Password = Console.ReadLine
    End While
    While _ReportPath = Nothing
      Console.Write(“Enter Oracle Report Path:”)
      _ReportPath = Console.ReadLine
    End While
    Return True
  End Function
 

  Public Function LoadReportFile() As Boolean
    Dim dStart As Date = Now
    Console.WriteLine(dStart.ToLongTimeString & ” – Loading the report file”)
    _ReportDocument = New CrystalDecisions.CrystalReports.Engine.ReportDocument
    Dim reportFullPath As String = System.IO.Path.Combine(_ReportPath, _ReportName)
    If System.IO.File.Exists(reportFullPath) Then
      _ReportDocument.Load(reportFullPath)
    Else
      Console.WriteLine(“Error: could not find “, reportFullPath)
    End If
    Dim dEnd As Date = Now
    Console.WriteLine(“[” & reportFullPath & “] loaded in ” & DateAndTime.DateDiff(DateInterval.Second, dStart, dEnd).ToString & ” second” & Environment.NewLine)
    Return True
  End Function
 

Public Sub SetDatabaseLogonForReport(ByRef reportDocument As CrystalDecisions.CrystalReports.Engine.ReportDocument)
    Dim dStart As Date = Now
    Console.WriteLine(dStart.ToLongTimeString & ” – Logon to tables”)
    Dim crTableLogOnInfo As CrystalDecisions.Shared.TableLogOnInfo
    Dim connectionInfo As CrystalDecisions.Shared.ConnectionInfo = GetConnectionInfo()
    ‘Loop through all tables in the report and apply the connection information for each table.
    For Each crTable As CrystalDecisions.CrystalReports.Engine.Table In reportDocument.Database.Tables
      crTableLogOnInfo = crTable.LogOnInfo
      crTableLogOnInfo.ConnectionInfo = connectionInfo
      crTable.ApplyLogOnInfo(crTableLogOnInfo)
      Console.WriteLine(dStart.ToLongTimeString & ” – ” & crTable.Name)
    Next
    ‘update subreports
    Dim crSubreportObject As CrystalDecisions.CrystalReports.Engine.SubreportObject
    ‘loop through all the sections to find all the report objects
    For Each crSection As CrystalDecisions.CrystalReports.Engine.Section In reportDocument.ReportDefinition.Sections
      ‘loop through all the report objects to find all subreports
      For Each crReportObject As CrystalDecisions.CrystalReports.Engine.ReportObject In crSection.ReportObjects
        If crReportObject.Kind = CrystalDecisions.Shared.ReportObjectKind.SubreportObject Then
          Console.WriteLine(dStart.ToLongTimeString & ” — Subreport: ” & crReportObject.Name)
          crSubreportObject = CType(crReportObject, CrystalDecisions.CrystalReports.Engine.SubreportObject)
          ‘open the subreport and set the database logon for it
          SetDatabaseLogonForReport(crSubreportObject.OpenSubreport(crSubreportObject.SubreportName))
        End If
      Next
    Next
    Console.WriteLine(dStart.ToLongTimeString & ” – Start verifing database”)
    reportDocument.VerifyDatabase()
    Dim dEnd As Date = Now
    Console.WriteLine(“Logon process finished in ” & DateAndTime.DateDiff(DateInterval.Second, dStart, dEnd).ToString & ” second” & Environment.NewLine)
  End Sub

  Private Function GetConnectionInfo() As CrystalDecisions.Shared.ConnectionInfo
    Dim dbAttributes As CrystalDecisions.Shared.DbConnectionAttributes
    Dim crConnectionInfo As CrystalDecisions.Shared.ConnectionInfo = Nothing
    ‘setup the attributes for the connection
    dbAttributes = New CrystalDecisions.Shared.DbConnectionAttributes
    dbAttributes.Collection.Set(“Server”, _ServiceName)
    dbAttributes.Collection.Set(“Trusted_Connection”, False)
    ‘setup the connection
    crConnectionInfo = New CrystalDecisions.Shared.ConnectionInfo
    crConnectionInfo.LogonProperties.Clear()
    crConnectionInfo.Attributes.Collection.Clear()
    crConnectionInfo.DatabaseName = “”
    crConnectionInfo.ServerName = _ServiceName
    crConnectionInfo.UserID = _UserName
    crConnectionInfo.Password = _Password
    crConnectionInfo.Attributes.Collection.Set(“Database DLL”, “crdb_oracle.dll”)
    crConnectionInfo.Attributes.Collection.Set(“QE_DatabaseName”, “”)
    crConnectionInfo.Attributes.Collection.Set(“QE_DatabaseType”, “Oracle Server”)
    crConnectionInfo.Attributes.Collection.Set(“QE_LogonProperties”, dbAttributes)
    crConnectionInfo.Attributes.Collection.Set(“QE_ServerDescription”, _ServiceName)
    crConnectionInfo.Attributes.Collection.Set(“QE_SQLDB”, True)
    crConnectionInfo.Attributes.Collection.Set(“SSO Enabled”, False)
    crConnectionInfo.LogonProperties = dbAttributes.Collection
    Return crConnectionInfo
  End Function

  Public Sub AddReportParameters()
    Dim dStart As Date = Now
    Console.WriteLine(dStart.ToLongTimeString & ” – Add report parameters”)
    Dim strRpt As String = “{TableName.FieldName1} = Value1” & _
    ” AND {TableName.FieldName2} = Value2″

    _ReportDocument.RecordSelectionFormula = strRpt
    _ReportDocument.Refresh()
    Dim dEnd As Date = Now
    Console.WriteLine(“Report parameters added in ” & DateAndTime.DateDiff(DateInterval.Second, dStart, dEnd).ToString & ” second” & Environment.NewLine)
  End Sub
 

Public Sub PrintToPrinter()
    Dim dStart As Date = Now
    Console.WriteLine(dStart.ToLongTimeString & ” – Start to print”)
    If _PrinterAddress Is Nothing Then
      Console.WriteLine(“Error: No printer is entered”)
      Exit Sub
    End If
    Dim pd As New System.Drawing.Printing.PrintDocument
    pd.PrinterSettings.PrinterName = _PrinterAddress.Trim
    If pd.PrinterSettings.IsValid Then
      _ReportDocument.PrintOptions.PrinterName = _PrinterAddress.Trim
      _ReportDocument.PrintOptions.PaperSource = CrystalDecisions.[Shared].PaperSource.Auto
    Else
      Console.WriteLine(“Error: Printer setting is invalid”)
      Exit Sub
    End If
    _ReportDocument.PrintToPrinter(1, False, 0, 0)
    Dim dEnd As Date = Now
    Console.WriteLine(“Print finished in ” & DateAndTime.DateDiff(DateInterval.Second, dStart, dEnd).ToString & ” second” & Environment.NewLine)
  End Sub

End Module

Advertisements
Categories: Crystal Report
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: