我尝试使用 PDFBox在常规 .pdf
文件上运行良好。
然而,当我遇到损坏的 .pdf
时,代码会“卡住”.. 不会抛出错误或其他东西 .. 只是 load
或 parse
函数需要永远执行
这里是 the corrupted file (我把它压缩了,这样每个人都可以下载),它可能不是原生的 pdf 文件,但它被保存为 .pdf
扩展名,而且只有 4 Kb。
我根本不是专家,但我认为这是 PDFBox 的一个错误。根据文档,load()
和 parse()
方法都应该在失败时抛出异常。但是对于我的文件,代码将永远执行并且不会抛出异常。
我试过只使用load
,可以试试parse()
.. 结果是一样的
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;
public class TestTest {
public static void main(String[] args) throws FileNotFoundException, IOException {
System.out.println(pdfToText("C:\\..............MYFILE.pdf"));
System.out.println("done ! ! !");
}
private static String pdfToText(String fileName) throws IOException {
PDDocument document = null;
document = PDDocument.load(new File(fileName)); // THIS TAKES FOREVER
PDFTextStripper stripper = new PDFTextStripper();
document.close();
return stripper.getText(document);
}
}
如果 .pdf
文件已损坏,如何强制此代码抛出异常或停止执行?
谢谢
最佳答案
试试这个解决方案:
private static String pdfToText(String fileName) {
PDDocument document = null;
try {
document = PDDocument.load(fileName);
PDFTextStripper stripper = new PDFTextStripper();
return stripper.getText(document);
} catch (IOException e) {
System.err.println("Unable to open PDF Parser. " + e.getMessage());
return null;
} finally {
if (document != null) {
try {
document.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
关于java - PDFBox 中的 load() 和 parse() 方法可能存在错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20004290/