Search code examples
c#alignmentitexttabularpdfptable

Multiple Table Column alignment in iTextsharp


I am creating a table where each column has its own alignment as shown below. How do I accomplish it at column level than at cell level?

enter image description here


Solution

  • iText and iTextSharp don't support column styles and formatting. The only way to do this is as you are doing currently, cell by cell.

    EDIT

    The easiest work around is to create helper methods that set your common properties. These can either be done through extension methods or just regular static methods. I don't have a C# IDE in front of me so my sample code below is in VB but should translate fairly easily.

    You can create a couple of quick methods for each alignment:

    Public Shared Function CreateLeftAlignedCell(ByVal text As String) As PdfPCell
        Return New PdfPCell(New Phrase(text)) With {.HorizontalAlignment = PdfPCell.ALIGN_LEFT}
    End Function
    Public Shared Function CreateRightAlignedCell(ByVal text As String) As PdfPCell
        Return New PdfPCell(New Phrase(text)) With {.HorizontalAlignment = PdfPCell.ALIGN_RIGHT}
    End Function
    Public Shared Function CreateCenterAlignedCell(ByVal text As String) As PdfPCell
        Return New PdfPCell(New Phrase(text)) With {.HorizontalAlignment = PdfPCell.ALIGN_CENTER}
    End Function
    

    Or just a single one that you have to pass in one of the known constants:

    Public Shared Function CreatePdfPCell(ByVal text As String, ByVal align As Integer) As PdfPCell
        Return New PdfPCell(New Phrase(text)) With {.HorizontalAlignment = align}
    End Function
    

    Then you can just do the following:

    Dim T As New PdfPTable(3)
    T.AddCell(CreateCenterAlignedCell("Hello"))