javaimageitextitext7

Itext 7.0.2 Clockwise rotation of Image


Image element (com.itextpdf.layout.element.Image) supports anticlockwise rotation. Is it possible to make a clockwise rotation of the same image?

PdfPage page = iTextPdfDoc.getLastPage();
PdfCanvas pdfCanvas = new PdfCanvas(page.newContentStreamAfter(), page.getResources(), iTextPdfDoc);
Canvas canvas = new Canvas(pdfCanvas, iTextPdfDoc, page.getPageSize());
Image img = new Image(ImageDataFactory.create(path));
img.scaleAbsolute(525.58203, 737.0079)
img.setFixedPosition(30.785828, 34.66619)

// The following block of code does not affect the center point of rotation.
// I tried a lot of different values for rotation point. No change!
{
  img.setProperty(Property.ROTATION_POINT_X, 30.785828);
  img.setProperty(Property.ROTATION_POINT_Y, 34.66619);
}

img.setProperty(Property.ROTATION_ANGLE, Math.toRadians(90)); //img.setRotationAngle(Math.toRadians(90));
canvas.add(img);

Update:

This is what happens with the image using 90 degrees counter clockwise. enter image description here

This is what happens with the image using -90 or 270 degrees counter clockwise. enter image description here


Solution

  • I found out that the problem is due to:

    img.scaleAbsolute(525.58203, 737.0079)
    

    That line scales the image to be fitted into the container with

    width = 525.58203 and height = 737.0079.
    

    The following block of code makes what I need!

    PdfPage page = iTextPdfDoc.getLastPage();
    PdfCanvas pdfCanvas = new PdfCanvas(page.newContentStreamAfter(), 
    page.getResources(), iTextPdfDoc);
    Canvas canvas = new Canvas(pdfCanvas, iTextPdfDoc, page.getPageSize());
    Image img = new Image(ImageDataFactory.create(path));
    
    float width = img.getXObject().getWidth();
    float widthContainer = 525.58203;
    float heightContainer = 737.0079;
    float horizontalScaling = widthContainer / width;
    
    img.scaleAbsolute(widthContainer, heightContainer);
    
    img.setProperty(Property.ROTATION_ANGLE, Math.toRadians(270));
    img.setFixedPosition(imageLlx, imageLly + width * horizontalScaling);
    
    canvas.add(img);
    

    The result looks like: enter image description here