2013-08-01 109 views
4

如何使用Java将pdf文件转换为word文件?如何将pdf文件转换为使用Java的word文件

而且,它看起来很简单吗?

+0

谷歌它,你会发现你的答案。你也应该使用stackoverflow的搜索引擎... – ZeusNet

+1

你可以使用aphace poi。 http://poi.apache.org/ –

+1

它看起来容易吗? –

回答

7

尝试PDFBOX

public class PDFTextReader 
{ 
    static String pdftoText(String fileName) { 
     PDFParser parser; 
     String parsedText = null; 
     PDFTextStripper pdfStripper = null; 
     PDDocument pdDoc = null; 
     COSDocument cosDoc = null; 
     File file = new File(fileName); 
     if (!file.isFile()) { 
      System.err.println("File " + fileName + " does not exist."); 
      return null; 
     } 
     try { 
      parser = new PDFParser(new FileInputStream(file)); 
     } catch (IOException e) { 
      System.err.println("Unable to open PDF Parser. " + e.getMessage()); 
      return null; 
     } 
     try { 
      parser.parse(); 
      cosDoc = parser.getDocument(); 
      pdfStripper = new PDFTextStripper(); 
      pdDoc = new PDDocument(cosDoc); 
      parsedText = pdfStripper.getText(pdDoc); 
     } catch (Exception e) { 
      System.err 
        .println("An exception occured in parsing the PDF Document." 
          + e.getMessage()); 
     } finally { 
      try { 
       if (cosDoc != null) 
        cosDoc.close(); 
       if (pdDoc != null) 
        pdDoc.close(); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
     return parsedText; 
    } 
    public static void main(String args[]){ 

     try { 

      String content = pdftoText(PDF_FILE_PATH); 

      File file = new File("/sample/filename.txt"); 

      // if file doesnt exists, then create it 
      if (!file.exists()) { 
       file.createNewFile(); 
      } 

      FileWriter fw = new FileWriter(file.getAbsoluteFile()); 
      BufferedWriter bw = new BufferedWriter(fw); 
      bw.write(content); 
      bw.close(); 

      System.out.println("Done"); 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 
+0

下载jar:http://mirror.nexcess.net/apache/pdfbox/1.8.2/pdfbox-1.8.2.jar – newuser

+1

非常感谢,但请问图像和数学字符怎么样?我需要直接将其转换为Word文件吗? – Gentuzos

+0

您的PDF有图像和数学字符 – newuser

4

我已经深深的看了这个问题,我发现,对于正确的结果,你需要无法避免同时使用微软Word。甚至像LibreOffice这样的资助项目也会因为Word格式相当复杂而改变版本而与正确的转换相抗争。只有MS Word会跟踪这一点。

因此,我实施了documents4j将使用Java API的转换委托给MS Word。此外,它还允许您将转换移至另一台可以使用REST API联系的机器。您可以找到详细信息on its GitHub page

+0

'类型com.documents4j.job.AbstractConverterBuilder无法解析。它是从所需的.class文件中间接引用的,并且该类型不存在于javadoc参考中 – Mauro

+0

看起来像您的类路径不完整。 javadoc只包含官方的API类。 –

相关问题