在 Java 中更改 PDF 页面尺寸

Aspose.PDF for Java 既可以报告页面尺寸,也可以更新它们。

更改页面尺寸

当您需要调整现有页面大小并在更改前后检查页面框时,请使用此示例。

  1. 打开源 PDF Document。
  2. 获取目标 Page 并打印其当前的框值。
  3. 设置新的页面大小并保存文档。
public static void setPageSize(Path inputFile, Path outputFile) {
    try (Document document = new Document(inputFile.toString())) {
        Page page = document.getPages().get_Item(1);
        printBoxes("Before set", page);
        page.setPageSize(597.6, 842.4);
        printBoxes("After set", page);
        document.save(outputFile.toString());
    }
}

获取页面尺寸

当您需要读取页面的可见尺寸时,请使用此示例。

  1. 打开源 PDF Document。
  2. 获取页面矩形,并启用旋转处理。
  3. 输出页面宽度和高度。
public static void getPageSize(Path inputFile) {
    try (Document document = new Document(inputFile.toString())) {
        Rectangle rectangle = document.getPages().get_Item(1).getPageRect(true);
        System.out.println(rectangle.getWidth() + " : " + rectangle.getHeight());
    }
}

获取已应用旋转的页面尺寸

当您需要比较在考虑旋转前后的页面尺寸时,请使用此示例。

  1. 打开源 PDF Document。
  2. 旋转目标 Page。
  3. 读取页面矩形(包含旋转处理和不包含旋转处理),并输出两个值。
public static void getPageSizeRotation(Path inputFile) {
    try (Document document = new Document(inputFile.toString())) {
        Page page = document.getPages().get_Item(1);
        page.setRotate(Rotation.on90);
        Rectangle rectangle = page.getPageRect(false);
        System.out.println(rectangle.getWidth() + " : " + rectangle.getHeight());
        rectangle = page.getPageRect(true);
        System.out.println(rectangle.getWidth() + " : " + rectangle.getHeight());
    }
}