第三方軟件
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 }
