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.