ankit sharma
ankit sharma

Reputation: 449

Table nested into PDFPCELL in itextsharp

I want to give rounded border to a table but after research i found it can't be done but we can give rounded border to a cell..

so i done something like this

PdfPCell cell = new PdfPCell()
{
     CellEvent = rr, // rr is RoundRectangle object
     Border = PdfPCell.NO_BORDER,
     Padding = 4,
     Phrase = new Phrase("test")
};
table.AddCell(cell);
document.Add(table);

Now i can give border to a cell so what i want to do is i want to place my complete nested table into this pdfpcell so that i can acheive border indirectly on that table...

Can you help on this? If you didn't understand my approach..ask questions..i ll explain more clearly on comments section...

Upvotes: 4

Views: 5589

Answers (1)

Chris Haas
Chris Haas

Reputation: 55427

Using kuujinbo's code verbatim for the RoundRectangle class:

public class RoundRectangle : IPdfPCellEvent {
    public void CellLayout(
      PdfPCell cell, iTextSharp.text.Rectangle rect, PdfContentByte[] canvas
    ) {
        PdfContentByte cb = canvas[PdfPTable.LINECANVAS];
        cb.RoundRectangle(
          rect.Left,
          rect.Bottom,
          rect.Width,
          rect.Height,
          4 // change to adjust how "round" corner is displayed
        );
        cb.SetLineWidth(1f);
        cb.SetCMYKColorStrokeF(0f, 0f, 0f, 1f);
        cb.Stroke();
    }
}

You then just need an "outer" and an "inner" table and only put the CellEvent on the outer table.

//Create a one column table
var outerTable = new PdfPTable(1);

//Create a single cell for that outer table
var outerCell = new PdfPCell();

//Turn the border off for that cell because we're manually going to draw one
outerCell.Border = iTextSharp.text.Rectangle.NO_BORDER;

//Bind our custom class for drawing the borders
outerCell.CellEvent = new RoundRectangle();


//Do whatever we want with the inner table
var innerTable = new PdfPTable(3);
for (var i = 0; i < 9; i++) {
    innerTable.AddCell("Hello");
}

//When done, add the inner table to the outer cell
outerCell.AddElement(innerTable);

//Add the outer cell to the outer table
outerTable.AddCell(outerCell);

//Add the outer table to the document
doc.Add(outerTable);

Upvotes: 5

Related Questions