I have concatenated several PDF files, some of which were landscape. I am now stamping each page of the final PDF.
I have realised that not using setRotateContents(false)
will result in your modification being added at -90 degrees to where you expect. Except some of my landscape pages actually correctly position the modification at this stage at 0 degrees.
If I use setRotateContents(false)
then all of these modifications are rotated clockwise 90 degrees meaning most of my page modifications on landscape pages are now correct at 0 degrees but some of my landscape pages are now at +90 degrees.
The problem is I can't work out what is causing my pages to give this strange behaviour? They both are using very similar code to generate the reports. Has anyone seen a similar problem before?
There are 3 different ways to do a landscape page, and all three are used (I'm using 8.5x11 as a basis here, YMMV):
- 11x8.5 (these are the pages that "look right".
- 8.5x11 90 clockwise
- 8.5x11 90 counterclockwise
So you need to check the page's rotation.
int rot = PdfReader.getPageRotation(pageNum);
If you want your stamp to come out "even" you then need to transform it based on that rotation. The basic transform goes something like this:
cos(rot), sin(rot), -sin(rot), cos(rot), xoff, yoff
Rotation takes place around the origin, 0,0. You need xoff
and yoff
to move the stamp back to where you want it. Because you can combine transformations, one common trick is:
- Move your object so it is centered on the origin.
- Rotate
- Move it back.
When you combine those three individual transformations in the proper order, you end up with a single transform that does just what you want.
Or you could cheat and use AffineTransform.getRotateInstance( theta, centerX, centerY)
, but where's the fun in that? PdfContentByte.transform(AffineTransform)
will suck the array out for you, but all the elements are in the proper order to simply pass them to any of the content byte functions that accepts a transformation as six floats (the parameters are usually called something like "a, b, c, d, h, v").