`

使用PDFBox处理PDF文档

阅读更多
最常见的一种PDF文本抽取工具就是PDFBox了。PDFBox是一个开源的Java PDF库,这个库允许你访问PDF文件的各项信息。在接下来的例子中,将演示如何使用PDFBox提供的API,从一个PDF文件中提取出文本信息。
PDFBox下载:访问网址http://sourceforge.net/projects/pdfbox/,进入如图7-1所示的下载界面。读者可以在该网页下载其最新的版本。本书采用的是PDFBox-0.7.3版本。
1.创建PdfboxTest类。该类包含一个getText方法,用于从一个PDF中获取文本信息
public void geText(String file) throws Exception {
// 是否排序
   boolean sort = false;
// pdf文件名
   String pdfFile = file;
// 输入文本文件名称
   String textFile = null;
// 编码方式
   String encoding = "UTF-8";
// 开始提取页数
   int startPage = 1;
// 结束提取页数
   int endPage = Integer.MAX_VALUE;
// 文件输入流,生成文本文件
   Writer output = null;
// 内存中存储的PDF Document
   PDDocument document = null;
try {
      try {
         // 首先当作一个URL来装载文件,如果得到异常再从本地文件系统//去装载文件
         URL url = new URL(pdfFile);
         document = PDDocument.load(url);
         // 获取PDF的文件名
         String fileName = url.getFile();
        
// 以原来PDF的名称来命名新产生的txt文件
         if (fileName.length() > 4) {
            File outputFile = new File(fileName.substring(0, fileName.length() - 4) + ".txt");
            textFile = outputFile.getName();
         }
      } catch (MalformedURLException e) {
        
// 如果作为URL装载得到异常则从文件系统装载
         document = PDDocument.load(pdfFile);
         if (pdfFile.length() > 4) {
            textFile = pdfFile.substring(0, pdfFile.length() - 4) + ".txt";
         }
      }
      // 文件输入流,写入文件倒textFile
      output = new OutputStreamWriter(new FileOutputStream(textFile), encoding);
      // PDFTextStripper来提取文本
      PDFTextStripper stripper = null;
      stripper = new PDFTextStripper();
// 设置是否排序
      stripper.setSortByPosition(sort);
// 设置起始页
      stripper.setStartPage(startPage);
// 设置结束页
      stripper.setEndPage(endPage);
// 调用PDFTextStripper的writeText提取并输出文本
      stripper.writeText(document, output);
   } finally {
      if (output != null) {
         // 关闭输出流
         output.close();
      }
      if (document != null) {
         // 关闭PDF Document
         document.close();
      }
   }
}


在上面的代码中,getText方法接收一个 String类型的参数,指定要提取的PDF文件路径。这个位置可以是一个URL或本地文件。然后函数调用PDFBox提供的 PDFTextStripper类,设置提取过程中的一些属性(如起始页、是否排序等)。最后将文本提取并写入文件。

2.运行

public static void main(String[] args) {
   PdfboxTest test = new PdfboxTest();
   try {
      // 取得C盘下的index.pdf的内容
      test.geText("C:\\index.pdf");
   } catch (Exception e) {
      e.printStackTrace();
   }
}



3.与Lucene的集成
PDFBox还提供和Lucene的集成,它提供了一套简单的方法把PDF Documents加入到Lucene的索引中去,请看以下代码:
Document lucenedocument = LucenePDFDocument.getDocument(…);
其中,LucenePDFDocument是 PDFBox中提供的一个类,它的getDocument被重载为3个方法,分别接收一个File对象、InputStream对象或者URL对象作为参数,然后从该参数传递进来的PDF文件中,提取并生成Lucene的Document对象。
当通过PDFBox从一个PDF文档中得到一个 Lucene Document后,可以直接使用IndexWriter把它加到Lucene的index中。LucenePDFDocument自动从PDF文件中提 取各种元数据Field,并把它们加入到Document中。它提取的信息如
新建新建一个PdfLuceneTest类
public class PdfLuceneTest {
    public static void main(String[] args) {
        try {
            // IndexWriter存放索引到d:\index下
            IndexWriter writer = new IndexWriter("d:\\index",
                    new StandardAnalyzer(), true);
            // LucenePDFDocument返回由PDF产生的Lucene Docuement
            Document d = LucenePDFDocument
                    .getDocument(new File("C:\\index.pdf"));  // 注:关键点
            // 写入索引
            writer.addDocument(d);
            // 关闭索引文件流
            writer.close();
            // 读取d:\index下的索引文件建立IndexSearcher
            IndexSearcher searcher = new IndexSearcher("d:\\index");
            // 对索引的contents Field进行查找关键词poi
            Term t = new Term("contents", "poi");
            // 根据Term生成Query
            Query q = new TermQuery(t);
            // 搜索返回结果集
            Hits hits = searcher.search(q);
            // 打印结果集
            for (int i = 0; i < hits.length(); i++) {
                System.out.println(hits.doc(i));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


   函数利用LucenePDFDocument的 getDocument函数,从一个PDF文件直接返回一个Lucene的Document,其中包含有path、url、modified、 contents、summary等Field,把它们直接写入index,然后创建一个IndexSearcher,对contents字段经行检索, 查找关键词“poi”(注意必须是小写)
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics