5

I try to align the cell content in a pdf table using ItextSharp. Somehow, it doesn't work at all, it's always aligned on the left.

     var pageSize = PageSize.A4;

        if (_pdfSettings.LetterPageSizeEnabled)
        {
            pageSize = PageSize.LETTER;
        }


        var doc = new Document(pageSize);
        PdfWriter.GetInstance(doc, stream);
        doc.Open();

        //fonts     

        var normalFont = GetFont();

            normalFont.Color = BaseColor.BLACK;
            normalFont.Size = 14;

       //..titlefont, smallfont,largefont....

         var addressTable = new PdfPTable(1);
         addressTable.WidthPercentage = 100f;

         cell = new PdfPCell();

         cell.AddElement(new Paragraph("Người Gửi", titleFont));
         cell.AddElement(new Paragraph("TAKARA.VN", largeFont));

         cell.HorizontalAlignment = Element.ALIGN_RIGHT;

         addressTable.AddCell(cell);

         doc.Add(addressTable);
         doc.Add(new Paragraph("", normalFont));

Updated: I found an answer

You are confusing text mode and composite mode.

Text mode:

Phrase p = New Phrase("value");
PdfPCell cell = new PdfPCell(p);
cell.HorizontalAlignment = Element.ALIGN_CENTER;
table.AddCell(cell);

Composite mode:

PdfPCell cell = New PdfPCell();
Paragraph p = New Paragraph("value");
p.Alignment = Element.ALIGN_CENTER;
cell.AddElement(p);
table.AddCell(cell);

In text mode the alignment of the cell is used. In composite mode (triggered by using AddElement(), the alignment of the cell is ignored in favor of the alignment of the elements added to the cell.

Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165
nam vo
  • 3,271
  • 12
  • 49
  • 76
  • *Updated: I found an answer* - Please make that an actual answer or (if you found that answer here on stack overflow) mark your question as a duplicate of the question of that answer. – mkl Jun 12 '17 at 15:02

3 Answers3

4

You can use :

cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; 

Or you can align using numbers: 0=Left, 1=Centre, 2=Right

Leonardo Alves Machado
  • 2,747
  • 10
  • 38
  • 53
Maka
  • 43
  • 1
  • 6
0

I do it like this, and it works for me:

cell.HorizontalAlignment = 1;
shA.t
  • 16,580
  • 5
  • 54
  • 111
0

I dont know if this is relevant but check if the rundirection is rtl , if it is you have to remove that parameter. Else it will override align components.

Ps using itextsharp 5