我試圖找出PDF文檔的頁面是否包含任何沒有黑色&使用iText的白色對象(或者可能是其他一些Java庫if你知道任何)。 我的PDF文件不應該包含圖像,所以我們不必擔心。iText頁面顏色或黑色/白色
任何想法?
我希望有一些其他的方式,比轉換爲圖像和讀取每個像素的顏色。
我試圖找出PDF文檔的頁面是否包含任何沒有黑色&使用iText的白色對象(或者可能是其他一些Java庫if你知道任何)。 我的PDF文件不應該包含圖像,所以我們不必擔心。iText頁面顏色或黑色/白色
任何想法?
我希望有一些其他的方式,比轉換爲圖像和讀取每個像素的顏色。
一個可能的解決方案是獲取頁面流並對顏色設置運算符進行正則表達式搜索。
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
我可以想像這可能會非常棘手得到的權利。更實用的解決方案可能是將頁面轉換爲圖像(使用許多可以谷歌搜索的工具之一),然後檢查圖像。
Apache PDFBox的一個可能的解決方案是創建一個圖像並檢查RGB像素。但要小心,即使PDF是純b/w,渲染圖像也可能包含灰度。
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);
}
我不知道任何lib可以幫助你,但我可以告訴你,itext將是有用的,因爲當使用itext讀取pdf時,所有格式都將被刪除。 – user979490