【问题标题】:iText page color or black/whiteiText 页面颜色或黑/白
【发布时间】:2011-11-23 14:03:42
【问题描述】:

我正在尝试使用 iText(或者如果您知道任何其他 java 库)来确定 PDF 文档的页面是否包含任何非黑白对象(页面是黑白或彩色)。 我的 PDF 文件不应包含图像,因此我们不必担心。

有什么想法吗?

我希望除了转换为图像并读取每个像素的颜色之外,还有其他方法。

【问题讨论】:

  • 我不知道有什么库可以帮助你,但我可以告诉你 itext 会很有帮助,因为当使用 itext 阅读 pdf 时,所有格式都会被删除。

标签: java pdf itext


【解决方案1】:

一种可能的解决方案是获取页面流并对颜色设置运算符进行正则表达式搜索。

byte[] contentStream = pdfRdr.getPageContent(pageNo);

PDF 页面上的几乎所有内容都是文本或图形对象。使用最多四个浮点值后指定的运算符设置颜色:

f1 .. fn SC % you need to know more about the colour space to determine whether this is black or not
fq .. fn sc
f1 f2 f3 RG % 0 0 0 would be black 1 1 1 would be white
f1 f2 f3 rg
f1 f2 f3 f4 K % CMYK (0 0 0 1 = Black, 0 0 0 0 = White, I think)
f1 f2 f3 f4 k
f1 g % the g operator choose the greyscale colour space
g1 G

我可以想象这可能很难做到。更实用的解决方案可能是将页面转换为图像(使用您可以通过谷歌搜索的众多工具之一),然后检查图像。

【讨论】:

  • 我认为处理图像的方式更节省,正如你所说,更实用。使用 pdf-renderer(来自 java.net)或 apache pdfBox 以及生成的 awt.image 应该很容易。
  • Jimmy 建议的 C# 实现可以在这里找到:habjan.blogspot.com/2013/09/…
【解决方案2】:

Apache PDFBox 的一个可能解决方案是创建图像并检查像素 RGB。但请注意,即使 PDF 是纯黑白的,渲染的图像也可能包含灰度。

import java.awt.image.BufferedImage;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;

...

public void checkColor(final File pdffile) {
  PDDocument document = PDDocument.load(pdffile);
  List<PDPage> pages = document.getDocumentCatalog().getAllPages();
  for (int i = 0; i < pages.size(); i++) {
    PDPage page = pages.get(i);
    BufferedImage image = page.convertToImage(BufferedImage.TYPE_INT_RGB, 72);
    for (int h = 0; h < image.getHeight(); h++) {
      for (int w = 0; w < image.getWidth(); w++) {
        int pixel = image.getRGB(w, h);
        boolean color = isColorPixel(pixel);
        // ... do something
      }
    }
  }
}

private boolean isColorPixel(final int pixel) {
    int alpha = (pixel >> 24) & 0xff;
    int red = (pixel >> 16) & 0xff;
    int green = (pixel >> 8) & 0xff;
    int blue = (pixel) & 0xff;
    // gray: R = G = B
    return !(red == green && green == blue);
}

【讨论】:

    猜你喜欢
    • 2020-03-24
    • 2010-11-22
    • 1970-01-01
    • 1970-01-01
    • 2015-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多