Bashar
Bashar

Reputation: 71

PDFBOX: Gradient not fill only the specific shape

I'm trying to use gradiant colors to fill the drawn shapes, but the gradinet color fill the whole area, attached my code:

code for creating the gradient color:

public static PDColor createSpotColorFromRGB(String spotColorName, int r, int g, int b) throws IOException {
        PDSeparation seperation = new PDSeparation();
        COSDictionary dictionary = new COSDictionary();
        COSArray C0 = new COSArray();
        COSArray C1 = new COSArray();
        COSArray range = new COSArray();
        COSArray domain = new COSArray();
        float[] components = null;

        seperation.setColorantName(spotColorName);

        components = new float[] { r / 255f, g / 255f, b / 255f };

        seperation.setAlternateColorSpace(PDDeviceRGB.INSTANCE);

        C0.add(COSInteger.ZERO);
        C0.add(COSInteger.ZERO);
        C0.add(COSInteger.ZERO);

        range.add(COSInteger.ZERO);
        range.add(COSInteger.ONE);
        range.add(COSInteger.ZERO);
        range.add(COSInteger.ONE);
        range.add(COSInteger.ZERO);
        range.add(COSInteger.ONE);

        for (int i = 0; i < components.length; i++) {
            C1.add(new COSFloat(components[i]));
        }

        domain.add(COSInteger.ZERO);
        domain.add(COSInteger.ONE);

        dictionary.setItem(COSName.C1, C1);
        dictionary.setItem(COSName.C0, C0);
        dictionary.setItem(COSName.DOMAIN, domain);
        dictionary.setItem(COSName.FUNCTION_TYPE, COSInteger.TWO);
        dictionary.setItem(COSName.N, COSInteger.ONE);
        dictionary.setItem(COSName.RANGE, range);

        PDFunction functionTyp2 = new PDFunctionType2(dictionary);

        seperation.setTintTransform(functionTyp2);

        return new PDColor(new float[] { 1f }, seperation);
    }

code for drawing rectangle:

contentStream.saveGraphicsState();

extendedGraphicsStateForDrawing = new PDExtendedGraphicsState();
extendedGraphicsStateForDrawing.setAlphaSourceFlag(true);
extendedGraphicsStateForDrawing.setStrokingAlphaConstant(alphaStroke);
extendedGraphicsStateForDrawing.setNonStrokingAlphaConstant(alphaFill);

contentStream.setGraphicsStateParameters(extendedGraphicsStateForDrawing);

contentStream.moveTo(5, 5);
contentStream.lineTo(10,5);
contentStream.lineTo(10,10);
contentStream.lineTo(10,5);
contentStream.closePath();

contentStream.shadingFill(PdfUtils.createGradientColor(gradiantFactors));

contentStream.restoreGraphicsState();

why all the page filled with the gradient and not only the rectangle: enter image description here

Thanks.

Upvotes: 1

Views: 102

Answers (1)

Tilman Hausherr
Tilman Hausherr

Reputation: 18861

call

contentStream.clip();

before doing the shading. The shading fill does not work like the normal fill.

Upvotes: 1

Related Questions