Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iTextSharp Table Cell Spacing Possible?

Tags:

pdf

itext

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

like image 816
Nick Reeve Avatar asked Apr 19 '12 15:04

Nick Reeve


1 Answers

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);
like image 98
Chris Haas Avatar answered Nov 02 '22 11:11

Chris Haas