Search code examples
javaitextcrop

Cropping images in Itext


is there an easy way to crop an Image in Itext?

I have the following code:

URL url = new URL(imgUrl);

connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
iStream = connection.getInputStream();
img = new Jpeg(url);

// a method like 
// img.crop(x1, y1, x2, y2) would be nice.

Now I want to "delete" a strip of let's say 20 pixels left and 20 pixels right. Is there an easy way to do this?


Solution

  • You could investigate using the clipping path. You'll need to know the width and height of the JPEG. The code might look something like this:

    PdfTemplate t = writer.getDirectContent().createTemplate(850, 600);
    t.rectangle(x+20,y+20, width-40, height-40);
    t.clip();
    t.newPath();
    t.addImage(img, width, 0, 0, height, x, y);