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.
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.
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.
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:
Hope it helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With