How to add a shading pattern to a custom shape?

I have drawn an equilateral triangle as follows using iText


int x = start.getX();
int y = start.getY();
canvas.lineTo(x + side,y);
canvas.lineTo(x + (side/2), (float)(y+(side*Math.sin(convertToRadian(60)))));
I wish to add a multi color gradient in this shape i.e. fill it with shading comprising of BaseColor.PINK and BaseColor.BLUE. I just can't find a way to do this with iText.

Posted on StackOverflow on Oct 27, 2014 by RaghaveShukla

I've created an example called ShadedFill that fills the triangle you are drawing using a shading pattern that goes from pink to blue as shown in the shaded_fill.pdf PDF:

Shaded fill

Shaded fill

PdfContentByte canvas = writer.getDirectContent();
float x = 36;
float y = 740;
float side = 70;
PdfShading axial = PdfShading.simpleAxial(writer, x, y,
        x + side, y, BaseColor.PINK, BaseColor.BLUE);
PdfShadingPattern shading = new PdfShadingPattern(axial);
canvas.lineTo(x + side, y);
canvas.lineTo(x + (side / 2), (float)(y + (side * Math.sin(Math.PI / 3))));

As you can see, you need to create a PdfShading object. I created an axial shading that varies from pink to blue from the coordinate (x, y) to the coordinate (x + side, y). With this axial shading, you can create a PdfShadingPattern that can be used as a parameter of the setShadingFill() method to set the fill color for the canvas.

Ready to use iText?

Try our iText 7 Library and add-ons FREE for 30 days. Test your proof of concept, and see if our solution is right for you.

Get my FREE trial

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