我需要从pdf提取文本以验证某些内容,并使用java计算pdf文档中的图像数量。我可以使用下面的getText函数毫无问题地获取文本内容,但找不到仅对图像对象计数的方法。我已经能够使用下面的代码获得所有对象的计数,但是找不到关于如何仅计数图像的任何文档。任何想法将不胜感激。谢谢
static String getText(File pdfFile) throws IOException {
PDDocument doc = PDDocument.load(pdfFile);
return new PDFTextStripper().getText(doc);
}
static void countImages(File pdfFile) throws IOException{
PDDocument doc = PDDocument.load(pdfFile);
List myObjects = doc.getDocument().getObjects();
System.out.println("Count: " + myObjects.size());
doc.close();
}
最佳答案
一个快速而肮脏的解决方案可能看起来像这样:
static void countImages(File pdfFile) throws IOException{
PDDocument doc = PDDocument.load(pdfFile);
PDResources res = doc.getDocumentCatalog().getPages().getResources();
int numImg = 0;
for (PDXObject xobject : res.getXObjects().values()) {
if (xobject instanceof PDXObjectImage) {
numImg++;
}
}
System.out.println("Count: " + numImg);
doc.close();
}