Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I round the corners of an iTextSharp table border?

Tags:

c#

itext

I want to make a round rectangle in itextsharp. Here is the output I have now without rounding:

enter image description here

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?

like image 810
Neeraj Avatar asked Apr 22 '12 19:04

Neeraj


1 Answers

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);
}
like image 87
kuujinbo Avatar answered Oct 22 '22 14:10

kuujinbo