如何根据单元格数据长度 c# 制作 table 边框长度?

How to make the table border length as per cell data length c#?

是否可以使特定 table 单元格的边框长度适合该单元格的内容?

我做到了

PdfPCell cell = new PdfPCell(new Phrase(total.ToString(),myFont));
cell.Border=PdfPCell.BOTTOM_BORDER | PdfPCell.TOP_BORDER;
cell.HorizontalAlignment=Element.ALIGN_LEFT;
tabl.AddCell(cell);

但它产生了以下结果(顶部和底部边框超出了单元格数据length/space)

有人可以帮忙吗?

iText 7

在 iText 7 中,这非常简单,因为可以开箱即用地为任何元素设置边框。在此用例中,不使用 table 或单元格边框,而是为文本本身设置顶部和底部边框更容易。

Table table = new Table(4);
table.SetWidth(UnitValue.CreatePercentValue(100));
// no border on the table
table.SetBorder(null);

// no border on the cell
Cell cell = new Cell().SetBorder(null);
Text t = new Text("410.40");
// top and bottom border on the Text instance
t.SetBorderTop(new SolidBorder(1.5f));
t.SetBorderBottom(new SolidBorder(1.5f));
Paragraph p = new Paragraph().Add(t);
cell.Add(p);
table.AddCell(cell);

// some test cells
table.AddCell(new Cell().Add(new Paragraph("Column 2")).SetBorder(null));
table.AddCell(new Cell().Add(new Paragraph("C 3")).SetBorder(null));
table.AddCell(new Cell().Add(new Paragraph("C 4")).SetBorder(null));

doc.Add(table);

iText 5 / iTextSharp

要获得相同的效果,还需要做一些繁重的工作。一种可能的方法是使用页面事件侦听器和带有“通用标记”的 Chunk 在呈现时触发页面事件。该回调将公开 Chunk 的渲染矩形,这允许使用这些坐标在正确的位置绘制顶线和底线。

writer.PageEvent = new BorderEvent();

PdfPTable table = new PdfPTable(4);
table.WidthPercentage = 100;

PdfPCell cell = new PdfPCell();
// Use a Chunk with a "generic tag", which triggers a callback when it's rendered
Chunk c = new Chunk("410.40");
c.SetGenericTag("borders");
cell.AddElement(c);
// no border on the cell
cell.Border = 0;
table.AddCell(cell);

// some test cells
cell = new PdfPCell();
cell.AddElement(new Paragraph("Column 2"));
cell.Border = 0;
table.AddCell(cell);
cell = new PdfPCell();
cell.AddElement(new Paragraph("C 3"));
cell.Border = 0;
table.AddCell(cell);
cell = new PdfPCell();
cell.AddElement(new Paragraph("C 4"));
cell.Border = 0;
table.AddCell(cell);

doc.Add(table);

通用标签的回调:

class BorderEvent : PdfPageEventHelper
{
    public override void OnGenericTag(PdfWriter writer, Document document,
            Rectangle rect, String text)
    {
        PdfContentByte canvas = writer.DirectContent;
        // draw the top border, based on the rendering rectangle
        canvas.SetLineWidth(1.5);
        canvas.MoveTo(rect.Left, rect.Top);
        canvas.LineTo(rect.Right, rect.Top);
        // draw the bottom border, based on the rendering rectangle
        // the bottom coordinate is the base line of the text,
        // so some calculation, probably including the font size, is
        // needed to lower it a bit
        // I've used a quick and dirty 3 points here
        canvas.Stroke();
        canvas.MoveTo(rect.Left, rect.Bottom - 3);
        canvas.LineTo(rect.Right, rect.Bottom - 3);
        canvas.Stroke();
    }
}