標籤:代碼 mode 斷行符號 images 比較 class 設定 odi new
在嘗試pdf轉成String的時候,首先用python的pdfminer和pdfminer3k去嘗試轉換,然後資料看不太懂,就嘗試用了java,
以下是java的pdfbox寫的pdf轉String函數(main函數沒有貼出來,直接用的一個全域函數) 需要加入的包有
百度搜一下pdfbox去官網下載一個放在lib裡就行了
然後比較重要的突破是能把原來產生格式比較混亂的String處理成比較能看的String
效果如下:
沒有轉換前輸出格式如下
轉換後格式:
代碼如下:
import java.io.*;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
public static String getText(String file) throws Exception {
// 是否排序
boolean sort = false;
// PDF的本地路徑或者url
String pdfFile = file;
// 編碼方式
String encoding = "UTF-8";
// 開始提取頁數
int startPage = 1;
// 結束提取頁數
int endPage = Integer.MAX_VALUE;
// 檔案輸入資料流,產生文字檔
Writer output = null;
// 記憶體中儲存的PDF Document
PDDocument document = null;
try{
// 採用PDFTextStripper提取文本
PDFTextStripper stripper = new PDFTextStripper();
// 設定是否排序
stripper.setSortByPosition(sort);
// 設定起始頁
stripper.setStartPage(startPage);
// 設定結束頁
stripper.setEndPage(endPage);
String text = stripper.getText(document);
//嘗試把前邊或後邊接有空白字元的分行符號換成其他的文字,然後把分行符號替換掉,之後再把其他文字換成分行符號
//原理是pdf轉成String中間有過多的斷行符號分行符號\r\n這種,但是如果分行符號前後都是有文字的(不為空白),則這應該是一個被pdf強行換行出來的
text = text.replaceAll("\\r\\n\\s","Jacck"); //這裡的Jacck最好換成一個更複雜的文本,作為中間替換物存在盡量在中間轉化過程中和文檔中沒有任何匹配
text = text.replaceAll("\\s\\r\\n","Jacck");
text = text.replaceAll("\\n|\\r",""); //處理掉被強行加上來的斷行符號分行符號
text = text.replaceAll("Jacck","\r\n");
return text;
// stripper.writeText(document, output);
}catch(Exception e){
e.printStackTrace();
}finally{
if(document != null){
document.close();
}
}
return "";
}
Java pdf轉String 並修正格式