iText pdf library
Website search

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

PdfCanvas canvas = new PdfCanvas(pdfDoc.addNewPage());
float x = 36;
float y = 740;
float side = 70;
PdfShading.Axial axial = new PdfShading.Axial(new PdfDeviceCs.Rgb(), x, y, Color.PINK.getColorValue(),
        x + side, y, Color.BLUE.getColorValue());
PdfPattern.Shading shading = new PdfPattern.Shading(axial);
canvas.moveTo(x, y);
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.Axial 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 PdfPattern.Shading that can be used as a parameter of the setFillColorShading() method to set the fill color for the canvas.

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

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