iTextSharp表格单元间距可能吗?

Nic*_*eve 11 pdf itext

在iTextSharp中,是否可以在表格(PdfPTable)中使用单元格间距?我无法看到任何可能的地方.我确实看到了一个使用iTextSharp.text.Table的建议,但在我的iTextSharp版本(5.2.1)上似乎没有.

Chr*_*aas 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

要使用它:

//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);
Run Code Online (Sandbox Code Playgroud)


Ale*_*eon 0

从 5.x 开始,Table 类已从 iText 中删除,取而代之的是 PdfPTable。

至于间距,您正在寻找的是 setPadding 方法。

查看 iText 的 API 了解更多信息:

http://api.itextpdf.com/itext/com/itextpdf/text/pdf/PdfPCell.html

(这是针对 Java 版本的,但 C# 端口保留了方法的名称)

  • 谢谢您,但那是为了添加单元格填充(在单元格内)。我需要的是单元格间距(单元格之间)。 (4认同)