iTextSharp表格单元间距可能吗? [英] iTextSharp Table Cell Spacing Possible?

查看:138
本文介绍了iTextSharp表格单元间距可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to have cell spacing within a table (PdfPTable) in iTextSharp? I can't see anywhere that it is possible. I did see one suggestion of using the iTextSharp.text.Table instead but that doesn't seem available on my version of iTextSharp (5.2.1).

推荐答案

如果你正在寻找像HTML那样的真正的单元格间距,那么 PdfPTable 本身就不支持。但是, PdfPCell 支持一个属性,该属性采用 IPdfPCellEvent 的自定义实现,每当单元格布局发生时都会调用它。下面是一个简单的实现,您可能希望根据需要调整它。

If you're looking for true cell spacing like HTML's then no, the PdfPTable doesn't support that natively. However, the PdfPCell supports a property that takes a custom implementation of IPdfPCellEvent which will get called whenever a cell layout happens. Below is a simple implementation of one, you'll probably want to tweak it to your needs.

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

这篇关于iTextSharp表格单元间距可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆