Search code examples
vb.netitextreporting

itextsharp colspan formatting issues


I was trying to create ItextSharp Table the table format is driving me crazy

here is the code I have it's very simple so far

 Dim objTable As PdfPTable = New PdfPTable(3) 
  objTable.AddCell("1")
    objTable.AddCell("2")
    objTable.AddCell("3")


    Dim xp As Phrase = New Phrase("1.5 A")
    Dim x As PdfPCell = New PdfPCell(xp)
    x.Colspan = 1.5
    objTable.AddCell(x)

    Dim yp As Phrase = New Phrase("1.5 B")
    Dim y As PdfPCell = New PdfPCell(yp)
    y.Colspan = 1.5
    objTable.AddCell(y)

And this generate the following table

enter image description here

Question Is what is the best way -if there is any - to make row two having equal columns

and make them like this

enter image description here right in the middle?


Solution

  • Turn Option Strict On and you should see your first problem, Colspan takes integers only.

    The only way that I can think of is to split it up into even more columns like we used to do in HTML table days. There's two basic way, either go with the least common multiple of the column counts (6) or divide the center column into two smaller columns. Personally I prefer the first approach since I think its a little cleaner.

    ''//Create a 6 column table with each column have about 16.666667%
    Dim T1 As New PdfPTable(6)
    ''//For three across we span 2
    T1.AddCell(New PdfPCell(New Phrase("1")) With {.Colspan = 2})
    T1.AddCell(New PdfPCell(New Phrase("2")) With {.Colspan = 2})
    T1.AddCell(New PdfPCell(New Phrase("3")) With {.Colspan = 2})
    ''//For two across we span 3
    T1.AddCell(New PdfPCell(New Phrase("1.5A")) With {.Colspan = 3})
    T1.AddCell(New PdfPCell(New Phrase("1.5B")) With {.Colspan = 3})
    
    Doc.Add(T1)
    
    ''//Create a 4 column table with the center columns have half the width of the outer columns
    Dim T2 As New PdfPTable({2, 1, 1, 2})
    ''//Add a normal cell
    T2.AddCell(New PdfPCell(New Phrase("1")))
    ''//Add a cell that spans the two "smaller" columns
    T2.AddCell(New PdfPCell(New Phrase("2")) With {.Colspan = 2})
    ''//Add a normal cell
    T2.AddCell(New PdfPCell(New Phrase("3")))
    ''//In this row we need a full normal column plus one of the half columns
    T2.AddCell(New PdfPCell(New Phrase("1.5A")) With {.Colspan = 2})
    T2.AddCell(New PdfPCell(New Phrase("1.5B")) With {.Colspan = 2})
    
    Doc.Add(T2)