nam vo
nam vo

Reputation: 3447

ItextSharp horizontal alignment in a pdfptable

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.

Upvotes: 6

Views: 21152

Answers (3)

AtomicFlee
AtomicFlee

Reputation: 17

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

Upvotes: 0

Maka
Maka

Reputation: 53

You can use :

cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; 

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

Upvotes: 5

shA.t
shA.t

Reputation: 16968

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

cell.HorizontalAlignment = 1;

Upvotes: 0

Related Questions