java读取pdf总结

第三方软件

1、pdfbox

PDFBox 0.7.3。PDFBox是一个开源的对pdf文件进行操作的库。 PDFBox-0.7.3.jar加入classpath。同时FontBox1.0.jar加入classpath,否则报错:

Exception in thread "main" java.lang.NoClassDefFoundError: org/fontbox/afm/FontMetric

Caused by: java.lang.ClassNotFoundException: org.fontbox.afm.FontMetric

代码1

 1 import java.io.FileInputStream;  
 2 import java.io.FileNotFoundException;  
 3 import java.io.IOException;  
 4   
 5 import org.pdfbox.pdfparser.PDFParser;  
 6 import org.pdfbox.pdmodel.PDDocument;  
 7 import org.pdfbox.util.PDFTextStripper;  
 8   
 9 public class PdfReader {  
10     /** 
11      * simply reader all the text from a pdf file.  
12      * You have to deal with the format of the output text by yourself. 
13      * 2008-2-25 
14      * @param pdfFilePath file path 
15      * @return all text in the pdf file 
16      */  
17     public static String getTextFromPDF(String pdfFilePath)   
18     {  
19         String result = null;  
20         FileInputStream is = null;  
21         PDDocument document = null;  
22         try {  
23             is = new FileInputStream(pdfFilePath);  
24             PDFParser parser = new PDFParser(is);  
25             parser.parse();  
26             document = parser.getPDDocument();  
27             PDFTextStripper stripper = new PDFTextStripper();  
28             result = stripper.getText(document);  
29         } catch (FileNotFoundException e) {  
30             // TODO Auto-generated catch block  
31             e.printStackTrace();  
32         } catch (IOException e) {  
33             // TODO Auto-generated catch block  
34             e.printStackTrace();  
35         } finally {  
36             if (is != null) {  
37                 try {  
38                     is.close();  
39                 } catch (IOException e) {  
40                     // TODO Auto-generated catch block  
41                     e.printStackTrace();  
42                 }  
43             }  
44             if (document != null) {  
45                 try {  
46                     document.close();  
47                 } catch (IOException e) {  
48                     // TODO Auto-generated catch block  
49                     e.printStackTrace();  
50                 }  
51             }  
52         }  
53         return result;  
54     }  
55     public  static void main(String[] args)  
56     {  
57         String str=PdfReader.getTextFromPDF("C:\\Read.pdf");  
58         System.out.println(str);  
59       
60     }  
61 }  

参考: http://daning.iteye.com/blog/165284

代码2

 1 import java.io.File;  
 2 import java.io.FileOutputStream;  
 3 import java.io.OutputStreamWriter;  
 4 import java.io.Writer;  
 5 import java.net.MalformedURLException;  
 6 import java.net.URL;  
 7 import org.pdfbox.pdmodel.PDDocument;  
 8 import org.pdfbox.util.PDFTextStripper;  
 9 public class PDFReader {  
10  public void readFdf(String file) throws Exception {  
11   // 是否排序  
12   boolean sort = false;  
13   // pdf文件名  
14   String pdfFile = file;  
15   // 输入文本文件名称  
16   String textFile = null;  
17   // 编码方式  
18   String encoding = "UTF-8";  
19   // 开始提取页数  
20   int startPage = 1;  
21   // 结束提取页数  
22   int endPage = Integer.MAX_VALUE;  
23   // 文件输入流,生成文本文件  
24   Writer output = null;  
25   // 内存中存储的PDF Document  
26   PDDocument document = null;  
27   try {  
28    try {  
29     // 首先当作一个URL来装载文件,如果得到异常再从本地文件系统//去装载文件  
30     URL url = new URL(pdfFile);  
31    //注意参数已不是以前版本中的URL.而是File。  
32     document = PDDocument.load(pdfFile);  
33     // 获取PDF的文件名  
34     String fileName = url.getFile();  
35     // 以原来PDF的名称来命名新产生的txt文件  
36     if (fileName.length() > 4) {  
37      File outputFile = new File(fileName.substring(0, fileName  
38        .length() - 4)  
39        + ".txt");  
40      textFile = outputFile.getName();  
41     }  
42    } catch (MalformedURLException e) {  
43     // 如果作为URL装载得到异常则从文件系统装载  
44    //注意参数已不是以前版本中的URL.而是File。  
45     document = PDDocument.load(pdfFile);  
46     if (pdfFile.length() > 4) {  
47      textFile = pdfFile.substring(0, pdfFile.length() - 4)  
48        + ".txt";  
49     }  
50    }  
51    // 文件输入流,写入文件倒textFile  
52    output = new OutputStreamWriter(new FileOutputStream(textFile),  
53      encoding);  
54    // PDFTextStripper来提取文本  
55    PDFTextStripper stripper = null;  
56    stripper = new PDFTextStripper();  
57    // 设置是否排序  
58    stripper.setSortByPosition(sort);  
59    // 设置起始页  
60    stripper.setStartPage(startPage);  
61    // 设置结束页  
62    stripper.setEndPage(endPage);  
63    // 调用PDFTextStripper的writeText提取并输出文本  
64    stripper.writeText(document, output);  
65   } finally {  
66    if (output != null) {  
67     // 关闭输出流  
68     output.close();  
69    }  
70    if (document != null) {  
71     // 关闭PDF Document  
72     document.close();  
73    }  
74   }  
75  }  
76  /** 
77   * @param args 
78   */  
79  public static void main(String[] args) {  
80   // TODO Auto-generated method stub  
81      PDFReader pdfReader = new PDFReader();  
82   try {  
83    // 取得E盘下的SpringGuide.pdf的内容  
84    pdfReader.readFdf("C:\\Read.pdf");  
85   } catch (Exception e) {  
86    e.printStackTrace();  
87   }  
88  }  
89 } 

参考:http://blog.csdn.net/weijie_search/article/details/2662189

2、抽取支持中文的pdf文件-xpdf
xpdf是一个开源项目,我们可以调用他的本地方法来实现抽取中文pdf文件。
下载xpdf函数包:
http://www.java-cn.com/technology/tech_downs/1880_004.zip
同时需要下载支持中文的补丁包:
http://www.java-cn.com/technology/tech_downs/1880_005.zip
按照readme放好中文的patch,就可以开始写调用本地方法的java程序了
下面是一个如何调用的例子:

 1 import java.io.*;  
 2 /** 
 3 * <p>Title: pdf extraction</p> 
 4 * <p>Description: email:chris@matrix.org.cn</p> 
 5 * <p>Copyright: Matrix Copyright (c) 2003</p> 
 6 * <p>Company: Matrix.org.cn</p> 
 7 * @author chris 
 8 * @version 1.0,who use this example pls remain the declare 
 9 */  
10   
11   
12 public class PdfWin {  
13 public PdfWin() {  
14 }  
15 public static void main(String args[]) throws Exception  
16 {  
17 String PATH_TO_XPDF="C:Program Filesxpdfpdftotext.exe";  
18 String filename="c:a.pdf";  
19 String[] cmd = new String[] { PATH_TO_XPDF, "-enc", "UTF-8", "-q", filename, "-"};  
20 Process p = Runtime.getRuntime().exec(cmd);  
21 BufferedInputStream bis = new BufferedInputStream(p.getInputStream());  
22 InputStreamReader reader = new InputStreamReader(bis, "UTF-8");  
23 StringWriter out = new StringWriter();  
24 char [] buf = new char[10000];  
25 int len;  
26 while((len = reader.read(buf))>= 0) {  
27 //out.write(buf, 0, len);  
28 System.out.println("the length is"+len);  
29 }  
30 reader.close();  
31 String ts=new String(buf);  
32 System.out.println("the str is"+ts);  
33 }  
34 }  

参考:http://blog.csdn.net/lyd518/article/details/2318224

3、iText

iText作为在Java中处理PDF文档的工具被广泛使用,各种开源项目中都比较常见。现在就使用iText提供的API将PDF文档中的文本信息导出为纯文本,虽然现在很多工具中都已经支持这样的操作,这是第一步也算是读取PDF文件最常见的需求。

    首先下载iText包,地址为http://sourceforge.net/projects/itext/,最新版本为5.1.2,完整包名为iText-5.1.2.zip,解压后将得到一组jar包,我们要使用的是里面的itextpdf-5.1.2.jar。在本地配置好Java编译和运行环境后,编写如下示例代码:

 1 import java.io.IOException;  
 2   
 3 import com.itextpdf.text.pdf.PdfReader;  
 4 import com.itextpdf.text.pdf.parser.PdfReaderContentParser;  
 5 import com.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy;  
 6 import com.itextpdf.text.pdf.parser.TextExtractionStrategy;  
 7   
 8 public class PDFReader {  
 9   
10  /** 
11   * @param args 
12   * @throws IOException 
13   */  
14  public static void main(String[] args) throws IOException {  
15   System.out.print(getPdfFileText("E:\\test\\plugindoc.pdf"));  
16  }  
17   
18  public static String getPdfFileText(String fileName) throws IOException {  
19   PdfReader reader = new PdfReader(fileName);  
20   PdfReaderContentParser parser = new PdfReaderContentParser(reader);  
21   StringBuffer buff = new StringBuffer();  
22   TextExtractionStrategy strategy;  
23   for (int i = 1; i <= reader.getNumberOfPages(); i++) {  
24    strategy = parser.processContent(i,  
25      new SimpleTextExtractionStrategy());  
26    buff.append(strategy.getResultantText());  
27   }  
28   return buff.toString();  
29  }  
30   
31 } 

参考:http://blog.csdn.net/mscf/article/details/6957061

1,2都不能读出目标pdf,其它pdf可以

3.1能够读出目标pdf,但是按页读取的,没法按行读取

代码2 按行读取

仿照iTextsharp

  1 package com.iText.read.pdf;  
  2   
  3   
  4 import java.io.IOException;  
  5 import java.util.Arrays;  
  6   
  7 import com.itextpdf.text.pdf.PdfReader;  
  8   
  9 public class PdfIO {  
 10       
 11       ///<summary>  
 12     ///读取单个或多个pdf  
 13     ///</summary>  
 14     ///<returns>文件内容字符串</returns>  
 15     @SuppressWarnings("null")  
 16     public static String readPdf(String fileName) throws IOException  
 17     {  
 18   
 19             PdfReader p = new PdfReader(fileName);  
 20             //从每一页读出的字符串  
 21             String str = null;  
 22             //"[......]"内部字符串  
 23             String subStr =null;  
 24             //函数返回的字符串  
 25             StringBuffer rtBuf=new  StringBuffer();  
 26               
 27             String rtStr=null;  
 28               
 29             //"[","]","(",")"在字符串中的位置  
 30             int bg = 0, ed = 0, subbg = 0, subed = 0;  
 31   
 32   
 33   
 34             //":"前面的字符串  
 35             String fc =null;  
 36   
 37             //":"前面的字符串  
 38             String bc =null;  
 39   
 40             
 41   
 42             //取得文档总页数  
 43             int pg = p.getNumberOfPages();  
 44   
 45   
 46             // ExcelIO ei = new ExcelIO();  
 47             for (int i = 1; i <= 1; i++)  
 48             {  
 49            
 50   
 51                 bg = 0;  
 52                 ed = 0;  
 53   
 54                //Arrays.fill(b, 0);  
 55                   
 56               //从每一页读出的8位字节数组  
 57                 byte[] b = new byte[0];  
 58                 //取得第i页的内容  
 59                 b = p.getPageContent(i);  
 60   
 61                 //下一行是把每一页的取得的字节数据写入一个txt的文件,仅供研究时用  
 62                 //System.IO.File.WriteAllBytes(Application.StartupPath + "//P" + i.ToString() + ".txt", b);  
 63   
 64                 StringBuilder sb = new StringBuilder();  
 65   
 66                 //取得每一页的字节数组,将每一个字节转换为字符,并将数组转换为字符串  
 67                 for (int j = 0; j < b.length; j++) sb.append((char)(b[j]));  
 68                 str = sb.toString();  
 69               
 70                 //return str;  
 71   
 72                if (str.indexOf("[") >= 0)  
 73                 {  
 74   
 75                     //循环寻找"["和"]",直到找不到"["为止  
 76                     while (bg > -1)  
 77                     {  
 78                         //取得下一个"["和"]"的位置  
 79                         bg = str.indexOf("[", ed);  
 80                         ed = str.indexOf("]", bg + 1);  
 81   
 82                         //如果没有下一个"["就跳出循环  
 83                         if (bg == -1) break;  
 84   
 85                         //取得一个"[]"里的内容,将开始寻找"("和")"的位置初始为0  
 86                         subStr = str.substring(bg + 1, ed - bg - 1);  
 87                         subbg = 0;  
 88                         subed = 0;  
 89   
 90                         //循环寻找下一个"("和")",直到没有下一个"("就跳出循环  
 91                         while (subbg > -1)  
 92                         {  
 93                             //取得下一对"()"的位置  
 94                             subbg = subStr.indexOf("(", subed);  
 95                             subed = subStr.indexOf(")", subbg + 1);  
 96   
 97                             //如找不到下一对就跳出  
 98                             if (subbg == -1) break;  
 99                             //在返回字符串后面加上新找到的字符串  
100                             rtStr = subStr.substring(subbg + 1, subed - subbg - 1);  
101   
102   
103   
104                         }  
105                         rtStr+= rtStr + "|";  
106                     }  
107                     return rtStr;  
108                 }  
109                 else  
110                 {  
111                     //每页的行数  
112                     int lineNumber = 0;  
113                     while (bg > -1)  
114                     {  
115                         //取得下一个"("和")"的位置  
116                         bg = str.indexOf("(", ed);  
117                         ed = str.indexOf(")", bg + 1);  
118                         //如果没有下一个"["就跳出循环  
119                         if (bg == -1) break;  
120                         //每行加个'|'为以后分隔准备,为什么不用"/n/r",因为不需要换行功能  
121                         //rtStr += str.substring(bg + 1, ed-1) + "|";  
122                           
123                         String rtStrTemp = str.substring(bg + 1, ed-1);  
124                           
125                         rtBuf.append(rtStrTemp);  
126                         rtBuf.append("|");  
127   
128                     }  
129                     rtStr=rtBuf.toString();  
130                      
131   
132                 }  
133                   
134   
135             }  
136             if (p != null)  
137             {  
138                 p.close();  
139             }  
140       
141             return rtStr;   
142               
143             
144     }  
145   
146 }

 

posted @ 2018-06-12 14:01  wangwiz  阅读(53227)  评论(2编辑  收藏  举报