Introduction
iTextSharp is a rich code library to create PDF. I decided to use it for a client and there were no good examples available on internet for the beginners and i did a lot of permutations and combinations to get a Output. I want to share my piece of code with beginners using this library
Using the code
In This article i would discuss how to export a Gridview in PDF format and add header, image to the PDF. Basically i would be discussing Proper Formating of A PDF according to the clients demand.
First of all download iTextSharp java Freely available library(DLL file)(Attached in the article below, place it into the bin folder and include it into your project.
Code:
<asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/App_Themes/images/icon/pdf.jpg"
ToolTip="Download Excel" OnClick="ImageButton2_Click" CssClass="PDF_download" />
Image Button OnClick of which GridView will be converted to PDF. If you are using update panel then dont forget to add a trigger to this button else the code will not work.
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" CellPadding="4"
DataSourceID="ObjectDataSource1" ForeColor="#333333" GridLines="Vertical" Visible="false">
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<Columns>
<asp:BoundField DataField="dfode" HeaderText="adf" SortExpression="dfode" />
<asp:BoundField DataField="bsid" HeaderText="BS" SortExpression="bsid" />
<asp:BoundField DataField="cityName" HeaderText="SSA" SortExpression="cityName" />
<asp:BoundField DataField="total_duration" HeaderText="Dur(Minutes)" SortExpression="total_duration" />
<asp:BoundField DataField="btNo" HeaderText="BT NO" SortExpression="btNo" />
<asp:BoundField DataField="btLocation" HeaderText="LOCATION" SortExpression="btLocation" />
<asp:BoundField DataField="bcNo" HeaderText="BC NO" SortExpression="bcNo" />
<asp:BoundField DataField="btType" HeaderText="BT TYPE" SortExpression="btType" />
</Columns>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<EmptyDataTemplate>
No Available Data In This Category...
</EmptyDataTemplate>
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
GridView which will be converted to PDF using iTextSharp Librabry, Table can also be converted to PDF with slight changes in the code. Basically you only need to know the control well then you can convert it into the PDF. I am taking GridView.
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
Including the iTextSharp Library in aspx.cs file.
protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
{
Document pdfReport = new Document(PageSize.A4, 15, 15, 40, 30);
System.IO.MemoryStream msReport = new System.IO.MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(pdfReport, msReport);
pdfReport.Open();
PdfPTable ptData = new PdfPTable(GridView2.Rows[0].Cells.Count);
ptData.SpacingBefore = 8;
ptData.DefaultCell.Padding = 1;
float[] headerwidths = new float[GridView2.Rows[0].Cells.Count]; for (int intK = 0; intK < GridView2.Rows[0].Cells.Count; intK++)
{
if (GridView2.HeaderRow.Cells[intK].Text.ToUpper().Contains("BTS ID") || GridView2.HeaderRow.Cells[intK].Text.ToUpper().Contains("LOC"))
headerwidths[intK] = (100 / (GridView2.Rows[0].Cells.Count + 2)) * 2;
else
headerwidths[intK] = 100 / (GridView2.Rows[0].Cells.Count + 2);
}
ptData.SetWidths(headerwidths);
ptData.WidthPercentage = 100;
ptData.DefaultCell.HorizontalAlignment = Element.ALIGN_JUSTIFIED;
ptData.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;
for (int intK = 0; intK < GridView2.Rows[0].Cells.Count; intK++)
{
PdfPCell cell = new PdfPCell();
cell.BorderWidth = 0.001f;
cell.BackgroundColor = BaseColor.LIGHT_GRAY;
cell.BorderColor = BaseColor.BLACK;
cell.Phrase = new Phrase(GridView2.HeaderRow.Cells[intK].Text, FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI,8,iTextSharp.text.Font.BOLD));
ptData.AddCell(cell);
}
ptData.HeaderRows = 1;
for (int intJ = 0; intJ < GridView2.Rows.Count; intJ++)
{
for (int intK = 0; intK < GridView2.Rows[0].Cells.Count; intK++)
{
PdfPCell cell = new PdfPCell();
cell.BorderWidth = 0.001f;
cell.BorderColor = BaseColor.BLACK;
cell.BackgroundColor = BaseColor.WHITE;
if(GridView2.Rows[intJ].Cells[intK].Text != " ")
cell.Phrase = new Phrase(GridView2.Rows[intJ].Cells[intK].Text, FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 9));
else
cell.Phrase = new Phrase("", FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 5));
ptData.AddCell(cell);
}
}
string imageFilePath = Server.MapPath("~/App_Themes/images/pdfheader.gif");
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imageFilePath);
img.ScaleToFit(80f, 60f);
img.SpacingBefore = 100F;
img.SpacingAfter = 100F;
img.Alignment = Element.ALIGN_MIDDLE;
Chunk firstline = new Chunk("Codescape Consultants PVt Ltd", FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 7, iTextSharp.text.Font.BOLD));
Chunk secondline = new Chunk("(A Pvt Ltd Company)", FontFactory.GetFont(FontFactory.HELVETICA, 5));
Chunk thirdline = new Chunk("In Jaipur", FontFactory.GetFont(FontFactory.HELVETICA,5));
Chunk fourthline = new Chunk("Rajasthan", FontFactory.GetFont(FontFactory.HELVETICA, 5));
Chunk fifthline = new Chunk("Date: " + DateTime.Now.ToString("dd/MMM/yyyy"), FontFactory.GetFont(FontFactory.HELVETICA, 5));
Phrase left_top = new Phrase();
left_top.Add(firstline + "\n");
left_top.Add(secondline + "\n");
left_top.Add(thirdline + "\n");
left_top.Add(fourthline + "\n");
left_top.Add(fifthline);
Paragraph para = new Paragraph();
para.Add(left_top);
para.Alignment = Element.ALIGN_RIGHT;
string bottom = "\n This is the string for the bottom part where the Table ends, it will be the note etc which you want to put @ end of the PDf \n\n";
Paragraph bottom_para = new Paragraph(bottom,FontFactory.GetFont(FontFactory.HELVETICA,7));
Paragraph company = new Paragraph("Codescape Consultants Pvt Ltd", FontFactory.GetFont(FontFactory.HELVETICA, 5));
company.Alignment = Element.ALIGN_RIGHT;
Chunk ch = new Chunk("Outage Report between " + stdateHF.Value + " To " + etdateHF.Value + " OFF Period >= " + periodHF.Value, FontFactory.GetFont(FontFactory.HELVETICA, 7, iTextSharp.text.Font.UNDERLINE));
pdfReport.Add(img);
pdfReport.Add(para);
pdfReport.Add(new Phrase(ch));
pdfReport.Add(ptData);
pdfReport.Add(bottom_para);
pdfReport.Add(company);
pdfReport.Close();
Response.Clear();
Response.AppendHeader("content-disposition", "attachment;filename=Export.pdf");
Response.Charset = "";
Response.ContentType = "application/pdf";
Response.BinaryWrite(msReport.ToArray());
Response.End();
}
Above code is written OnClick event of the image button. I will break it into clusters and try to explain all the minor details.
Code Explanation:
Cluster 1:
Document pdfReport = new Document(PageSize.A4, 15, 15, 40, 30);
System.IO.MemoryStream msReport = new System.IO.MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(pdfReport, msReport);
pdfReport.Open();
Create a Document, i took it in A4 size there are other options also, with margin from left, right, top, bottom also create a memorystream and a Pdfwriter to write in the document.
Cluster 2:
PdfPTable ptData = new PdfPTable(GridView2.Rows[0].Cells.Count);
ptData.SpacingBefore = 8;
ptData.DefaultCell.Padding = 1;
float[] headerwidths = new float[GridView2.Rows[0].Cells.Count]; for (int intK = 0; intK < GridView2.Rows[0].Cells.Count; intK++)
{
if (GridView2.HeaderRow.Cells[intK].Text.ToUpper().Contains("BTS ID") || GridView2.HeaderRow.Cells[intK].Text.ToUpper().Contains("LOC"))
headerwidths[intK] = (100 / (GridView2.Rows[0].Cells.Count + 2)) * 2;
else
headerwidths[intK] = 100 / (GridView2.Rows[0].Cells.Count + 2);
}
ptData.SetWidths(headerwidths);
ptData.WidthPercentage = 100;
ptData.DefaultCell.HorizontalAlignment = Element.ALIGN_JUSTIFIED;
ptData.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;
for (int intK = 0; intK < GridView2.Rows[0].Cells.Count; intK++)
{
PdfPCell cell = new PdfPCell();
cell.BorderWidth = 0.001f;
cell.BackgroundColor = BaseColor.LIGHT_GRAY;
cell.BorderColor = BaseColor.BLACK;
cell.Phrase = new Phrase(GridView2.HeaderRow.Cells[intK].Text, FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI,8,iTextSharp.text.Font.BOLD));
ptData.AddCell(cell);
}
ptData.HeaderRows = 1;
for (int intJ = 0; intJ < GridView2.Rows.Count; intJ++)
{
for (int intK = 0; intK < GridView2.Rows[0].Cells.Count; intK++)
{
PdfPCell cell = new PdfPCell();
cell.BorderWidth = 0.001f;
cell.BorderColor = BaseColor.BLACK;
cell.BackgroundColor = BaseColor.WHITE;
if(GridView2.Rows[intJ].Cells[intK].Text != " ")
cell.Phrase = new Phrase(GridView2.Rows[intJ].Cells[intK].Text, FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 9));
else
cell.Phrase = new Phrase("", FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 5));
ptData.AddCell(cell);
}
}
Basically what i am doing is making elements separately and then adding them into the PDF together, Eg: Table, paragraph, chunks etc are elements and they can be created separately with different formats and then finally they can be clubbed into a PDF.
First of All I will explain how to make a table(PdfPTable type), this elements is withing the iTextSharp Librabry. PdfPtable can be broken into two parts which is header rows and normal row, In a general scenario we want header to be repeated on every page(If Page changes), this is done in the code.
In the first for loop we will decide the width of the columns, if in case we need some columns to be broader then the other then we can do so as i did for "LOCATION" and "BTS ID". It can be done for description or any type of explanation.
After that we assign value to the header cells as per the grid header row, in this we do a bit of formating also, like making the things bold, choosing fonts etc.
After that we assign values to the normal rows and format them also. We keep adding cells to the rows and adding rows to the table once the table is complete we will add it to the PDF.
Cluster 3:
string imageFilePath = Server.MapPath("~/App_Themes/images/pdfheader.gif");
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imageFilePath);
img.ScaleToFit(80f, 60f);
img.SpacingBefore = 100F;
img.SpacingAfter = 100F; img.Alignment = Element.ALIGN_MIDDLE;
Now we will make another kind of element ie image element, u can add images to the PDF by using above code. Get the Image file path from your folder and then format it ie scaling, spacing, aligment. Our Image element(img) is ready.
Cluster 4:
Chunk firstline = new Chunk("Codescape Consultants PVt Ltd", FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 7, iTextSharp.text.Font.BOLD));
Chunk secondline = new Chunk("(A Pvt Ltd Company)", FontFactory.GetFont(FontFactory.HELVETICA, 5));
Chunk thirdline = new Chunk("In Jaipur", FontFactory.GetFont(FontFactory.HELVETICA,5));
Chunk fourthline = new Chunk("Rajasthan", FontFactory.GetFont(FontFactory.HELVETICA, 5));
Chunk fifthline = new Chunk("Date: " + DateTime.Now.ToString("dd/MMM/yyyy"), FontFactory.GetFont(FontFactory.HELVETICA, 5));
Phrase left_top = new Phrase();
left_top.Add(firstline + "\n");
left_top.Add(secondline + "\n");
left_top.Add(thirdline + "\n");
left_top.Add(fourthline + "\n");
left_top.Add(fifthline);
Paragraph para = new Paragraph();
para.Add(left_top);
para.Alignment = Element.ALIGN_RIGHT;
Another element is Paragraph, we can directly create a Paragraph as done in the code below this code but in case if we want a Paragraph with different fonts and formatting in each line we will use chunk and then we will add them to make a phrase and then finally a paragraph and this element can be directly added to the PDF.
pdfReport.Add(img);
pdfReport.Add(para);
pdfReport.Add(ptData);
Finally we are adding all the elements created into a PDF they will appear in the order they are added, image first, paragraph second and finally the table ie Gridview.
pdfReport.Close();
Response.Clear();
Response.AppendHeader("content-disposition", "attachment;filename=Export.pdf");
Response.Charset = "";
Response.ContentType = "application/pdf";
Response.BinaryWrite(msReport.ToArray());
Response.End();
Close the document, and transmit it to the end user. The PDF created will be downloaded to the end user. If there are any doubts or if someone needs more clarification on any part please let me know. Comments Invited
The Code is well documented according to me and if there are any problem we can discuss them on the discussion/comment thread.
Hope this will help.
Points of Interest
If you are using a Update panel then don,t forget to add a trigger to the image button otherwise the code will not work. This is just a basic idea of how to use iTextSharp class. Advance Tutorial about this will come soon from my side.
History
Elaborated
File
Download itextsharp-5.0.0-dll.zip - 1.06 MB