PDFBox renderImage 在指定比例下生成不正确的图像尺寸

PDFBox renderImage produces incorrect image dimensions at specified scale

我正在使用非常有用的 PDFBox 构建一个简单的 pdf 冲压 GUI。

但是我注意到某个文档存在严重问题。

当我为渲染指定特定比例因子时,预期的输出图像大小不同。

更糟糕的是什么?结果图像沿水平轴和垂直轴使用的比例因子不同。

这是我使用的代码:

/**
 * @param pdfPath The path to the pdf document
 * @param page The pdf page number(is zero based)
 */
public BufferedImage loadPdfImage(String pdfPath, int page) {
    File file = new File(pdfPath);

    try (PDDocument doc = PDDocument.load(file)) {

        pageCount = doc.getNumberOfPages();
        PDPage pDPage = doc.getPage(page);

       float w = pDPage.getCropBox().getWidth();
       float h = pDPage.getCropBox().getHeight();

       System.out.println("Pdf opening: width: "+w+", height: "+h);


        PDFRenderer renderer = new PDFRenderer(doc);

        float dpiRatio =  1.5f;

        BufferedImage img = renderer.renderImage(page, dpiRatio);

 float dpiXRatio = img.getWidth() / w;
 float dpiYRatio = img.getHeight()/ h;


       System.out.println("dpiXRatio: "+dpiXRatio+", dpiYRatio: "+dpiYRatio);

        return img;
    } catch (IOException ex) {
        System.out.println( "invalid pdf found. Please check");
    }

    return null;
}

上面的代码加载了我试过的大多数 pdf 文档,并将其中的给定页面转换为 BufferedImage 对象。

然而,对于上述文档,它似乎无法以提供的比例因子渲染转换后的图像。

我的代码有什么问题吗?还是已知错误?

谢谢。

编辑

我正在使用 PDFBOX v2.0.15

并且页面没有旋转。

错误是我的;大多数情况下。

我曾使用 MediaBox 计算比例因子,不幸的是,所讨论的 pdf 文件的 MediaBox 和 CropBox 并不相同。

例如:

cropbox-rect: [8.50394,34.0157,586.496,807.984]
mediabox-rect: [0.0,0.0,595.0,842.0]

在对这些进行更正后,比例因子在两个轴上匹配得更好,除了由于图像大小是整数而导致的错误。

虽然这对我来说可以忽略不计。

盖章时,我所要做的就是对 cropbox 进行必要的修正。例如要在 P(x,y) 处绘制图像(图章),我会这样做:

        x += cropBox.getLowerLeftX();
        y += cropBox.getLowerLeftY();

在调用绘制图像功能之前。

一切顺利!