How to draw vertical gradient in iTextSharp?

I can make a horizontal gradient, but how do I make it vertical?

31st May 2016

I am trying to draw a vertical gradient at the bottom of an iTextSharp pdf document:


PdfShading shading = PdfShading.SimpleAxial(pdfWriter, 0, document.PageSize.Height, document.PageSize.Width, 0, BaseColor.WHITE, BaseColor.GREEN);
PdfShadingPattern pattern = new PdfShadingPattern(shading);
pdfContentByte.Rectangle(0, 0, document.PageSize.Width, 70);

This creates a gradient at the exact position I want it to be created, but the gradient is horizontal from left (white) to right (green). I want the gradient to be vertical from top (white) to bottom (green). Modifying the coordinates did not solve the problem. I also tried to rotate the document but that didn't work as well.


Posted on StackOverflow on Dec 23, 2015 by Norman

You are using the wrong coordinates. In Java, you'd need something like this:

PageSize pageSize = new PageSize(150, 300);
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
PdfCanvas canvas = new PdfCanvas(pdfDoc.addNewPage());
PdfShading.Axial axial = new PdfShading.Axial(new PdfDeviceCs.Rgb(), 0, pageSize.getHeight(), Color.WHITE.getColorValue(),
        0, 0, Color.GREEN.getColorValue());
PdfPattern.Shading pattern = new PdfPattern.Shading(axial);
canvas.rectangle(0, 0, pageSize.getWidth(), pageSize.getHeight());

See GradientTopToBottom for the full sample code.

Do you see the difference?

  • You go from the left-top corner (0, document.PageSize.Height) to the right-bottom corner (document.PageSize.Width, 0). That's a diagonal.

  • You want to go from the top (0, document.PageSize.Height) to the bottom (0, 0) which leads to the following result: gradient_top_to_bottom.pdf

    Gradient from top to bottom

    Gradient from top to bottom

Click this link if you want to see how to answer this question in iText 5.

Share this article


Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now