iText

How to right-align text in a PdfPCell?

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:

C#
PdfPTable table = new PdfPTable(2);
table.TotalWidth = invoice.PageSize.Width;
float[] widths = {
  invoice.PageSize.Width - 70 f,
  70 f
};
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

In iText 7 the following code could help you:

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

Cell cell1 = new Cell()
  .add("Item name")
  .setFont(PdfFontFactory.createFont(FontConstants.HELVETICA))
  .setFontSize(16)
  .setTextAlignment(TextAlignment.LEFT)
  .setVerticalAlignment(VerticalAlignment.MIDDLE);
table.addCell(cell1);

Cell cell2 = new Cell()
  .add("price")
  .setFont(PdfFontFactory.createFont(FontConstants.HELVETICA_BOLD))
  .setFontSize(10)
  .setTextAlignment(TextAlignment.RIGHT)
  .setVerticalAlignment(VerticalAlignment.MIDDLE);
table.addCell(cell2);

doc.add(table);
doc.close();

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:

Java
cell.setBorder(Border.NO_BORDER);

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

Paragraph p = new Paragraph("Item name")
  .add(new Tab())
  .addTabStops(new TabStop(1000, TabAlignment.RIGHT))
  .add("price");
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

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