iTextSharp表格单元格间距是否可以调整?

11

在 iTextSharp 的 PdfPTable 中是否可以设置单元格之间的间距?我没有看到任何可以实现这一功能的地方。有人建议使用 iTextSharp.text.Table,但我使用的 iTextSharp 版本(5.2.1)好像没有这个选项。

2个回答

15

如果你想要类似HTML的真正单元格间距,那么PdfPTable是不支持的。不过,PdfPCell支持一个属性,该属性接受IPdfPCellEvent的自定义实现,每当发生单元格布局时就会调用它。下面是一个简单的实现示例,你可能需要根据自己的需求进行调整。

public class CellSpacingEvent : IPdfPCellEvent {
    private int cellSpacing;
    public CellSpacingEvent(int cellSpacing) {
        this.cellSpacing = cellSpacing;
    }
    void IPdfPCellEvent.CellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) {
        //Grab the line canvas for drawing lines on
        PdfContentByte cb = canvases[PdfPTable.LINECANVAS];
        //Create a new rectangle using our previously supplied spacing
        cb.Rectangle(
            position.Left + this.cellSpacing,
            position.Bottom + this.cellSpacing,
            (position.Right - this.cellSpacing) - (position.Left + this.cellSpacing),
            (position.Top - this.cellSpacing) - (position.Bottom + this.cellSpacing)
            );
        //Set a color
        cb.SetColorStroke(BaseColor.RED);
        //Draw the rectangle
        cb.Stroke();
    }
}

使用方法:

//Create a two column table
PdfPTable table = new PdfPTable(2);
//Don't let the system draw the border, we'll do that
table.DefaultCell.Border = 0;
//Bind our custom event to the default cell
table.DefaultCell.CellEvent = new CellSpacingEvent(2);
//We're not changing actual layout so we're going to cheat and padd the cells a little
table.DefaultCell.Padding = 4;
//Add some cells
table.AddCell("Test");
table.AddCell("Test");
table.AddCell("Test");
table.AddCell("Test");

doc.Add(table);

0

4
谢谢,但是那是用来添加单元格内边距的。我需要的是单元格间距(即单元格之间的距离)。 - Nick Reeve

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接