PageSize of PDF always the same between landscape and portrait with itextpdf

扶醉桌前 提交于 2019-12-02 06:30:22

There are two convenience methods, named getPageSize() and getPageSizeWithRotation().

Let's take a look at an example:

PdfReader reader =
    new PdfReader("src/main/resources/pages.pdf");
show(reader.getPageSize(1));
show(reader.getPageSize(3));
show(reader.getPageSizeWithRotation(3));
show(reader.getPageSize(4));
show(reader.getPageSizeWithRotation(4));

In this example, the show() method looks like this:

public static void show(Rectangle rect) {
    System.out.print("llx: ");
    System.out.print(rect.getLeft());
    System.out.print(", lly: ");
    System.out.print(rect.getBottom());
    System.out.print(", urx: ");
    System.out.print(rect.getRight());
    System.out.print(", lly: ");
    System.out.print(rect.getTop());
    System.out.print(", rotation: ");
   System.out.println(rect.getRotation());
}

This is the output:

llx: 0.0, lly: 0.0, urx: 595.0, lly: 842.0, rotation: 0
llx: 0.0, lly: 0.0, urx: 595.0, lly: 842.0, rotation: 0
llx: 0.0, lly: 0.0, urx: 842.0, lly: 595.0, rotation: 90
llx: 0.0, lly: 0.0, urx: 842.0, lly: 595.0, rotation: 0
llx: 0.0, lly: 0.0, urx: 842.0, lly: 595.0, rotation: 0

Page 3 (see line 4 in code sample 3.8) is an A4 page just like page 1, but it's oriented in landscape. The /MediaBox entry is identical to the one used for the first page [0 0 595 842], and that's why getPageSize() returns the same result.

The page is in landscape, because the \Rotate entry in the page dictionary is set to 90. Possible values for this entry are 0 (which is the default value if the entry is missing), 90, 180 and 270.

The getPageSizeWithRotation() method takes this value into account. It swaps the width and the height so that you're aware of the difference. It also gives you the value of the /Rotate entry.

Page 4 also has a landscape orientation, but in this case, the rotation is mimicked by adapting the /MediaBox entry. In this case the value of the /MediaBox is [0 0 842 595] and if there's a /Rotate entry, its value is 0.

That explains why the output of the getPageSizeWithRotation() method is identical to the output of the getPageSize() method.

When I read your question, I see that you are looking for the rotation. This can be done with the getRotation() method.

Remark: This text is copied from my book "The ABC of PDF" (the book is under construction; you can download the first chapters for free). The code sample can be found here.

Fix :

use

PdfStamper.getImportedPage(pdfReader, pagenumber).getBoundingBox().getWidth()

instead of

stamper.getOverContent(i).getPdfDocument().getPageSize().getWidth();
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!