Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ItextSharp horizontal alignment in a pdfptable

Tags:

c#

pdf

itextsharp

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.

like image 414
nam vo Avatar asked Oct 21 '22 10:10

nam vo


1 Answers

You can use :

cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; 

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

like image 79
Maka Avatar answered Oct 23 '22 10:10

Maka