iTextsharp自定义边框

时间:2017-03-15 09:48:17

标签: c# itext

我想知道如何将自定义边框附加到iTextSharp pdfdcell。

喜欢

enter image description here

问题是我找不到用2行添加边框的方法。

我只能通过

在pdfdcell中创建一个普通的底部边框
PdfPCell tmp = new PdfPCell(new Phrase(c));
tmp.HorizontalAlignment = Element.ALIGN_RIGHT;
tmp.Border = c.borderPosition;
tmp.BorderWidth = c.borderWidth;
pt.AddCell(tmp);

所以结果是这样的

enter image description here

但我需要在边框下再添加一行。

1 个答案:

答案 0 :(得分:0)

由于我使用的是C#和iTextSharp,评论仅显示Java上的解决方案。

我已经实施了类似的事情来解决这个问题。

基本的事实是iTextSharp并不支持自定义边框,但它允许您在PDF上绘制内容。因此,目标是在单元格的底部画一条双线。

  1. 隐藏现有边框
  2. 找出细胞的确切位置
  3. 画线
  4. 诀窍是在单元格上实现CellEvent,在cellevent中它为我们提供了单元格的确切位置,因此我们可以轻松地绘制内容。

    下面是在我的C#项目中工作的代码

    public function void DrawACell_With_DOUBLELINE_BOTTOM_BORDER(Document doc, PdfWriter writer){
        PdfPTable pt = new PdfPTable(new float[]{1});   
        Chunk c = new Chunk("A Cell with doubleline bottom border");
        int padding = 3;
        PdfPCell_DoubleLine cell = new PdfPCell_DoubleLine(PdfPTable pt,new Phrase(c), writer, padding);
        pt.AddCell(cell);
        doc.Add(pt);
    }
    
    public class PdfPCell_DoubleLine : PdfPCell
    {
        public PdfPCell_DoubleLine(Phrase phrase, PdfWriter writer, int padding) : base(phrase)
        {
            this.HorizontalAlignment = Element.ALIGN_RIGHT;
            //1. hide existing border
            this.Border = Rectangle.NO_BORDER;
            //2. find out the exact position of the cell
            this.CellEvent = new DLineCell(writer, padding);
        }
        public class DLineCell : IPdfPCellEvent
        {
            public PdfWriter writer { get; set; }
            public int padding { get; set; }
            public DLineCell(PdfWriter writer, int padding)
            {
                this.writer = writer;
                this.padding = padding;
            }
    
            public void CellLayout(PdfPCell cell, iTextSharp.text.Rectangle rect, PdfContentByte[] canvases)
            {
                //draw line 1
                PdfContentByte cb = writer.DirectContent;
                cb.MoveTo(rect.GetLeft(0), rect.GetBottom(0) - padding);
                cb.LineTo(rect.GetRight(0), rect.GetBottom(0) - padding);
                //draw line 2
                cb.MoveTo(rect.GetLeft(0), rect.GetBottom(0) - padding - 2);
                cb.LineTo(rect.GetRight(0), rect.GetBottom(0) - padding - 2);
                cb.Stroke();
            }
        }
    }
    
相关问题