2012-07-11 135 views
0

我想通過使用Apache POI(對於doc來將它們轉換爲單個字符串來閱讀和處理.doc,.docx,.pdf文件,docx)和Apache PDFBox(用於pdf)庫。
它工作正常,直到它遇到文本框。 如果格式是這樣的:

段落1個
文本框1
第2段
文本框2
第3段

然後輸出應爲:
第1文本框1第2段文本框2第3段
但我得到的輸出爲:
第1款第2款第3款文本框1個文本框2

似乎在最後,而不是在這個地方要添加文本框的地方翔即,在段落之間。這個問題在doc和pdf文件的情況下都是如此。這意味着圖書館,POI和PDFBox都會帶來同樣的問題。

閱讀PDF文件中的代碼爲:
在使用Apache POI和Apache PDF閱讀器閱讀文檔,pdf文件中的錯位文本框

 

    void pdf(String file) throws IOException { 
     //Initialise file 
     File myFile = new File(file); 
     PDDocument pdDoc = null; 
     try { 
      //Load PDF 
      pdDoc = PDDocument.load(myFile); 
      //Create extractor 
      PDFTextStripper pdf = new PDFTextStripper(); 
      //Extract text 
      output = pdf.getText(pdDoc); 
     } 
     finally { 
      if(pdDoc != null) 
       //Close document 
       pdDoc.close(); 
     } 
    } 

併爲doc文件的代碼爲:

 

    void doc(String file) throws FileNotFoundException, IOException { 
     File myFile = null; 
     WordExtractor extractor = null ; 
     //initialise file 
     myFile = new File(file); 
     //create file input stream 
     FileInputStream fis=new FileInputStream(myFile.getAbsolutePath()); 
     //open document 
     HWPFDocument document=new HWPFDocument(fis); 
     //create extractor 
     extractor = new WordExtractor(document); 
     //get text from document 
     output = extractor.getText(); 
    } 

+0

您可能會發現文本框被錨定到一個段落,並且您無意中移動/丟失錨點。如果您可以讓iText向您提供有關文本框錨點的信息,那麼也許您可以保留或重置它。 – 2012-07-30 04:28:31

+0

你有直接使用底層庫的原因嗎?使用[Apache Tika](http://tika.apache.org)可能會簡單得多,它包裝庫並生成一致的文本 – Gagravarr 2015-01-05 13:14:25

回答

0

對於PDFBox的做到這一點: pdf.setSortByPosition(真);