James Raitsev
James Raitsev

Reputation: 96371

How to set a background color of a Table Cell using iText?

While it is of course possible to use BaseColor, by default, it offers very limited choices.

I wonder how can i add my own custom color to the document?

...
        PdfPTable table = new PdfPTable(3);

        PdfPCell cell = new PdfPCell(new Phrase("some clever text"));
        cell.setBackgroundColor(BaseColor.GREEN);
        table.addCell(cell);
...

Upvotes: 32

Views: 88091

Answers (4)

Tony Chen
Tony Chen

Reputation: 31

Try this:
cell.setBackgroundColor(new BaseColor(226, 226, 226));
or:
cell.setBackgroundColor(WebColors.getRGBColor("#E2E2E2")); deprecated

Upvotes: 3

James Raitsev
James Raitsev

Reputation: 96371

Posting, in hopes someone else will find this response useful.

It seems one can create a new BaseColor from WebColor as:

BaseColor myColor = WebColors.GetRGBColor("#A00000");

Which then can be added as a background as:

cell.setBackgroundColor(myColor);

Upvotes: 51

Mark Storer
Mark Storer

Reputation: 15868

Lots of options.

BaseColor color = new BaseColor(red, green, blue); // or red, green, blue, alpha
CYMKColor cmyk = new CMYKColor(cyan, yellow, magenta, black); // no alpha
GrayColor gray = new GrayColor(someFloatBetweenZeroAndOneInclusive); // no alpha

There's also pattern colors and shading colors, but those are Much Less Simple.

Upvotes: 34

Sagar Shah
Sagar Shah

Reputation: 4292

One more solution is:

public static String mColor = "#aa8cc5";
int aa = Integer.parseInt(mColor,16); // base 16
int colorArr = Color.rgb(Color.red(aa),Color.green(aa),Color.blue(aa));
cell1.setBackgroundColor(new BaseColor(colorArr));

Upvotes: 0

Related Questions