iTextSharp: PdfPTable Basic Example

In this article I will give fully functioning examples in C# and VB.NET of using the iTextSharp Pdf library of objects to create a simple tabular report. Below I’ve added an image of what the report will look like.

iTextSharp Example Report

iTextSharp Example Report

Note that if you work directly with the iTextSharp PDF object library, you have much finer control over the formatting of elements on the report than you do if you are using the iTextSharp XMLWorkerHelper object to convert an HTML/CSS report to a PDF.

So, for example, in the report for this article I have rotated the text in the first column to save space. This is a feature that is commonly used when writing reports, but which is not part of the CSS supported by the  iTextSharp XMLWorkerHelper object.

If you are interested in finding out more about what CSS is supported by the XMLWorkerHelper object, then take a look at this CSS conformance grid on the iTextSharp Web site. You will see that only the most basic styling is supported. Unfortunately this likely means that you will not be able to simply feed your HTML reports directly into PDF format, but will have to re-code them to output to PDF using the custom iTextSharp library of objects.

Check out my other articles on the subject if you are interested in more articles about generating PDF documents in .NET

Background Information About the Following Examples

Below I’m  providing a fully functioning example in both C# and VB.NET of using the iTextSharp library of objects to generate a PDF document. The overall steps are:

  1. Import the iTextSharp .NET libraries
  2. Instantiate an instance of the iTextSharp Document object
  3. Set up a PDFWriter object to write the PDF document to the Web Server
  4. Set up and populate a PdfTable object to output your report data
  5. Add the PDfTable to the Document object and close the Document
  6. Register a JavaScript popup window to display the newly generated PDF document

This report assumes that you have a sub-folder on your Web site called Reports, and the PDF is then saved as a unique time-stamp based document in the Reports directory.

This example also shows how to set the PDF table to the full width of the document using the table object’s WidthPercentage attribute.

You should note that unlike with an HTML table, you must set the PDF table column widths when the table is being instantiated, rather than for each cell. This is done using an array of float values

When  you are populating the PDF Table object, there is no concept of a Row object, you simply start adding table cell objects. A new row is created when the number of cells added exceeds the number of columns set while instantiating the table. So you will need to keep a close watch on the number of cells that you add while generating your PDF table.

This example also shows you how you can rotate text in your PDF table object by rotating the cell itself using the Rotation attribute. In this example the Rotation attribute is set to -90, which rotates the text 90 degrees clockwise (so the text ends up reading downwards).

Alternately you can set the Rotation attribute to positive 90 degrees, which ends up rotating the text counter-clockwise.

I set the SpacingAfter attribute to the table to ensure that there is a bit of white-space after the table for readability reasons. This is especially important if you were to follow up your table with text or another table.

Alternately if you want a new page to start after your table, simply call the NewPage() method of the Document object after you have added the table.

C# Example Report

<%@ Page Language="C#" %>
<%@ Import Namespace="iTextSharp.text.pdf" %>
<%@ Import Namespace="iTextSharp.text" %>
<%@ Import Namespace="System.IO" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
 protected void Button1_Click(object sender, EventArgs e)
 {
 iTextSharp.text.Font fntTableFontHdr = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
 iTextSharp.text.Font fntTableFont = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
 string strReportName = "myPdf" + DateTime.Now.Ticks + ".pdf";
 Document doc = new Document(iTextSharp.text.PageSize.LETTER, 5, 10, 20, 20);
 string pdfFilePath = Server.MapPath(".") + "\\Reports\\";
 PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(pdfFilePath + strReportName, FileMode.Create));
 doc.Open();
PdfPTable myTable = new PdfPTable(3);
 // Table size is set to 100% of the page
 myTable.WidthPercentage = 100;
 //Left aLign
 myTable.HorizontalAlignment = 0;
 myTable.SpacingAfter = 10;
 float[] sglTblHdWidths = new float[3];
 sglTblHdWidths[0] = 15f;
 sglTblHdWidths[1] = 200f;
 sglTblHdWidths[2] = 385f;
 // Set the column widths on table creation. Unlike HTML cells cannot be sized.
 myTable.SetWidths(sglTblHdWidths);
PdfPCell CellOneHdr = new PdfPCell(new Phrase(" ", fntTableFontHdr));
 myTable.AddCell(CellOneHdr);
 PdfPCell CellTwoHdr = new PdfPCell(new Phrase("cell 2 Hdr", fntTableFontHdr));
 myTable.AddCell(CellTwoHdr);
 PdfPCell CellTreeHdr = new PdfPCell(new Phrase("cell 3 Hdr", fntTableFontHdr));
 myTable.AddCell(CellTreeHdr);
PdfPCell CellOne = new PdfPCell(new Phrase("R1 C1", fntTableFont));
 CellOne.Rotation = -90;
 myTable.AddCell(CellOne);
 PdfPCell CellTwo = new PdfPCell(new Phrase("R1 C2", fntTableFont));
 myTable.AddCell(CellTwo);
 PdfPCell CellTree = new PdfPCell(new Phrase("R1 C3", fntTableFont));
 myTable.AddCell(CellTree);
PdfPCell CellOneR2 = new PdfPCell(new Phrase("R2 C1", fntTableFont));
 CellOneR2.Rotation = -90;
 myTable.AddCell(CellOneR2);
 PdfPCell CellTwoR2 = new PdfPCell(new Phrase("R2 C2", fntTableFont));
 myTable.AddCell(CellTwoR2);
 PdfPCell CellTreeR2 = new PdfPCell(new Phrase("R2 C3", fntTableFont));
 myTable.AddCell(CellTreeR2);
doc.Add(myTable);
 doc.Close();
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "myscript", "window.open('Reports/" + strReportName + "','MyPDFDocument','toolbar=1,location=1,status=1,scrollbars=1,menubar=1,resizable=1,left=10,top=10,width=860,height=640');", true);
 }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title></title>
</head>
<body>
 <form id="form1" runat="server">
<asp:button ID="Button1" runat="server" text="Button" onclick="Button1_Click" />
 </form>
</body>
</html>

VB.NET Example Report

In the code below I’m providing the VB.NET version of the iTextSharp example report that is given in C# above.

<%@ Page Language="VB" %>
<%@ Import Namespace="iTextSharp.text.pdf" %>
<%@ Import Namespace="iTextSharp.text" %>
<%@ Import Namespace="System.IO" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
 Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
 Dim fntTableFontHdr As iTextSharp.text.Font = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.BOLD, BaseColor.BLACK)
 Dim fntTableFont As iTextSharp.text.Font = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK)
 Dim strReportName As String = "myPdf" & DateTime.Now.Ticks & ".pdf"
 Dim doc As New Document(iTextSharp.text.PageSize.LETTER, 5, 10, 20, 20)
 Dim pdfFilePath As String = Server.MapPath(".") & "\Reports\"
 Dim wri As PdfWriter = PdfWriter.GetInstance(doc, New FileStream(pdfFilePath & strReportName, FileMode.Create))
 doc.Open()

 Dim myTable As New PdfPTable(3)
 myTable.WidthPercentage = 100 ' Table size is set to 100% of the page
 myTable.HorizontalAlignment = 0 'Left aLign
 myTable.SpacingAfter = 10
 Dim sglTblHdWidths(2) As Single
 sglTblHdWidths(0) = 15
 sglTblHdWidths(1) = 200
 sglTblHdWidths(2) = 385
 myTable.SetWidths(sglTblHdWidths) ' Set the column widths on table creation. Unlike HTML cells cannot be sized.

 Dim CellOneHdr As New PdfPCell(New Phrase(" ", fntTableFontHdr))
 myTable.AddCell(CellOneHdr)
 Dim CellTwoHdr As New PdfPCell(New Phrase("cell 2 Hdr", fntTableFontHdr))
 myTable.AddCell(CellTwoHdr)
 Dim CellTreeHdr As New PdfPCell(New Phrase("cell 3 Hdr", fntTableFontHdr))
 myTable.AddCell(CellTreeHdr)

 Dim CellOne As New PdfPCell(New Phrase("R1 C1", fntTableFont))
 CellOne.Rotation = -90
 myTable.AddCell(CellOne)
 Dim CellTwo As New PdfPCell(New Phrase("R1 C2", fntTableFont))
 myTable.AddCell(CellTwo)
 Dim CellTree As New PdfPCell(New Phrase("R1 C3", fntTableFont))
 myTable.AddCell(CellTree)

 Dim CellOneR2 As New PdfPCell(New Phrase("R2 C1", fntTableFont))
 CellOneR2.Rotation = -90
 myTable.AddCell(CellOneR2)
 Dim CellTwoR2 As New PdfPCell(New Phrase("R2 C2", fntTableFont))
 myTable.AddCell(CellTwoR2)
 Dim CellTreeR2 As New PdfPCell(New Phrase("R2 C3", fntTableFont))
 myTable.AddCell(CellTreeR2)

 doc.Add(myTable)
 doc.Close()

 ScriptManager.RegisterStartupScript(Me.Page, Me.GetType(), "myscript", "window.open('Reports/" & strReportName & "','MyPDFDocument','toolbar=1,location=1,status=1,scrollbars=1,menubar=1,resizable=1,left=10,top=10,width=860,height=640');", True)
 End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title></title>
</head>
<body>
 <form id="form1" runat="server">
<asp:button ID="Button1" runat="server" text="Button" onclick="Button1_Click" />
 </form>
</body>
</html>
About these ads

One thought on “iTextSharp: PdfPTable Basic Example

  1. Pingback: iTextSharp PdfPCell Text Alignment Example « Justin Cooney

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s