2

How can I add a rectangle with certain width, height and background color into a PdfPCell using itextsharp?

Something like this:

                    PdfPCell cell = new PdfPCell();

                    Rectangle rectangle = new Rectangle();
                    rectangle.Width = 50f;
                    rectangle.BackgroundColor = BaseColor.RED;

                    cell.AddElement(cell);
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
POIR
  • 3,110
  • 9
  • 32
  • 48

1 Answers1

2

The simple answer is: draw the Rectangle as a Form XObject (PdfTemplate), wrap it inside an Image object, and add that image to the table.

However: there are several ways to do this, and there may be only one way that results in the desired output. That's why I've made you an example: rectangle_in_cell.pdf

Take a close look at this PDF. In the top margin you see a line that measures 120 pt in length. In the different tables, you see three rectangles that were created as a rectangle measuring 120 by 80 pt. Only one rectangle seems to have the correct size.

When adding objects to a table, iText often resizes the content to make it fit into a cell. The RectangleInCell example shows you the differences in code between the three approaches. It's written in Java, but I'm sure you'll be able to adapt it to C#.

Christian Davén
  • 16,713
  • 12
  • 64
  • 77
Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165