How to create a dotted line in iTextSharp PDF table cell.

First, you will need to create a new class that will handle the PDF PCell events of CellLayout:

 // Cell Event to make dotted Line
    class dot : IPdfPCellEvent {

        public void CellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases)
        {
             cell.Border = Rectangle.TOP_BORDER;
            PdfContentByte cb = canvases[PdfPTable.LINECANVAS];
            cb.SetLineDash(3f, 3f);
            cb.Rectangle(position.Left, position.Bottom, position.Width, position.Height);
            cb.Stroke();
        }
}

With a cell event, a border is drawn around every cell. This means you’ll have multiple stroke() operators and overlapping lines.

The most elegant way to draw the cell borders, as it uses only one stroke() operator for all the lines. This isn’t an option if you have tables with rowspans (but you probably don’t care about rowspans, because you’re using an obsolete version of iText that didn’t support rowspans).

 class DottedCells : IPdfPTableEvent {


    public void TableLayout(PdfPTable table, float[][] widths, float[] heights, int headerRows, int rowStart, PdfContentByte[] canvases)
    {
        PdfContentByte canvas = canvases[PdfPTable.LINECANVAS];
        canvas.SetLineDash(3f, 3f);
        float llx = widths[0][0];
        float urx = widths[0][widths[0].Length - 1];
        for (int i = 0; i < heights.Length; i++)
        {
            canvas.MoveTo(llx, heights[i]);
            canvas.LineTo(urx, heights[i]);
        }
        for (int i = 0; i < widths.Length; i++)
        {
            for (int j = 0; j < widths[i].Length; j++)
            {
                canvas.MoveTo(widths[i][j], heights[i]);
                canvas.LineTo(widths[i][j], heights[i + 1]);
            }
        }
        canvas.Stroke();
    }
    }

How to call the code:

                PdfPTable t1 = new PdfPTable(1); t1.WidthPercentage = 100f;
                //add dotted line underneath
                PdfPCell cell2 = new PdfPCell();
                dot evt = new dot();
                cell2.CellEvent = evt;
                cell2.Border = Rectangle.NO_BORDER;
                cell2.Colspan = 2;
                pB = new Paragraph(3f, " ", times);
                cell2.AddElement(pB);
                t1.AddCell(cell2); 
Advertisements