'How do I round the corners of an iTextSharp table border?
I want to make a round rectangle in itextsharp. Here is the output I have now without rounding:
and here is my code that processes that output:
pdftbl = new PdfPTable(3);
pdftbl.WidthPercentage = 100;
width = new float[3];
width[0] = 0.6F;
width[1] = 0.2F;
width[2] = 0.6F;
pdftbl.SetWidths(width);
pdfcel = new PdfPCell(new Phrase(Insuredaddress, docFont9));
pdfcel.BorderColor = Color.BLACK;
pdftbl.AddCell(pdfcel);
pdfcel = new PdfPCell(new Phrase("", docWhiteFont9));
pdfcel.Border = 0;
pdftbl.AddCell(pdfcel);
pdfcel = new PdfPCell(new Phrase(BkrAddrss, docFont9));
pdfcel.BorderColor = Color.BLACK;
pdftbl.AddCell(pdfcel);
objDocument.Add(pdftbl);
What can I change/add to achieve the desired result?
Solution 1:[1]
iText[Sharp] doesn't have this functionality out of the box. It's a roundabout way of doing things, but first you have to implement the IPdfPCellEvent interface, and second attach the event handler to each cell you add to the table. First a simple implementation:
public class RoundRectangle : IPdfPCellEvent {
public void CellLayout(
PdfPCell cell, 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();
}
}
See the PdfContentByte documentation - basically all the code above does is draw a cell border with round corners like you want.
Then assign the event handler created above like this:
RoundRectangle rr = new RoundRectangle();
using (Document document = new Document()) {
PdfWriter writer = PdfWriter.GetInstance(document, STREAM);
document.Open();
PdfPTable table = new PdfPTable(1);
PdfPCell cell = new PdfPCell() {
CellEvent = rr, Border = PdfPCell.NO_BORDER,
Padding = 4, Phrase = new Phrase("test")
};
table.AddCell(cell);
document.Add(table);
}
Solution 2:[2]
Given that at least in Itext 7 it is only possible to draw a border on a table by setting it on cells, you can configure its radius as follows:
var cell = new Cell();
cell.SetBorderBottomLeftRadius(new BorderRadius(4f));
Setting border radius on a table makes no effect:
var table = new Table(2);
table.SetBorderBottomLeftRadius(new BorderRadius(4f)); // No border is drawn
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Artur |