我尝试使用PDFBox http://pdfbox.apache.org/定期.pdf
文件并且工作正常。
但是当我遇到损坏的.pdf
,代码会“冻结”..不抛出错误或其他东西..简单地说load
or parse
函数需要永远执行
Here is 损坏的文件 https://dl.dropboxusercontent.com/u/41007907/MYFILE.zip(我已将其压缩,以便每个人都可以下载),它可能不是本机 pdf 文件,但它被保存为.pdf
扩展名只有 4 Kb。
我根本不是专家,但我认为这是 PDFBox 的一个错误。根据文档,两者load()
and 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();
}
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)