How to add a shading pattern to a custom shape?

How do I use iText to add a multi color gradient in a shape?

31st May 2016
admin-marketing

I have drawn an equilateral triangle as follows using iText

 

canvas.setColorStroke(BaseColor.BLACK);
int x = start.getX();
int y = start.getY();
canvas.moveTo(x,y);
canvas.lineTo(x + side,y);
canvas.lineTo(x + (side/2), (float)(y+(side*Math.sin(convertToRadian(60)))));
canvas.closePathStroke();
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.setFillColorShading(shading);
canvas.moveTo(x, y);
canvas.lineTo(x + side, y);
canvas.lineTo(x + (side / 2), (float) (y + (side * Math.sin(Math.PI / 3))));
canvas.closePathFillStroke();

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.


Share this article

Contact

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