Java pdf轉String 並修正格式

來源:互聯網
上載者:User

標籤:代碼   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 並修正格式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.