Site iconJava PDF Blog

How to Convert PDF co-ordinates to Java co-ordinates

How do Java co-ordinates work?

Java is a top, left system, which means 0,0 is in the top, left corner of the screen with X axis going to right and Y co-ordinates going down. Negative values are allowed.

How do PDF co-ordinates work?

PDF is a bottom, left system, which means 0,0 is in the bottom, left corner of the screen with X axis going to right and Y co-ordinates going up. Negative values are allowed.

How to convert co-ordinates with AffineTransforms?

Java AffineTransforms provide an easy way to convert between co-ordinate systems using Matrices. This allows you to change Java to use your preferred co-ordinates. In our case, we want to work in the PDF coordinates.

To convert the Java space to PDF space we have to invert the display, thus moving the 0,0 to the bottom left. You could be forgiven for thinking that turning it by -90 degrees was the answer but if you plot 20 across by 40 up, (20,40) you will see what I mean.


This is shown above, as the 90 degree rotated space will have x co-ordinates that go up the display and y co-ordinates that go across the screen.

That shows you the basic transform that needs applying to all pdf’s, but then we have to deal with the PDF mediabox, cropbox and even trim(rare) boxes, these are points which define a box on the page. The media box is the initial page bounds box, so everything on that page should be within these points.

The crop or trim box generally tells you what on the page is going to be visible.
These boxes can be any values, so 0,0,580,720 is a good standard box, but also -700,-300,10,10 is a perfectly valid box.

Coupled with all this, the PDF offers the ability to rotate every PDFObject differently and then even to say that each object is positions in a different rotation again.

Graphics2D is a very powerful library and the AffineTransform is very useful for making things simple. Do you have any clever tricks with using Graphics2D in Java?