【问题标题】:Why I can't obtain rounded table corners in this iText\iTextSharp footer table?为什么我无法在此 iText\iTextSharp 页脚表中获得圆角?
【发布时间】:2014-05-14 11:05:15
【问题描述】:

我有以下情况:我必须使用 iTextSharp 在我的 PDF 的页脚中创建一个圆角表,但我发现这样做有些困难。

首先,我创建了一个名为 PdfHeaderFooter 的类,它扩展了 PdfPageEventHelper iTextSharp 接口。

在这个类中,我实现了在所有页面末尾创建页脚的 OnEndPage() 方法,这是我的代码:

    // Write on end of each page
    public override void OnEndPage(PdfWriter writer, Document document)
    {
        base.OnEndPage(writer, document);
        PdfPTable tabFot = new PdfPTable(new float[] { 1F });
        tabFot.TotalWidth = 300F;

        tabFot.DefaultCell.Border = PdfPCell.NO_BORDER;
        tabFot.DefaultCell.CellEvent = new RoundedBorder();

        PdfPCell cell;
        cell = new PdfPCell(new Phrase("Footer"));
        tabFot.AddCell(cell);

        tabFot.WriteSelectedRows(0, -1, 150, document.Bottom, writer.DirectContent);
    }

正如您在这段代码中看到的那样,我创建了一个名为 TabFoot 的表,它的宽度为 300 像素,并且包含一列。我还将这个表格单元格的单元格事件处理程序设置为 RoundBorder 对象。

这是我的 RoundBorder 类的代码:

class RoundedBorder : IPdfPCellEvent
{
    public void CellLayout(PdfPCell cell, iTextSharp.text.Rectangle rect, PdfContentByte[] canvas)
    {
        PdfContentByte cb = canvas[PdfPTable.BACKGROUNDCANVAS];
        cb.RoundRectangle(
          rect.Left + 1.5f,
          rect.Bottom + 1.5f,
          rect.Width - 3,
          rect.Height - 3, 4
        );
        cb.Stroke();
    }
}

问题是我的程序工作并且生成了PDF,但是页脚中的表格不是圆角而是经典的方角,我得到了这个结果:

为什么?我错过了什么?有什么办法可以解决?

Tnx

【问题讨论】:

    标签: c# pdf pdf-generation itextsharp itext


    【解决方案1】:

    它不起作用的原因很简单。您正在定义NO_BORDER 值和DefaultCell 的单元格事件。如文档所述,当您添加一个单元格而不自己创建一个单元格时,将使用默认单元格的属性。例如:

    table.AddCell("Test 1");
    

    在您的情况下,您没有使用默认单元格,而是在创建自己的 PdfPCell 实例:

    PdfPCell cell = new PdfPCell(new Phrase("Footer"));
    

    这个cell 实例有它自己的属性。它不会查看您为 DefaultCell 定义的内容(否则将无法引入与默认值不同的属性)。因此你需要:

    cell.Border = PdfPCell.NO_BORDER;
    cell.CellEvent = new RoundedBorder();
    

    现在特定单元格cell 将只有圆形边框。

    【讨论】:

    • 在创建自己的 PdfPCell 实例时,有什么方法可以使表格的边框而不是每个单元格的边框变圆?
    • 是的,这是使用表格事件而不是单元格事件来完成的。
    猜你喜欢
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2021-03-21
    • 1970-01-01
    • 2017-02-11
    • 1970-01-01
    相关资源
    最近更新 更多