我正在使用 iText 读取 PDF 文档。我收到 ArrayIndexOutOfBoundsException。奇怪的是,它只发生在某些文件和这些文件中的某些位置。我怀疑这与 PDF 在这些位置的编码方式有关,但无法找出问题所在。
我看过这个问题Read pdf using iText但他似乎通过更改该文件的位置解决了他的问题。这对我来说不起作用,因为我在某些文件中的某些位置遇到了异常 - 所以导致异常的不是文件本身,而是相关页面。
堆栈跟踪是
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Invalid index: 02 at com.lowagie.text.pdf.CMapAwareDocumentFont.decodeSingleCID(Unknown Source) at com.lowagie.text.pdf.CMapAwareDocumentFont.decode(Unknown Source) at com.lowagie.text.pdf.parser.PdfContentStreamProcessor.decode(Unknown Source) at com.lowagie.text.pdf.parser.PdfContentStreamProcessor.displayPdfString(Unknown Source) at com.lowagie.text.pdf.parser.PdfContentStreamProcessor$ShowText.invoke(Unknown Source) at com.lowagie.text.pdf.parser.PdfContentStreamProcessor.invokeOperator(Unknown Source) at com.lowagie.text.pdf.parser.PdfContentStreamProcessor.processContent(Unknown Source) at com.lowagie.text.pdf.parser.PdfTextExtractor.getTextFromPage(Unknown Source) at com.pdfextractor.main.Extractor.main(Extractor.java:61)
第 61 行对应于这一行:
content = extractor.getTextFromPage(page);
所以很明显 getTextFromPage() 方法不起作用。
public static void main(String[] args) throws IOException{
ArrayList<String> keywords = new ArrayList<String>();
keywords.add("location");
keywords.add("Mass Spectrometry");
keywords.add("vacuole");
keywords.add("cytosol");
String directory = "C:/Ankur/Projects/PEB/Extractor/papers/";
File directoryToRead = new File(directory);
String[] sa_filesToRead = directoryToRead.list();
List<String> filesToRead = Arrays.asList(sa_filesToRead);
Iterator<String> fileItr = filesToRead.iterator();
while(fileItr.hasNext()){
String nextFile = fileItr.next();
PdfReader reader = new PdfReader(directory+nextFile);
int noPages = reader.getNumberOfPages();
PdfTextExtractor extractor = new PdfTextExtractor(reader);
String content="";
for(int page=1;page<=noPages;page++){
int index = 1;
System.out.println(page);
content = extractor.getTextFromPage(page);
}
}
}
最佳答案
大多数 Java 类/库都希望像 getTextFromPage(int)
这样的方法从 0 开始索引 - 这意味着 getTextFromPage(0)
应返回第 1 页的文本,getTextFromPage(1)
应返回第 2 页的文本。
导致 ArrayIndexOutOfBoundsException 的 for 循环的索引从 1 开始。
您确定 iText 的 getTextFromPage(int)
索引是从 1 开始的,而不是(几乎)标准的 0 开始的吗?
关于java - 使用 iText 读取 PDF 文档有时无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1753615/