使用PDFBox处理PDF文档

来源:互联网 发布:桌面文件恢复软件 编辑:程序博客网 时间:2024/04/29 05:02

转载自:http://www.cnblogs.com/hejycpu/archive/2009/01/19/1378380.html

前面的介绍文本是转载的,实际上和一本书上的内容大致相同(除了代码)。

1、使用PDFBox处理PDF文档

PDF全称Portable Document Format,是Adobe公司开发的电子文件格式。这种文件格式与操作系统平台无关,可以在Windows、Unix或Mac OS等操作系统上通用。

PDF文件格式将文字、字型、格式、颜色及独立于设备和分辨率的图形图像等封装在一个文件中。如果要抽取其中的文本信息,需要根据它的文件格式来进行解析。幸好目前已经有不少工具能帮助我们做这些事情。

2、PDFBox的下载

最常见的一种PDF文本抽取工具就是PDFBox了,访问网址http://sourceforge.net/projects/pdfbox/,进入如图7-1所示的下载界面。读者可以在该网页下载其最新的版本。本书采用的是PDFBox-0.7.3版本。PDFBox是一个开源的Java PDF库,这个库允许你访问PDF文件的各项信息。在接下来的例子中,将演示如何使用PDFBox提供的API,从一个PDF文件中提取出文本信息。

3、在Eclipse中配置

以下是在Eclipse中创建工程,并建立解析PDF文件的工具类的过程。

(1)在Eclipse的workspace中创建一个普通的Java工程:ch7。

(2)把下载的PDFBox-0.7.3.zip解压。

(3)进入external目录下,可以看到,这里包括了PDFBox所有用到的外部包。复制下面的Jar包到工程ch7的lib目录下(如还未建立lib目录,则先创建一个)。

l bcmail-jdk14-132.jar

l bcprov-jdk14-132.jar

l checkstyle-all-4.2.jar

l FontBox-0.1.0-dev.jar

l lucene-core-2.0.0.jar

然后再从PDFBox的lib目录下,复制PDFBox-0.7.3.jar到工程的lib目录下。

(4)在工程上单击右键,在弹出的快捷菜单中选择“Build Path->Config Build Path->Add Jars”命令,把工程lib目录下面的包都加入工程的Build Path。

4、使用PDFBox解析PDF内容

在刚刚创建的Eclipse工程中,创建一个ch7.pdfbox包,并创建一个PdfboxTest类。该类包含一个getText方法,用于从一个PDF中获取文本信息,其代码如下。

import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;

import org.pdfbox.pdfparser.PDFParser;
import org.pdfbox.util.PDFTextStripper;


public class PdfParser {

   /**
   * @param args
   */
   // TODO 自动生成方法存根

       public   static   void   main(String[]   args)   throws   Exception{ 
            FileInputStream   fis   =   new   FileInputStream("F:\\task\\lerman-atem2001.pdf"); 
            BufferedWriter writer = new BufferedWriter(new FileWriter("F:\\task\\pdf_change.txt"));
            PDFParser   p   =   new   PDFParser(fis); 
            p.parse();         
            PDFTextStripper   ts   =   new   PDFTextStripper();         
            String   s   =   ts.getText(p.getPDDocument()); 
            writer.write(s);
            System.out.println(s); 
            fis.close(); 
            writer.close();
          
   }
}
1package TestPDF.pdfbox;  3import java.io.File;  4import java.io.FileOutputStream;  5import java.io.IOException;  6import java.io.OutputStreamWriter;  7import java.io.Writer;  8import java.net.URL; 10import org.apache.lucene.analysis.standard.StandardAnalyzer; 11import org.apache.lucene.document.Document; 12import org.apache.lucene.index.IndexWriter; 13import org.apache.lucene.index.Term; 14import org.apache.lucene.search.IndexSearcher; 15import org.apache.lucene.search.PhraseQuery; 16import org.apache.lucene.search.Query; 17import org.apache.lucene.search.ScoreDoc; 18import org.apache.lucene.search.TermQuery; 19import org.apache.lucene.search.TopDocCollector; 20import org.apache.lucene.search.TopDocs; 21import org.pdfbox.pdmodel.PDDocument; 22import org.pdfbox.searchengine.lucene.LucenePDFDocument; 23import org.pdfbox.util.PDFTextStripper; 25public class Test {   public void getText(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);               String fileName = url.getFile();                          if(fileName.length() > 4){                   //以原来pdf名称来命名新产生的txt文件                   File outputFile = new File(fileName.substring(0, fileName.length()-4) + ".txt");                   textFile = outputFile.getName();               }                       }catch(Exception 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 = 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){               document.close();           }       }           }      /** *//**    * test Lucene with pdfbox    * @throws IOException    */   public void LuceneTest() throws IOException{              String path = "D:\\index";       String pdfpath = "D:\\index\\Lucene.Net基本用法.pdf";              IndexWriter writer = new IndexWriter(path, new StandardAnalyzer(),true);       //writer.setMaxFieldLength(10240);       //LucenePDFDocument返回由PDF产生的Lucene Document       Document d = LucenePDFDocument.getDocument(new File(pdfpath));       //System.out.println(d);       //写入索引       writer.addDocument(d);       writer.close();              //读取d:\index下的索引文件,建立IndexSearcher       IndexSearcher searcher = new IndexSearcher(path);       //对索引的contents Field进行关键字Query的查找       Term t = new Term("contents","优");       Term m = new Term("contents","化");       PhraseQuery q = new PhraseQuery();       q.add(t);       q.add(m);       //Query q = new TermQuery(t);       TopDocCollector co = new TopDocCollector(10);       searcher.search(q,co);              Document document;       TopDocs docs = co.topDocs();       ScoreDoc[] doc = docs.scoreDocs;       //System.out.println(doc.length);              for(int i=0;i<doc.length;i++){           System.out.println("文档编号:" + doc[i].doc);           //document = searcher.doc(doc[i].doc);       }   }   /** *//**    * @param args    */   public static void main(String[] args) {       // TODO Auto-generated method stub       Test test = new Test();       try{           //test.getText("D:\\index\\Lucene.Net基本用法.pdf");           test.LuceneTest();       }catch(Exception e){           e.printStackTrace();       }   }139}140


原创粉丝点击