Raju Khinda
Raju Khinda

Reputation: 105

Itext7 - Crop Image

Hi How can we resize image in iText 7 . I am not able to find PDFTemplate in itext 7 now which used to crop image. .

public Image cropImage(PdfWriter writer, Image image, float leftReduction, float rightReduction, float topReduction, float bottomReduction) throws DocumentException {
    float width = image.getScaledWidth();
    float height = image.getScaledHeight();
    PdfTemplate template = writer.getDirectContent().createTemplate(
            width - leftReduction - rightReduction,
            height - topReduction - bottomReduction);
    template.addImage(image,
            width, 0, 0,
            height, -leftReduction, -bottomReduction);
    return Image.getInstance(template);
}

This is used for itext 5

Upvotes: 2

Views: 1735

Answers (1)

Bruno Lowagie
Bruno Lowagie

Reputation: 77528

Suppose that you have this image, measuring 900 x 1200 pixels:

enter image description here

But you only want to show part of this image (e.g. the ping pong balls):

enter image description here

Then you can use this iText 7 code:

PdfDocument pdf = new PdfDocument(new PdfWriter("cropimage.pdf"));
Document document = new Document(pdf);
Image image = new Image(ImageDataFactory.create(imagePath));
image.setFixedPosition(-20, -320);
Rectangle rectangle = new Rectangle(300, 300);
PdfFormXObject template = new PdfFormXObject(rectangle);
Canvas canvas = new Canvas(template, pdf);
canvas.add(image);
Image croppedImage = new Image(template);
document.add(croppedImage);
document.close();

We create an Image instance with the full image, and we set the fixed position in such a way that we chip off 20 pixels from the left, and 320 from the bottom.

We create a rectangle of 300 x 300 user units. This defines the size of the cropped image.

We create a PdfFormXObject using this rectangle. In iText 5 language, a Form XObject used to be named a PdfTemplate.

We create a Canvas object with this template, and we add the image to the canvas.

Finally, we create another Image using the template. The Canvas operation will have added the full image to that template, but it will be cropped to the size of the rectangle.

You can add this croppedImage to the document.

Upvotes: 2

Related Questions