如何将PDF转换为文本文件并保留PDF的格式?

时间:2012-01-05 13:01:03

标签: java pdf text file-conversion

您好我想将PDF文件转换为文本文件。我正在将PDF文件转换为文本文件。但它并不保留完全以PDF文件格式的文本格式。

请帮帮我。

3 个答案:

答案 0 :(得分:4)

文本文件本身不能包含格式。

您无法在纯文本文件中保留格式,因为它只包含文本。文本文件中可能有HTML标记,但我会称之为HTML文件。否则,您应该尝试将其转换为富文本格式(RTF),Microsoft Word,OpenOffice或其他一些文档类型。

答案 1 :(得分:1)

PDFBox会帮助你,因为它可能会失去一些格式正如Erick Robertson所说

参考PDF Text Parser: Converting PDF to Text in Java using PDFBox

答案 2 :(得分:1)

这可以帮到你。

File f = new File(fileName);
        if (!f.isFile()) {  
            return null;  
        } 


        try {
            parser = new PDFParser(new FileInputStream(f));
        } catch (Exception e) {
            return null;
        }  

        try {
            parser.parse();
            cosDoc = parser.getDocument();  
            pdfStripper = new PDFTextStripper();
           /* pdfStripper.setStartPage(2); 
            pdfStripper.setEndPage(3);*/  
            pdDoc = new PDDocument(cosDoc);
            parsedText = pdfStripper.getText(pdDoc);
        } catch (Exception e) {  
            System.out.println("An exception occured in parsing the PDF Document.");  
            e.printStackTrace();  
            try {  
                   if (cosDoc != null) cosDoc.close();  
                   if (pdDoc != null) pdDoc.close();  
               } catch (Exception e1) {  
               e.printStackTrace();  
            }  
            return null;  
        }