Search code examples
itextpdfptable

DefaultCell properties are not used in my pdf created with iTextSharp


I use iTextSharp v5.5.6

I'm creating a large table. To be consistent in my layout I want to use the DefaultCell class to set some default settings like font, padding and alignment. I'm not doing something correct because the settings are not applied to my cells.

Here's some code:

var table = new PdfPTable(2) 
  { KeepTogether = true, TotalWidth = printWidth, LockedWidth = true,
    HorizontalAlignment = 0, SpacingBefore = 0, SpacingAfter = 15f };
// Set default values:
table.DefaultCell.Colspan = 1;
table.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
table.DefaultCell.Padding = 5f;
table.DefaultCell.PaddingLeft = 5f;
table.DefaultCell.PaddingBottom = 5f;
table.DefaultCell.VerticalAlignment = Element.ALIGN_BOTTOM;
table.DefaultCell.BorderWidthBottom = 0f;
table.DefaultCell.Phrase = new Phrase { Font = Blue11BoldFont };
table.DefaultCell.Border = Rectangle.NO_BORDER; 

table.AddCell(new PdfPCell(new Phrase("Foo")) 
  { HorizontalAlignment = Element.ALIGN_CENTER, MinimumHeight = 20f });
table.AddCell(new PdfPCell(new Phrase("Bar", Black10BoldFont)) 
  { Colspan = 4, HorizontalAlignment = Element.ALIGN_CENTER });

I would have expected my first cell would use my blue font and padding is applied. But nothing is applied. In fact when I remove the DefaultCell lines I get the same result.

I've been searching for hours now and most samples I've found use something similar. Any suggestion is much appreaciated.


Solution

  • You are creating PdfPCell objects yourself. In that case, the default cell is always ignored.

    See What is the PdfPTable.DefaultCell property used for?

    When creating a PdfPTable, you add cells.

    • One way is to create a PdfPCell object and to add that cell with the addCell() method. In this case, you are responsible to define the properties of each individual cell.
    • Another way is to use a short-cut: you don't create a PdfPCell, but you add a String or a Phrase to the table with the addCell() method. In this case, a PdfPCell is created internally using default properties. You can change the default properties by changing the properties of the default cell. The default cell is obtained using the getDefaultCell() method.

    This is not a bug, this is by design. You are misinterpreting the meaning of the concept of the "default cell". Note that this concept was explained in the free ebook The Best iText Questions on StackOverflow.

    If you want to be consistent in your layout, the best way to do this, is by creating your own createCell() method that creates a PdfPCell to which you apply all the properties for which you were using the default cell.