How to right-align text in a PdfPCell?

Tags: tablesalignmentiText 7

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.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));
Can anyone help?

Posted on StackOverflow on Nov 28, 2012 by colincameron

In iText 7 the following code could help you:

PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
Document doc = new Document(pdfDoc);
Table table = new Table(2);

Cell cell1 = new Cell()
    .add("Item name")

Cell cell2 = new Cell()


This way you define two Cells with different text alignment, different fonts and sizes. If you don’t want to display the border between these columns, use this method:


Another approach is to create a Paragraph instance and use TabStops, as is shown in LeftRight example.

Paragraph p = new Paragraph("Item name")
    .add(new Tab())
    .addTabStops(new TabStop(1000, TabAlignment.RIGHT))
table.addCell(new Cell().add(p));
table.addCell("Some more text...");

I’ve applied both approaches (each one corresponds to the number of row) so the result looks like this. You can choose the method you like more:

Alignments in Cell
Alignments in Cell

Click this link if you want to see how to answer this question in iText 5.