Search code examples
c#itext7

How to Colorize Selected Rows in an iText Table?


I want to draw a visual distinction between rows based on their content in my iText table.

I found a tutorial here:, but it's in Java instead of C#, and I don't know what version of iText it is for.

I am using iText 7 and it is apparently radically different than previous versions.

I tried using this code from that article:

if ((pod.Doc1Count > 0) && (pod.Doc2Count > 0))
{
    Cell cell = new Cell();
    cell.SetBackgroundColor(Color.DARK_GRAY);
}

...but it won't even compile (the Color class has no definition for DARK_GRAY).

I would much prefer to work with a row at a time, if that's possible, but I don't think it is.

Does anybody know how to change the background color of a row, either all at once, or a cell at a time, using iText 7?

UPDATE

I tried to convert this Java example to C#, but so far no go. This is what I have:

Color headerBg = new DeviceRgb(0xA6, 0xCB, 0x0B);
Color lineColor = new DeviceRgb(0xCC, 0xCC, 0xCC);
. . .
foreach (PairODocs pod in lstPairODocs.OrderByDescending(a => a.Doc1Prcntg).ThenByDescending(a => a.Doc2Prcntg))
{
    if ((pod.Doc1Count > 0) && (pod.Doc2Count > 0))
    {
        Cell cell = new Cell();
        cell.Add(new Paragraph(pod.Whirred));
        cell.SetBackgroundColor(Color.headerBg);
        table.AddCell(cell);
        // TODO: If get it to work, add for the other four vals below, too...
    }
    else // these work, but are plain jane
    {
        table.AddCell(pod.Whirred);
        table.AddCell(pod.Doc1Count.ToString());
        table.AddCell(pod.Doc1Prcntg.ToString());
        table.AddCell(pod.Doc2Count.ToString());
        table.AddCell(pod.Doc2Prcntg.ToString());
    }          
}

...and the compiler says, "Error CS0117 'Color' does not contain a definition for 'headerBg'" on the cell.SetBackgroundColor(Color.headerBg); line.

UPDATE 2

I had an extraneous "Color." preceding "headerBg" which was causing it to not compile. After removing it, it compiles with this code:

if ((pod.Doc1Count > 0) && (pod.Doc2Count > 0))
{
    Cell cell = new Cell();
    cell.Add(new Paragraph(pod.Whirred));
    cell.SetBackgroundColor(headerBg);
    table.AddCell(cell);

    cell = new Cell();
    cell.Add(new Paragraph(pod.Doc1Count.ToString()));
    cell.SetBackgroundColor(headerBg);
    table.AddCell(cell);

    ... // etc.
}

Solution

  • iText.Kernel.Colors.Color bgColour = new DeviceRgb(169, 169, 169);  //Create Darkgray color
    cell.SetBackgroundColor(bgColour);  // Set the color we created to the cell
    

    https://www.rapidtables.com/web/color/gray-color.html Here you can find multiple colors, just choose the one you like and edit the '169, 169, 169' in the example above.