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);
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#.