表嵌套到PDFPCELL在itextsharp

本文关键字:itextsharp PDFPCELL 嵌套 | 更新日期: 2023-09-27 18:17:34

我想给表格添加圆角边框,但是经过研究我发现这是不可能的,但是我们可以给单元格添加圆角边框。

所以我做了这样的操作

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

现在我可以给一个单元格边框所以我想做的是,我想把我的完整嵌套表到这个pdfpcell中,这样我就可以间接地在那个表上实现边框…

你能帮忙吗?如果你不明白我的方法,请提问,我将在评论区更清楚地解释…

表嵌套到PDFPCELL在itextsharp

RoundRectangle类逐字使用kuujinbo的代码:

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();
    }
}

您只需要一个"外部"和一个"内部"表,并且只将CellEvent放在外部表上。

//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);