Search code examples
javapdfbox

how to rotate pdf page and set origin


i'm trying to rotate every landscape page in document, so all pages are portrait orientation. i'm using apache pdfbox for that.

PDPage page = document.getPage(pageIndex);
PDRectangle mediaBox = page.getMediaBox();
if(mediaBox.getWidth() > mediaBox.getHeight()) {
  page.setRotation(270);
}

this works fine, page is rotated. now, the problem is, that after i send document to printer, it will put some marks on it (see image1).

printer marks on portrait (not rotated) page

on rotated page however marks appear on wrong position. like it would appear on landscape page (see image2).

printer marks on rotated page

i think it has something to do with origin. do you have any ideas how to set origin, so that printer mark appears on right place?

thank you and best regards Dalibor


Solution

  • Please try this:

    PDPageContentStream cs = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true, true);            int rotation = page.getRotation();
    switch (rotation)
    {
        case 90:
            width = page.getMediaBox().getHeight();
            height = page.getMediaBox().getWidth();
            cs.transform(Matrix.getRotateInstance(Math.toRadians(90), height, 0));
            break;
        case 180:
            cs.transform(Matrix.getRotateInstance(Math.toRadians(180), width, height));
            break;
        case 270:
            width = page.getMediaBox().getHeight();
            height = page.getMediaBox().getWidth();
            cs.transform(Matrix.getRotateInstance(Math.toRadians(270), 0, width));
            break;
        default:
            break;
    }
    

    then continue with your stuff. Don't forget to close the content stream. The code above is taken from the AddWatermarkText.java example from the source code download.