Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Horizontal text alignment in a PdfPCell

I am using this code to align horizontally.

cell = New PdfPCell();
p = New Phrase("value");
cell.AddElement(p);
cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; //Tried with Element.Align_Center Also. Tried Adding this line before adding element also. 
table.AddCell(cell);

It's not working.

I am creating a table with 5 columns in it and adding cells dynamically in runtime in a for loop with above code. I want all cells content to be centered.

like image 598
yogesh420 Avatar asked Aug 13 '13 01:08

yogesh420


People also ask

How do I align text horizontally?

To align text horizontally on a page, highlight the text you want to center. Next, click the “Center Alignment” icon in the “Paragraph” group of the “Home” tab. Alternatively, you can use the Ctrl+E keyboard shortcut. Your text will now be horizontally aligned.

What is the horizontal alignment of text in a cell?

The correct answer is Left. Users can change the horizontal alignment of the cell of an MS Excel worksheet as per requirement. By default MS Excel aligns the text to the left of an MS Excel worksheet. It also aligns numbers to the right of an MS Excel worksheet.


1 Answers

I tried all the above solutions and none worked. Then I tried this and that led me to the correct solution

PdfPCell c2 = new PdfPCell(new iTextSharp.text.Phrase("Text")) { HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER };
table.AddCell(c2);

I know it's not required from the OP but you can also have several words centered if separated with \n. Additionally you can also vertically center with Element.ALIGN_MIDDLE

With all that the code is:

PdfPCell c2 = new PdfPCell(new iTextSharp.text.Phrase("AAAAAAAAA\nBBBBBB")) { HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE };
table.AddCell(c2);

and the result:

enter image description here

Hope it helps

like image 143
Patrick Avatar answered Sep 21 '22 20:09

Patrick