iTextSharp C# - PdfPTable渐变色 - 如何?

时间:2016-02-23 08:25:39

标签: c# itextsharp

我看到这个教程Example gradient用于整页渐变但我只需要它用于PdfPTable,它必须用从以下开始的渐变着色:

BaseColor gradientStart = new BaseColor(137, 24, 28);
BaseColor gradientEnd = new BaseColor(169, 31, 42);

我该怎么做?

1 个答案:

答案 0 :(得分:1)

要操纵表格背景,您可以使用表格事件。例如。为你的任务:

public class GradientTableBackground : IPdfPTableEvent
{
    public GradientTableBackground(PdfWriter writer)
    {
        this.writer = writer;
    }

    public void TableLayout(PdfPTable table, float[][] widths, float[] heights, int headerRows, int rowStart, PdfContentByte[] canvases)
    {
        BaseColor gradientStart = ...;
        BaseColor gradientEnd = ...);

        float[] topWidths = widths[0];
        PdfContentByte cb = canvases[PdfPTable.BACKGROUNDCANVAS];

        Rectangle rectangle = new Rectangle(topWidths[0], heights[heights.Length - 1], topWidths[topWidths.Length - 1], heights[0]);

        PdfShading shading = PdfShading.SimpleAxial(writer, rectangle.Left, rectangle.Top, rectangle.Left, rectangle.Bottom, gradientStart, gradientEnd);
        PdfShadingPattern pattern = new PdfShadingPattern(shading);
        cb.SetShadingFill(pattern);
        cb.Rectangle(rectangle.Left, rectangle.Bottom, rectangle.Width, rectangle.Height);
        cb.Fill();
    }

    PdfWriter writer;
}

你这样使用它:

table = new PdfPTable(columns);
table.TableEvent = new GradientTableBackground(writer);
...
document.Add(table);

gradientStartgradientEnd使用红色和绿色,结果如下所示:

table with red-green gradient

但是,使用你的颜色,几乎看不到渐变:

table with gradient with OP's colors