itextsharp C#:如何在 Table 单元格内绘制对角线

itextsharp C#: How to draw Diagonal Line inside Table Cell

如何使用 itextsharp C# 在 pdf table 的单元格内绘制对角线? 我想要这样的东西: Splitting table cells diagonally itextsharp 但在 C# 中。因为 post 与 java 一起使用,而我无法在 C#

中完成

根据mkl在评论中的建议,可以尝试用下面的代码在table单元格中画一条对角线

首先,请安装 nuget-package iTextSharp.

其次,这是一个完整的代码示例,您可以参考。

 static void Main(string[] args)
        {
            Program p = new Program();
            p.createPdf("E:\test.pdf");
        }


        public void createPdf(String dest)
        {
            using (FileStream stream = new FileStream(dest,FileMode.Create,FileAccess.Write))
            {
                using (Document document = new Document())
                {
                    PdfWriter writer = PdfWriter.GetInstance(document, stream);
                    document.Open();
                    PdfPTable table = new PdfPTable(6);
                    table.DefaultCell.MinimumHeight=30;
                    PdfPCell cell = new PdfPCell();
                    cell.CellEvent = new PdfPCellEvent("Gravity", "Occ");
                    //cell.setCellEvent(new Diagonal("Gravity", "Occ"));
                    table.AddCell(cell);
                    table.AddCell("1");
                    table.AddCell("2");
                    table.AddCell("3");
                    table.AddCell("4");
                    table.AddCell("5");
                    for (int i = 0; i < 5;)
                    {
                        table.AddCell((++i).ToString());
                        table.AddCell("");
                        table.AddCell("");
                        table.AddCell("");
                        table.AddCell("");
                        table.AddCell("");
                    }
                    document.Add(table);
                    document.Close();
                    
                }
            }

        }



public class PdfPCellEvent : IPdfPCellEvent
    {
        protected String columns;
        protected String rows;

        public PdfPCellEvent(String columns, String rows)
        {
            this.columns = columns;
            this.rows = rows;
        }
        public void CellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases)
        {
            PdfContentByte canvas = canvases[PdfPTable.TEXTCANVAS];
            ColumnText.ShowTextAligned(canvas, Element.ALIGN_RIGHT,
                new Phrase(columns), position.GetRight(2), position.GetTop(12), 0);
            ColumnText.ShowTextAligned(canvas, Element.ALIGN_LEFT,
                new Phrase(rows), position.GetLeft(2), position.GetBottom(2), 0);
            canvas = canvases[PdfPTable.LINECANVAS];
            canvas.MoveTo(position.Left, position.Top);
            canvas.LineTo(position.Right, position.Bottom);
            canvas.Stroke();
        }
    }

结果: