0

Is there any way, how to change default table's iTextSharp font and cell's color? I have a table, where I can change a font, but that would have to be done on every single cell - which is very unfortunate. Most probably there is a better way, but I haven't found it.

The reason I want to do this change is, that default font does not support Czech characters.

I have following code:

PdfPTable subTable = new PdfPTable(4);
Font bigFont = FontFactory.GetFont("c:\\windows\\fonts\\arial.ttf", BaseFont.IDENTITY_H, 8, Font.NORMAL, BaseColor.RED);
PdfPCell subCell = new PdfPCell(new Phrase("Bělení fáze 1",bigFont));
subCell.BackgroundColor = new BaseColor(196, 231, 234);
subTable.AddCell(subCell);
subTable.AddCell("Test");

First printed cell is going to have defined font - arial, as well as cell's color. Second cell will have all in default.

I also tried following command, but that did not help at all:

subTable.DefaultCell.Phrase = new Phrase() { Font = bigFont };

Thanks for any hints.

Izmail360
  • 69
  • 2
  • 11

2 Answers2

0

Need to split them into separate chunks that use different Font and add them to a phase and then add them to the PdfPTable as a cell. See here: iTextSharp - Is it possible to set a different font color for the same cell and row?

Community
  • 1
  • 1
Casey O'Brien
  • 407
  • 2
  • 6
  • 15
0

I had the same problem and came accross this old question. While iTextSharp is deprecated and replaced by iText 7, I had to use the old iTextSharp. For anyone in the same position, here is what I ended up with.

Like the original asker, I first tried to achieve it that way, which - in my opinion - would be intuitive:

var table = new PdfPTable(4);  // <- use wrapper class here
table.DefaultCell.Phrase = new Phrase() { Font = myDefaultFont };

which obviously doesn't work. But you can make it work by writing a wrapper class for PdfPTable and overriding its AddCell(string text) like this

public class MyPdfTable : PdfPTable
{
    public new void AddCell(string text)
    {
        Phrase defaultPhrase = DefaultCell.Phrase;
        Phrase phrase = defaultPhrase == null ? new Phrase(text) : new Phrase(text, defaultPhrase.Font);
        base.AddCell(phrase);

        // for some reason iTextSharp sets this to null after AddCell() is called, so we restore it
        DefaultCell.Phrase = defaultPhrase;
    }

One could implement this as an extension method for PdfPTable as well, but I ended up with the above solution since I was working with legacy code. That way the only thing I had to change was the type when newing the table up and not each and every call to AddCell().

Hope it helps anyone.

Danno
  • 31
  • 6