in itext 7.1, I am adding an image to a pdf document with following code :
Document document = new Document(writerPdf); //make a new document object
ImageData imgData = ImageDataFactory.create(imageBytes);
Image image = new Image(imgData);
document.add(image);
This works fine for most images but I have come across an image that seems normal on desktop but when adding to pdf it is rotated by -90 .
imgData.getRotation() gives 0 as output
My question is :
how to check if image has any rotation set.
imgData.setRotation(90) does not seem to work for me. How to rotate . Thanks.
iText 7 unfortunately in general does not read (or at least not provide) that information, the Rotation
property of ImageData
currently is only extracted for TIFF files.
If the image has EXIF metadata and the orientation is properly contained in them, though, you can try and read those metadata using an appropriate library and use that orientation for inserting the image using iText.
One such library is Drew Noakes's metadata-extractor, cf. e.g. his answer here. It can be retrieved via maven using
<dependency>
<groupId>com.drewnoakes</groupId>
<artifactId>metadata-extractor</artifactId>
<version>2.11.0</version>
</dependency>
With that dependency available, you can go ahead and try:
Metadata metadata = ImageMetadataReader.readMetadata(new ByteArrayInputStream(imageBytes));
ExifIFD0Directory exifIFD0Directory = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class);
int orientation = exifIFD0Directory.getInt(ExifIFD0Directory.TAG_ORIENTATION);
double angle = 0;
switch (orientation)
{
case 1:
case 2:
angle = 0; break;
case 3:
case 4:
angle = Math.PI; break;
case 5:
case 6:
angle = - Math.PI / 2; break;
case 7:
case 8:
angle = Math.PI / 2; break;
}
Document document = new Document(writerPdf);
ImageData imgData = ImageDataFactory.create(imageBytes);
Image image = new Image(imgData);
image.setRotationAngle(angle);
document.add(image);
(from the RecognizeRotatedImage test testOskar
)
(For values 2, 4, 5, and 7 one actually also needs to flip the image; for more backgrounds look e.g. here.)
To be safe, consider wrapping the EXIF related code parts in an appropriate try-catch
envelope.