.Net, ASP.NET, C#, iTextSharp, PDF, Programming, Software, Web Development

iTextSharp PdfPCell Text Alignment Example

iTextSharp Table Cells
iTextSharp Table Cells

iTextSharp lets you do some fancy things with table cells that can make your generated PDF documents look exactly the way you want them to. In this example I will expand on a previous article: iTextSharp: PdfPTable Basic Example . Specifically, I will show how to absolutely size your PDF table, how to right and center align Phrase objects in your table cells, and how to horizontally and vertically align text in rotated cells.

Absolutely Sizing a Table in your PDF Document

When you instantiate your table object, iTextSharp likes to assume that it will render as the full width of your PDF document. However you may want to control the width of your table. In the code snippet below you can see the steps involved in setting your table and table cells to be an absolute size:

PdfPTable myTable = new PdfPTable(4);
 // STEP 1: Set the overall width of the table to render
 myTable.TotalWidth = 285f;
 myTable.HorizontalAlignment = 0;
 myTable.SpacingAfter = 10;
 float[] sglTblHdWidths = new float[4];
 sglTblHdWidths[0] = 20f;
 sglTblHdWidths[1] = 15f;
 sglTblHdWidths[2] = 100f;
 sglTblHdWidths[3] = 150f;
 // STEP 2: Set the widths of the table columns
myTable.SetWidths(sglTblHdWidths);
 // STEP 3: Set the table width to not resize
myTable.LockedWidth = true;

From the snippet above, you can see that we are setting the TotalWidth of the PdfPTable right after it is instantiated in Step 1. This width must equal the width of the columns specified as a float array.

Next we populate the table with a float array of column sizes in Step 2 using the iTextSharp SetWidths method.

Finally, we set the table to an absolute size in Step 3 by setting the iTextSharp PdfPTable LockedWidth property to be true.

Horizontally Align a Phrase in your PdfPCell

If you are setting the horizontal alignment of text in an iTextSharp table cell, there is a difference between setting a Phrase and a Paragraph. You can read more about the differences in aligning a Phrase and a Paragraph in the StackOverFlow discussion here.

For the sake of simplicity, we will use an example of a single Phrase in a table cell. If you want to horizontally center align your text, you would  set the HorizontalAlignment property of your cell to Element.ALIGN_CENTER Here is an example of center-aligning text in a cell:

PdfPCell CellTwoHdr = new PdfPCell(new Phrase("cell 2 Hdr", fntTableFontHdr));
 CellTwoHdr.HorizontalAlignment = Element.ALIGN_CENTER;
 myTable.AddCell(CellTwoHdr);

Here is an example of Right-aligning text in a PdfPCell:

PdfPCell CellTreeHdr = new PdfPCell(new Phrase("cell 3 Hdr", fntTableFontHdr));
CellTreeHdr.HorizontalAlignment = Element.ALIGN_RIGHT;
 myTable.AddCell(CellTreeHdr);

Horizontally and Vertically Align a Phrase in a Rotated PdfPCell

Things get a little more interesting when you are rotating one of your table cells, especially if you are spanning several rows and want to control the alignment both vertically and horizontally.The key concept is that no matter how far you rotate your cell, iTextSharp will consider vertical and horizontal directions based on the original cell.

What this means is that if you rotate your cell 90 degrees clockwise and top-align the text in your cell, the cell text will appear horizontally right aligned. Likewise, if you right align your text horizontally and then rotate your cell 90 degrees clockwise, iTextSharp will render the cell text as bottom-aligned.

Here is a code snippet that shows text rotated 90 degrees clockwise that is set to be top-aligned vertically and center aligned horizontally. This code renders the text as horizontally right-aligned and vertically center aligned. Cool!

PdfPCell CellZero = new PdfPCell(new Phrase("ZERO", fntTableFont));
 CellZero.Rotation = -90;
 CellZero.Rowspan = 3;
 CellZero.VerticalAlignment = Element.ALIGN_TOP;
 CellZero.HorizontalAlignment = Element.ALIGN_CENTER;
 myTable.AddCell(CellZero);

The Example Code

Below I’m providing a fully functional example C# WebForm that illustrates the sizing and alignment points I have made in the article above. If you are running the example, it consists of a page with a clickable button. Once the button is clicked, a PDF pops up with a styled iTextSharp table that looks like the screen capture at the start of this article.

<%@ 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(4);
 // Set the overall width of the table to render
 myTable.TotalWidth = 285f;
 myTable.HorizontalAlignment = 0;
 myTable.SpacingAfter = 10;
 float[] sglTblHdWidths = new float[4];
 sglTblHdWidths[0] = 20f;
 sglTblHdWidths[1] = 15f;
 sglTblHdWidths[2] = 100f;
 sglTblHdWidths[3] = 150f;
 // The following two settings are also important to set the overall width of the table to render
myTable.SetWidths(sglTblHdWidths);
myTable.LockedWidth = true;
// We create and set the first column here to span our three rows.
// Note that since we rotated the cell 90 degrees clockwise,
// the vertical alignment: Top actually renders as the horizontal alignment: Right
// and the horizontal alignment: Center renders as the vertical alignment for the middle of the cell
 PdfPCell CellZero = new PdfPCell(new Phrase("ZERO", fntTableFont));
 CellZero.Rotation = -90;
 CellZero.Rowspan = 3;
 CellZero.VerticalAlignment = Element.ALIGN_TOP;
 CellZero.HorizontalAlignment = Element.ALIGN_CENTER;
 myTable.AddCell(CellZero);

PdfPCell CellOneHdr = new PdfPCell(new Phrase(" ", fntTableFontHdr));
 myTable.AddCell(CellOneHdr);
 PdfPCell CellTwoHdr = new PdfPCell(new Phrase("cell 2 Hdr", fntTableFontHdr));
 // The following property sets the cell's alignment to horizontally centered
 CellTwoHdr.HorizontalAlignment = Element.ALIGN_CENTER;
 myTable.AddCell(CellTwoHdr);
 PdfPCell CellTreeHdr = new PdfPCell(new Phrase("cell 3 Hdr", fntTableFontHdr));
 // The following property sets the cell's alignment to right-aligned
CellTreeHdr.HorizontalAlignment = Element.ALIGN_RIGHT;
 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));
 // The following property sets the cell's alignment to horizontally centered
 CellTwo.HorizontalAlignment = Element.ALIGN_CENTER;
 myTable.AddCell(CellTwo);
 PdfPCell CellTree = new PdfPCell(new Phrase("R1 C3", fntTableFont));
 // The following property sets the cell's alignment to right-aligned
 CellTree.HorizontalAlignment = Element.ALIGN_RIGHT;
 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));
 // The following property sets the cell's alignment to horizontally centered
 CellTwoR2.HorizontalAlignment = Element.ALIGN_CENTER;
 myTable.AddCell(CellTwoR2);
 PdfPCell CellTreeR2 = new PdfPCell(new Phrase("R2 C3", fntTableFont));
 // The following property sets the cell's alignment to right-aligned
 CellTreeR2.HorizontalAlignment = Element.ALIGN_RIGHT;
 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 id="Head1" runat="server">
 <title></title>
</head>
<body>
 <form id="form1" runat="server">
<asp:button ID="Button1" runat="server" text="Click to Generate PDF" onclick="Button1_Click" />
 </form>
</body>
</html>
Advertisements

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