iTextSharp Table Cell Spacing Possible?

2019-02-09 04:24发布

问题:

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

回答1:

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

To use it:

//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:

The Table class has been removed from iText starting from 5.x, in favor of PdfPTable.

As for spacing, what you are looking for are the setPadding methods.

Have a look at iText's API for more information:

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

(It's for the Java version, but the C# port maintains the names of the methods)



标签: pdf itext