This is default featured post 1 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured post 2 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured post 3 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured post 4 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured post 5 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

Crystal Reports

In this example i m going to describe how to create crystal reports in ASP.NET.

In this i am generating report by fetching data from two tables and grouping them based on Project Name. Database tables are just for demo purpose you can create your own tables with whatever schema you want
Two tables are as shown below.


Create a new website and right click on solution explorer > add new Item > Select Crystal Report
In the dialog box choose blank report.

 
Now click on CrystalReports Menu in VS and select DataBase Expert 
  
In database expert dialog box expend create new connection > OLEDB(ADO) section
 
Now select SQL Native client and enter you SQL server address , username , password and pick database name from the dropdown. 
 
  
In next screen Expend your database objects in left pane and add the tables you want to use in right pane 
 

Link your tables based on Primary keys (If any)

Click ok to finish the wizard.
Right click on Field Explorer and select Group Name Fields  > Insert Group

In next box select the field you to report to be grouped (in my case it's ProjectsName)

Click on OK to finish
Now design the report , drag and fields from Database fields in field explorer and which you want to show in report and drop them in Section3(Details), and preview the report, it should look like show below.



Go to default.aspx page and drag and drop CrystalReportViewer from the toolbox, click on smart tag and choose new report source.

Choose you report from the dropdown menu and click ok to finish.
Now when you build and run the sample , it asks for the database password everytime.

 
To fix this we need to load the report programmatically and provide username and password from code behind .
Now run the report , it should look like this 


 


Html markup of default.aspx look like

<form id="form1" runat="server"> <div>   <CR:CrystalReportViewer ID="CrystalReportViewer1"                            runat="server" AutoDataBind="True"                           Height="1039px"                            ReportSourceID="CrystalReportSource1"                            Width="901px" />   <CR:CrystalReportSource ID="CrystalReportSource1"                            runat="server">             <Report FileName="CrystalReport.rpt">             </Report>    </CR:CrystalReportSource>          </div>     </form>


C# code behind

Write this code in the event you find appropriate , i m writing it in Page_Load , you can write this code in click event of button or in pagePreRender event
The code to provide password programmatically.

protected void Page_Load(object sender, EventArgs e)     {         ReportDocument crystalReport = new ReportDocument();         crystalReport.Load(Server.MapPath("CrystalReport.rpt"));         crystalReport.SetDatabaseLogon             ("amit", "password", @"AMIT\SQLEXPRESS", "TestDB");         CrystalReportViewer1.ReportSource = crystalReport;     }


VB.NET code behind

Protected Sub Page_Load (ByVal sender As Object, ByVal e As EventArgs)  Dim crystalReport As New ReportDocument()  crystalReport.Load(Server.MapPath("CrystalReport.rpt"))  crystalReport.SetDatabaseLogon ("amit", "password", "AMIT\SQLEXPRESS", "TestDB")  CrystalReportViewer1.ReportSource = crystalReport  End Sub


Hope this helps

export to Excel,Word or PDFs with out thirdparty tools in ASP.NET.


Many times we would like to export our page as an Excel sheet, Word doc or PDF file. This can be simply achieved by changing the ContentType of the Response object and overriding the RenderControl method of the control to be exported:


Page Load()
{
 //bind data to data bound controls and do other stuff


Response.Clear();

//this clears the Response of any headers or previous output
Response.Buffer = true; //make sure that the entire output is rendered simultaneously

///
///Set content type to MS Excel sheet
///Use "application/msword" for MS Word doc files
///"application/pdf" for PDF files
///

Response.ContentType =

"application/vnd.ms-excel";
StringWriter stringWriter = new StringWriter(); //System.IO namespace should be used

HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);

///
///Render the entire Page control in the HtmlTextWriter object
///We can render individual controls also, like a DataGrid to be
///exported in custom format (excel, word etc)
///
this.RenderControl(htmlTextWriter);
Response.Write(stringWriter.ToString());
Response.End();
} //end page load

For exporting ASP.NET pages as PDF files, you need to know the Adobe PDF specs for generating the PDf correctly. There is already a wonderful component which does the same and its free! See this article along with sample source code on how to export a page to PDF:


http://www.codeproject.com/cs/library/giospdfnetlibrary.asp


http://itextsharp.sourceforge.net/tutorial/index.html


Hope this would be helpful...!

Grid View to Pdf Exporting using ITextSharp dll


Introduction:

In one of the previous articles we demonstrated how to export a GridView to excel. In this article we will demonstrate how to export GridView to PDF format using the ITextSharp library.

Creating the Entity Class:

Let's create a simple entity class "Customer" and populate it with some dummy data. The Customer class looks like the following:

01  public class Customer
02     {
03         private string _firstName;
04         private string _lastName;
05         private string _email;
06         public string FirstName
07         {
08             get { return _firstName; }
09             set { _firstName = value; }
10         }
11         public string LastName
12         {
13             get { return _lastName; }
14             set { _lastName = value; }
15         }
16         public string FullName
17         {
18             get { return _firstName + " " + _lastName; }
19         }
20         public string Email
21         {
22             get { return _email; }
23             set { _email = value; }
24         }
25     }


Now, let's create a GridView control and poppulate it with the dummy Customer objects.

01 <asp:GridView BackColor="Green" ID="gvCustomers" runat="server" />
02  private void BindData()
03         {
04             gvCustomers.DataSource = GetCustomers();
05             gvCustomers.DataBind();
06         }
07         private List<Customer> GetCustomers()
08         {
09             List<Customer> customers = new List<Customer>();
10             for (int i = 1; i <= 20; i++)
11             {
12                 Customer customer = new Customer();
13                 customer.FirstName = "FirstName" + i;
14                 customer.LastName = "LastName" + i;
15                 customer.Email = "Email" + i;
16                 customers.Add(customer);
17             }
18             return customers;
19         }


The above code will populate the GridView with dummy Customers. Take a look at the screenshot of the GridView below:



Now, let's try to export this GridView to PDF.

How *NOT* to Export a GridView to PDF:

Here is the code which is used to export GridView to PDF.

01   protected void WrongExportGridViewToPDF(object sender, EventArgs e)
02         {
03             Response.Clear();
04              
05             StringWriter sw = new StringWriter();
06             HtmlTextWriter htw = new HtmlTextWriter(sw);
07             gvCustomers.RenderControl(htw);
08              
09             Response.ContentType = "application/pdf";
10             Response.AddHeader("content-disposition", "attachment; filename=MypdfFile.pdf");
11             Response.Write(sw.ToString());
12             Response.End();
13         }


When you export the GridView to PDF using the above code it will seem that the export is taking place correctly but when you try to open the file you will realize that the file is corrupted. Although this particular code works when exporting to Excel or Text files this code will fail when exporting to PDF files. To export GridView to PDF we will need to use a third party library ITextSharp. Let's see how we can use this library.

Downloading the ITextSharp Library:

You can download the ITextSharp library using the following link:

ITextSharp Library

The library is also included in the download sample files.

Exporting the GridView to Excel Using ITextSharp and ResponseOutputStream:

We are going to use the ITextSharp library to write the document to the ResponeOutputStream. Let's take a look at the code:

01  protected void ExportToPDFClick(object sender, EventArgs e)
02         {
03             Response.Clear();
04             StringBuilder sb = new StringBuilder();
05             StringWriter sw = new StringWriter(sb);
06             HtmlTextWriter htw = new HtmlTextWriter(sw);
07             gvCustomers.RenderControl(htw);
08             Response.ContentType = "application/pdf";
09             Response.AddHeader("content-disposition", "attachment; filename=MypdfFile.pdf");
10             Document document = new Document();
11             PdfWriter.GetInstance(document, Response.OutputStream);
12             document.Open();
13             string html = sb.ToString();
14             XmlTextReader reader = new XmlTextReader(new StringReader(html));
15             HtmlParser.Parse(document, reader);
16             document.Close();
17             sw.Close();
18             Response.Flush();
19             Response.End();
20         }


The above code is using the Document object which represents a Pdf document. The GridView is rendered into the HtmlTextWriter. The HtmlTextWriter uses the support of StringWriter and StringBuilder to get the HTML for the GridView control. The PdrWriter.getInstance is used to set the Document instance to the Stream which in this case is the Response Stream. The HtmlParser class is responsible for parsing the rendered GridView HTML. This is responsible for creating a table display for the PDF document. If we omit the use of HtmlParser then the raw HTML will be displayed in the Pdf document.

Take a look at the screenshot below which shows the GridView as a Pdf Document:



As, you can see the Pdf document is poorly styled and the table cells are of variable length. Let's see how we can improve the Table cell rendering.

Creating Pdf Document Using ITextSharp Tables:

The ITextSharp library includes the Table class which is used to create Tables in PdfDocuments. We will use the Table class to improve our display.

The button click will fire the following event:

1   protected void ExportCollectionToPDFClick(object sender,EventArgs e)
2         {
3             ExportToPDFCollection(new string[] { "FirstName", "LastName", "FullName" });
4         }


The ExportToPDFCollection method is responsible for creating the Table using the Customer collection. It takes a single parameter which is the names of the columns we will want to export to the Pdf document.

Here is the implementation of the ExportToPDFCollection method:

01  private void ExportToPDFCollection(string[] columnNames)
02         {
03             List<Customer> customers = GetCustomers();
04             int noOfColumns = columnNames.Length;
05             int noOfRows = customers.Count;
06             string propertyValue = String.Empty;
07              
08             iTextSharp.text.Table table = new iTextSharp.text.Table(noOfColumns, noOfRows);
09             table.BackgroundColor = new iTextSharp.text.Color(gvCustomers.BackColor);
10              
11             table.AutoFillEmptyCells = true;
12             for (int rowNo = 0; rowNo < noOfRows; rowNo++)
13             {
14                 for (int columnNo = 0; columnNo < noOfColumns; columnNo++)
15                 {
16                     propertyValue = GetPropertyValue(customers[rowNo], columnNames[columnNo]);
17                     table.AddCell(propertyValue, new Point(rowNo, columnNo));
18                 }
19             }
20             Document document = new Document();
21             PdfWriter.GetInstance(document, Response.OutputStream);
22             document.Open();
23             document.Add(table);
24             document.Close();
25             Response.ContentType = "application/pdf";
26             Response.AddHeader("content-disposition", "attachment; filename=MypdfFile.pdf");
27             Response.End();
28         }


The above code creates the Table and append cells to the Table. Each cell is populated with the particular propertyname of the Customer class. The GetPropertyValue method uses reflection to get the value from the property.

1   private string GetPropertyValue(Customer customer,string propertyName)
2         {
3             PropertyInfo property = customer.GetType().GetProperty(propertyName);
4             return property.GetValue(customer, null).ToString();
5         }


Here is the result:



Although the resultant Pdf document is not pretty but you can always make adjustments to make it better. Also note that the cells are property listed.

Conclusion:

In this article we learned how to export GridView to Pdf. We discussed different ways of performing this operation. In the future articles we will try to demonstrate how to customize the display of the exported Pdf document.

[Download Sample]

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites