如何使用 PDFBox 在 PDF 中查找空白页?

Sho*_*oyo 5 java pdf

这是我目前面临的挑战。
我有很多 PDF,我必须删除其中的空白页面并仅显示包含内容(文本或图像)的页面。
问题是那些pdf是扫描文件。
所以空白页有一些被扫描仪留下的脏东西。

Sho*_*oyo 9

我做了一些研究,最后得到了这段代码,它检查页面的 99% 是白色还是浅灰色。我需要灰度系数,因为扫描的文档有时不是纯白色的。

private static Boolean isBlank(PDPage pdfPage) throws IOException {
    BufferedImage bufferedImage = pdfPage.convertToImage();
    long count = 0;
    int height = bufferedImage.getHeight();
    int width = bufferedImage.getWidth();
    Double areaFactor = (width * height) * 0.99;

    for (int x = 0; x < width ; x++) {
        for (int y = 0; y < height ; y++) {
            Color c = new Color(bufferedImage.getRGB(x, y));
            // verify light gray and white
            if (c.getRed() == c.getGreen() && c.getRed() == c.getBlue()
                    && c.getRed() >= 248) {
                 count++;
            }
        }
    }

    if (count >= areaFactor) {
        return true;
    }

    return false;
}
Run Code Online (Sandbox Code Playgroud)

  • 不错的解决方案,但您应该计算“黑色”像素而不是白色,因为如果您发现 1% 的黑色像素,则意味着该页面“不是空白”,而不是扫描所有页面以搜索 99% 的白色像素。 (2认同)