Posts Tagged pdf

Rotating an Image in iText

I’ve used iText for a number of years now. It’s a java library for creating PDFs. It’s pretty full featured, but, the one problem most people have are the holes in the documentation.

I was recently trying to add and rotate an image to a PDF. To do this, I’m using the PDFContentByte class and the addImage method.

From the JavaDocs:

public void addImage(Image image,
float a,
float b,
float c,
float d,
float e,
float f)
throws DocumentException

Adds an Image to the page. The positioning of the Image is done with the transformation matrix. To position an image at (x,y) use addImage(image, image_width, 0, 0, image_height, x, y).

It doesn’t really explain how to manipulate the transform to rotate the image.

Here’s how to make it work. The key is getting the parameters a, b, c, and d right.

The variable degrees is the rotation angle you want for the image in degrees.
The variable e is where you want to place the image on the x cooridinate.
The variable f is where you want to place the image on the 7 coordinate.

(note: the Math.cos and Math.sin methods take an input of degree radians hence the additional math)

float a = (float)Math.cos( degrees * (float)Math.PI / 180) * image.getScaledHeight();
float b = (float)Math.sin( degrees * (float)Math.PI / 180) * image.getScaledWidth();
float c = -(float)Math.sin( degrees * (float)Math.PI / 180) * image.getScaledHeight();
float d = (float)Math.cos( degrees * (float)Math.PI / 180) * image.getScaledWidth();

Post to Twitter Tweet This Post

, ,

No Comments