iTextSharp PdfPCell Alignment with Chunk

Adam92 picture Adam92 · Jul 30, 2014 · Viewed 8.3k times · Source

I am creating a PDF programmatically using iTextSharp and generating a PdfPTable.

In some of the cells I need to have a hyperlink.

Without a hyperlink I can align the text in the cell horizontally and vertically, however when I add in the chunk which contain my hyperlink, the cell looses its alignment property.

Here is my code...

var webAddress = new Chunk(row["product_code"].ToString(), linkFont);
webAddress.SetAnchor(row["url"].ToString());

PdfPCell ProductCodeCell = new PdfPCell();
ProductCodeCell.AddElement(webAddress);
ProductCodeCell.VerticalAlignment = Element.ALIGN_MIDDLE;
ProductCodeCell.HorizontalAlignment = Element.ALIGN_CENTER;
ProductCodeCell.Padding = 3f;
table.AddCell(ProductCodeCell);

Can anyone help me realign the link?

Many thanks.

Answer

Chris Haas picture Chris Haas · Jul 30, 2014

See this answer for a discussion on Text Mode versus Composite Mode. Basically, if you use AddElement() you need to set the alignment on your object instead of the cell itself. Chunk doesn't have alignment, however, so you need to wrap your chunk in something that does which is the Paragraph.

var table = new PdfPTable(1);

//Create our chunk with anchor
var webAddress = new Chunk("hello");
webAddress.SetAnchor("http://www.example.net/");

//Create a paragraph holding the chunk and set the alignment on _it_
var para = new Paragraph(webAddress);
para.Alignment = Element.ALIGN_CENTER;

//Create our cell
PdfPCell ProductCodeCell = new PdfPCell();

//Add the paragrph to it
ProductCodeCell.AddElement(para);

//Padding on the cell still works
ProductCodeCell.Padding = 30f;

//Add cell to table
table.AddCell(ProductCodeCell);