Tuesday, October 28, 2008

Export DataTable into PDF with ASP.NET and iTextSharp.DLL

In this article I'll demonstrate how to export your DataTable to PDF file format.

Sometimes it may be the case that you need to export your search result(in tabular format) to a specified file format like .xls, .doc or even .txt. Converting your data to these file format is quite easy and ASP.NET can build it for you internally without letting you worry about any other things.

However, to export your records to .pdf(Adobe's Portable Digital Format) you need to include some third party tool. In the below case i have used " itextSharp.dll " (DLL) component. Which can be downloded from the SourceForge web-site (
http://sourceforge.net).

The following function takes a DataTable as a parameter and converts the data present in it into a PDF File Format in a same tabular view.


using iTextSharp.text;
using iTextSharp.text.pdf;

private void GeneratePDF(DataTable dataTable)
{
Document pdfDoc = new Document(PageSize.A4, 30, 30, 40, 25);
System.IO.MemoryStream mStream = new System.IO.MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, mStream);
int cols = dataTable.Columns.Count;
int rows = dataTable.Rows.Count;
pdfDoc.Open();

iTextSharp.text.Table pdfTable = new iTextSharp.text.Table(cols, rows);
pdfTable.BorderWidth = 1;
pdfTable.Width = 100;
pdfTable.Padding = 1;
pdfTable.Spacing = 1;

//creating table headers
for (int i = 0; i < cols; i++)
{
Cell cellCols = new Cell();
Font ColFont = FontFactory.GetFont(FontFactory.HELVETICA, 12, Font.BOLD);
Chunk chunkCols = new Chunk(dataTable.Columns[i].ColumnName, ColFont);
cellCols.Add(chunkCols);
pdfTable.AddCell(cellCols);

}
//creating table data (actual result)
for (int k = 0; k < rows; k++)
{
for (int j = 0; j < cols; j++)
{
Cell cellRows = new Cell();
Font RowFont = FontFactory.GetFont(FontFactory.HELVETICA, 12);
Chunk chunkRows = new Chunk(dataTable.Rows[k][j].ToString(), RowFont);
cellRows.Add(chunkRows);
pdfTable.AddCell(cellRows);

}
}

pdfDoc.Add(pdfTable);
pdfDoc.Close();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=Report.pdf");
Response.Clear();
Response.BinaryWrite(mStream.ToArray());
Response.End();

}
The above function is dynamic and can accept DataTable of any number of rows and columns.
Please note that "Table" class of DLL "itextSharp" namespace is conflicting with the .NET namespace "Web.UI.HtmlControls". Everything else is fine. That's why i used the complete name of this class.


Sunday, October 26, 2008

ASP.NET Ajax Request/Response using JQuery

Filling ASP.NET DropDown List using jQuery AJAX.

In this example, i'll demonstrate how to implement AJAX functionality on asp:DropDown change event, and to fill the other Dropdown list without using the ScriptManager class (that comes with ASP.NET AJAX Toolkit)

For this case, I'm using a Javascript Library called
jQuery. This must be downloaded and included before using the below source code. (http://jquery.com)

My form contains two DropDowns: Categories(ddlCategories) and Items(ddlItems). OnChange of the Category DropDown I will fill the Items DropDown.
<form id="form1" runat="server">
<asp:DropDownList ID="ddlCategories" runat="server">
<asp:ListItem>Select</asp:ListItem>
<asp:ListItem>Fruits</asp:ListItem>
<asp:ListItem>Vegetables</asp:ListItem>
<asp:ListItem>Desserts</asp:ListItem>
</asp:DropDownList>
<br />
<asp:DropDownList ID="ddlItems" runat="server"></asp:DropDownList>
</form>
    Here is my ASP.NET Desing View of the Form which shows these DropDowns. I have hardcoded the first DropDown with Categories: Fruits, Vegetables and Desserts. The Items DropDown is empty initially, since we will fill these through jQuery AJAX, when the onChange event of the Category DropDown will be fired.
    The Best thing is that we do not have to register any JavaScript Event with any control using our code behind file [ddlCategories.Attributes.Add()],  jQuery has the functionality where we can write our own onChange Event function. So here is my jQuery Code in which I will write the onChange function of the Categories DropDownList and call a C# function (or implement my AJAX) and then finally fill the Items DropDown.

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">

$(document).ready(function(){

$("#<%=ddlCategories.ClientID %>").change(
function()
{
var category = this.options[this.selectedIndex].value;
var ddlItems = document.getElementById("<%=ddlItems.ClientID%>");
ddlItems.options.length = 0;
$.ajax
({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/getItems",
data: "{'category':'"+category+"'}",
dataType: "json",
success: function(msg)
{
var arrItems = msg.d.split("|");
for(var i=0; i< arrItems.length; i++)
{
var opt = document.createElement("option");
ddlItems.options.add(opt)
opt.text = arrItems[i];
opt.value = arrItems[i];
}
}
});
}
);
});
</script>
Any jQuery implementation should be inside $(document).ready() function. This is the root function that is called everytime any event occurs on our page. In the above code we have written our onChange function inside this [ as $("#ddlCategories").change() ]. Inside this function we are catching up the item that is selected. The actual request for a C# function or AJAX function can be done through jQuery's $.ajax() function. This function takes 6 parameters that can be explained as follows:
1.  type: this is the Request type that we are going to make. Normally it is of type post.
2.  contenType: ASP.NET AJAX script services and page methods understand and expect parameters serialized as JSON strings. These parameters are parsed out of the POST data and used as arguments to the method you’ve called.
3.  url: This contains the url of the page that will handle our AJAX request and provide the response. Notice here we have defined our url as Default.aspx/getItems. The first element before slash(/) contains the page name and the second item is the actual function name that will process the request in this case its getItems. 
4. data: This option defines the parameters that have to be passed (if any) to the function on the basis of which our request will be processed. In this case we are passing the selected value of the Category dropDown. Also its worth noting that the parameter name of this option should match the parameter of the function that we are going to call. In this case its 'category'
5. dataType: this option defines the type of Data that will be returned to us when the request is processed successfully. In this case its JSON (JavaScript Object Notation).
6. success: this option is an indication of a successful request processed and response. In this function we will define a function that will process the response (i.e. fill the Items dropDown). As you'll look at the C# code below, we are appending the items using a bar( | ), coz if there are multiple items we need to handle them in response. Here we are finally splitting the response string and finally handling each of them separately by storing them in the Items DropDown list.

Finally here is the C# Code Behind function that will handle my Request, Process it and Response back the output. Currently I have hard coded mr response. We can also make a database request and finally append each of the items using a bar ( | ) and response back the string (output).
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

[System.Web.Services.WebMethod]
public static string getItems(string category)
{
string strItems = "";
if (category == "Fruits")
{
strItems = "Apple|Orange|Pinapple|Grapes";
}
else if (category == "Vegetables")
{
strItems = "Tomato|Cauliflower|Brinjal|Potato";
}
else if (category == "Desserts")
{
strItems = "Cakes|Cookies|IceCreams|Pastries";
}
return strItems;
}
}