How to right-align text in a PdfPCell?

Category: 
Tags: composite modetext modetablesalignmentiText 5

I have a C# application that generates a PDF invoice. In this invoice is a table of items and prices. This is generated using a PdfPTable and PdfPCells.

I want to be able to right-align the price column but I cannot seem to be able to: the text always comes out left-aligned in the cell.

Here is my code for creating the table:

PdfPTable table = new PdfPTable(2);
table.TotalWidth = invoice.PageSize.Width;
float[] widths = { invoice.PageSize.Width - 70f, 70f };
table.SetWidths(widths);
table.AddCell(new Phrase("Item Name", tableHeadFont));
table.AddCell(new Phrase("Price", tableHeadFont));
SqlCommand cmdItems = new SqlCommand("SELECT...", con);
using (SqlDataReader rdrItems = cmdItems.ExecuteReader())
{
    while (rdrItems.Read())
    {
        table.AddCell(new Phrase(rdrItems["itemName"].ToString(), tableFont));
        double price = Convert.ToDouble(rdrItems["price"]);
        PdfPCell pcell = new PdfPCell();
        pcell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
        pcell.AddElement(new Phrase(price.ToString("0.00"), tableFont));
        table.AddCell(pcell);
    }
}
Can anyone help?

Posted on StackOverflow on Nov 28, 2012 by colincameron

You're mixing text mode and composite mode.

In text mode, you create the PdfPCell with a Phrase as the parameter of the constructor, and you define the alignment at the level of the cell. However, you're working in composite mode. This mode is triggered as soon as you use the addElement() method. In composite mode, the alignment defined at the level of the cell is ignored (which explains your problem). Instead, the alignment of the separate elements is used.

How to solve your problem?

Either work in text mode by adding your Phrase to the cell in a different way. Or work in composite mode and use a Paragraph for which you define the alignment.

The advantage of composite mode over text mode is that different paragraphs in the same cell can have different alignments, whereas you can only have one alignment in text mode. Another advantage is that you can add more than just text: you can also add images, lists, tables,... An advantage of text mode is speed: it takes less processing time to deal with the content of a cell.