【问题标题】:iTextSharp Table Cell Spacing Possible?iTextSharp 表格单元格间距可能吗?
【发布时间】:2012-04-19 15:44:13
【问题描述】:

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

【问题讨论】:

    标签: pdf itext


    【解决方案1】:

    如果您正在寻找像 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);
    

    【讨论】:

      【解决方案2】:

      从 5.x 开始,表类已从 iText 中删除,以支持 PdfPTable。

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

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

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

      (是Java版本,但是C#端口维护了方法的名称)

      【讨论】:

      • 谢谢你,但那是为了添加单元格填充(在单元格内)。我需要的是单元格间距(单元格之间)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-18
      • 2017-01-20
      相关资源
      最近更新 更多