Sunday, October 24, 2021

How to Print a Crystal Report Programmatically in ASP.NET?

 You can print a Crystal Report using the print option of Crystal Report Viewer. However, there are occasions when you want your application to print a report directly to the printer without viewing the report in Crystal Report Viewer.

 
The ReportDocument class provides the PrintToPrinter method that may be used to print a CR direct to the printer. If no printer is selected, the default printer will be used to send the printing pages to.
 
The PrintToPrinter method takes four parameters.
 
nCopies : Indicates the number of copies to print.
collated : Indicates whether to collate the pages.
startPageN : Indicates the first page to print.
endPageN : Indicates the last page to print.
 
The following steps will guide you to achieve the same:
  1. Add a crystal report (.cr) file to your ASP.NET application.
  2. Add a report instance on the page level.
    1. Dim report As MyReport = New MyReport 
  1. Populate reports data on Page_Init 
    1. ' Get data in a DataSet or DataTable  
    2.   
    3. Dim ds As DataSet = GetData()  
    4. ' Fill report with the data  
    5. report.SetDataSource(ds) 
  1. Print Report
    1. report.PrintToPrinter(1, False, 0, 0) 
If you wish to print a certain page range, change the last two parameters From To page number.
 
If you want to set page margins, you need to create a PageMargin object and set PrintOptions of the ReportDocument.
 
The following code sets page margins and printer name:
  1. Dim margins As PageMargins =  Report.PrintOptions.PageMargins  
  2.    margins.bottomMargin = 200  
  3.    margins.leftMargin = 200  
  4.    margins.rightMargin = 50  
  5.    margins.topMargin = 100  
  6.    Report.PrintOptions.ApplyPageMargins(margins)  
  7.    
  8.    ' Select the printer name  
  9.    Report.PrintOptions.PrinterName = printerName 

No comments:

Post a Comment

No String Argument Constructor/Factory Method to Deserialize From String Value

  In this short article, we will cover in-depth the   JsonMappingException: no String-argument constructor/factory method to deserialize fro...