使用pdfbox从PDF文件中提取文本

时间:2013-01-16 08:54:14

标签: java pdf jsoup pdfbox

我正在尝试使用pdfbox从PDF文件中提取文本,但不是作为命令行工具,而是在我的Java应用程序中。我正在使用jsoup下载pdf。

res = Jsoup
.connect(host+action)
.ignoreContentType(true)
.data(data)
.cookies(cookies)
.method(Method.POST)
.timeout(20*1000)
.execute();

// prepare document
InputStream is = new ByteArrayInputStream(res.bodyAsBytes()); 
PDDocument pdf = new PDDocument();
pdf.load(is,true);

// extract text
PDFTextStripper stripper = new PDFTextStripper();
String text = stripper.getText(pdf);

// print extracted text
System.out.println(text);

此代码仅打印空行。当我这样做时:

System.out.println(res.body());

它打印pdf文件输出如下:

%PDF-1.4
%����
6 0 obj
<<
/Filter /FlateDecode
/Length 1869
>>
stream
x��X�n��

...

<<
/Size 28
/Info 27 0 R
/Root 26 0 R
>>
startxref
20632
%%EOF

所以我确信pdf已正确下载 - 只是这个PDF剥离器无效......

----------------------------------------------编辑

此问题已解决 - 工作代码在http://thottingal.in/blog/2009/06/24/pdfbox-extract-text-from-pdf/

1 个答案:

答案 0 :(得分:2)

(问题在评论中回答。见Question with no answers, but issue solved in the comments (or extended in chat)

@WeloSefer写道:

  

也许this可以帮助你开始...我从来没有使用过jsoup或pdfbox所以我没有帮助,但我肯定会尝试pdfbox,因为我一直在测试itextpdf阅读器来提取文本。

OP写道:

  

谢谢,这就是我想要的 - 它现在有效:)   这个问题已经解决了 - 工作代码在这里http://thottingal.in/blog/2009/06/24/pdfbox-extract-text-from-pdf/