简体   繁体   中英

iTextSharp C# - PdfPTable Gradient Color - How to?

I saw this tutorial Example gradient for full page gradient but I only need it for PdfPTable that must be colored with a gradient that start from:

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

How can I do it?

To manipulate table backgrounds, you can use table events. Eg for your task:

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;
}

You use it like this:

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

Using red and green for gradientStart and gradientEnd the result looks like this:

红绿色渐变表

Using your colors, though, one hardly sees the gradient:

带有OP颜色的渐变色桌子

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM