Thursday, December 22, 2011

Export Crystal Reports to PDF file

Reports are used by business for various management purposes. Crystal reports is very versatile and easy to use reporting tool that is bundled with the Microsoft Visual Studio .Net. There have been many enhancements in the latest version of crystal reports which make it simpler for developers to export reports directly to the HTTP response object.

The export option is very useful when business users want to have reports exported different formats such as PDF, Excel, Word and HTML. They want this facility in order to download the report and store it for future use or to modify the report further (possible in case of Word and Excel). In many cases the export option is used for scheduled reports to be send via email, In this case, the exporting is done on the server side and the exported file is attached to an email and send to the user's email id.
In this tutorial, I will be showing you how to export a report to PDF format, but it can be easily modified to export the report in other formats.

Create a Crystal Report and display to the user

Create a New ASP.NET Web Site Project

I will be using an XML file as the data source for this tutorial. In normal scenarios a business layer class would return a dataset or datatable containing data to be displayed in the report. So I created an XML file with customer data and will be reading the contents into a Dataset.

Add XML file to the Project

Right-Click on App_Data folder and select Add Existing Item
Browse to the XML file and select it:

Add a crystal report to the project

Right-Click on the website root and select Add New Item.
Select "Crystal Report".
Enter the name of the report, I used the default name given by the IDE.
When the Crystal report wizard comes up select "Standard" and click OK.
Select a data source for the report.
Expand the Create New Connection node and then expand the ADO.net option.
Browse to the XML file and select the file.
The Customers table will appear in the list of data sources, add the table to selected table list by clicking on the right arrow.
Select all the columns that you need to display in the reports. I selected all of them for simplicity.
Setup grouping as needed to display the report.
Setup fields available for filtering.
Select the layout of report that you want.
The report is now created, you can now change the layout, add logos, etc.

Display the report on a web page

In the design view drag and drop the crystal reports viewer from Toolbox onto the web page.
Add a button which will handle the displaying of the report.
The HTML for body of the webpage should like as follows:
<body>
<formid="form2"runat="server">
<div>
<asp:ButtonID="btnShow"runat="server"OnClick="btnShow_Click"Text="Show Report in Viewer" /><br/>
<br/>
<CR:CrystalReportViewerID="CrystalReportViewer1"runat="server"AutoDataBind="true"/>
</div>
</form>
</body>
Remember to add following namespaces at the top of code behind page for referencing Crystal Report objects.
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
The event handler should looks as follows:
protectedvoid btnShow_Click(object sender, EventArgs e)
{
// Get the report document and bind it with the crystal report viewer
CrystalReportViewer1.ReportSource = getReportDocument();
CrystalReportViewer1.DataBind();
}

// Returns a ReportDocument object with the report and data loaded
private ReportDocument getReportDocument()
{
// File Path for Crystal Report
string repFilePath = Server.MapPath("CrystalReport.rpt")
// Declare a new Crystal Report Document object
// and the report file into the report document
ReportDocument repDoc = new ReportDocument();
repDoc.Load(repFilePath);
// Set the datasource by getting the dataset from business
// layer and
// In our case business layer is getCustomerData function
repDoc.SetDataSource(getCustomerData());
}

// Business layer class to get the data from database
private DataSet getCustomerData()
{
string customerFilePath = Server.MapPath("App_Data\\Customers.xml");
DataSet ds =new DataSet();
ds.ReadXml(customerFilePath);
}
Run the Project to see if if works.

Export the Crystal Report in PDF format

Add a button to the web page so that user can click and get the PDF.

The HTML for web page should looks as follows:
<body>
<formid="form2"runat="server">
<div>
<asp:ButtonID="btnShow"runat="server"OnClick="btnShow_Click"Text="Show Report in Viewer" /><br/>
<br/>
<asp:ButtonID="btnExport"runat="server"OnClick="btnExport_Click"Text="Export To PDF"/>
<br/>
<br/>
<CR:CrystalReportViewerID="CrystalReportViewer1"runat="server"AutoDataBind="true"/>
</div>
</form>
</body>
The Code behind for export is as follows:
protectedvoid btnExport_Click(object sender, EventArgs e)
{
// Get the report document
ReportDocument repDoc = getReportDocument();
// Stop buffering the response
Response.Buffer =false;
// Clear the response content and headers
Response.ClearContent();
Response.ClearHeaders();
try
{
// Export the Report to Response stream in PDF format and file name Customers
repDoc.ExportToHttpResponse(ExportFormatType.PortableDocFormat,Response,true,"Customers");
// There are other format options available such as Word, Excel, CVS, and HTML in the ExportFormatType Enum given by crystal reports
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
ex =null;
}
}

Export to other formats

The report can be exported in different formats as follow:
PDFExportFormatType.PortableDocFormat
Complete Report to ExcelExportFormatType.Excel
Only Report Data to ExcelExportFormatType.ExcelRecord
HTMLExportFormatType.HTML40
RTFExportFormatType.RichText
WordExportFormatType.WordForWindows
Run the project to see does it working.
Once you click on the Export the PDF button the dialog box to download the pdf file will appear.
Now open the file and see if it is displayed properly.
By the end if this tutorial you should be able to

1) Create simple crystal reports
2) Display it to a web page using a crystal reports viewer
3) Allow users to download the reports in various formats such as PDF, Excel, Word and HTML.
You can download Sample Export Crystal Report To PDF Visual Studio Project, used in this tutorial.
Many people found that Crystal Reports are complicate to learn. Personally, I like Stimulsoft Reports for ASP.NET application. If you use SQL Server, nice solution is ApexSQL Report.
This tutorial is written by Chirag Nirmal - CANSoft.

No comments:

Post a Comment