Apache POI HWPF - 将doc文件转换为pdf时出现问题

use*_*305 7 java apache hwpf apache-poi

我目前正在使用apache poi工作Java项目.现在,在我的项目中,我想将doc文件转换为pdf文件.转换成功完成但我只获得pdf中的文本而不是任何文本样式或文本颜色.我的pdf文件看起来像黑白.虽然我的doc文件是彩色的,并且具有不同的文本样式.

这是我的代码,

 POIFSFileSystem fs = null;  
 Document document = new Document(); 

 try {  
     System.out.println("Starting the test");  
     fs = new POIFSFileSystem(new FileInputStream("/document/test2.doc"));  

     HWPFDocument doc = new HWPFDocument(fs);  
     WordExtractor we = new WordExtractor(doc);  

     OutputStream file = new FileOutputStream(new File("/document/test.pdf")); 

     PdfWriter writer = PdfWriter.getInstance(document, file);  

     Range range = doc.getRange();
     document.open();  
     writer.setPageEmpty(true);  
     document.newPage();  
     writer.setPageEmpty(true);  

     String[] paragraphs = we.getParagraphText();  
     for (int i = 0; i < paragraphs.length; i++) {  

         org.apache.poi.hwpf.usermodel.Paragraph pr = range.getParagraph(i);
        // CharacterRun run = pr.getCharacterRun(i);
        // run.setBold(true);
        // run.setCapitalized(true);
        // run.setItalic(true);
         paragraphs[i] = paragraphs[i].replaceAll("\\cM?\r?\n", "");  
     System.out.println("Length:" + paragraphs[i].length());  
     System.out.println("Paragraph" + i + ": " + paragraphs[i].toString());  

     // add the paragraph to the document  
     document.add(new Paragraph(paragraphs[i]));  
     }  

     System.out.println("Document testing completed");  
 } catch (Exception e) {  
     System.out.println("Exception during test");  
     e.printStackTrace();  
 } finally {  
                 // close the document  
    document.close();  
             }  
 }  
Run Code Online (Sandbox Code Playgroud)

请帮我.

Thnx提前.

Gag*_*arr 4

如果您查看 Apache Tika,就会发现有一个从 HWPF 文档中读取一些样式信息的好示例。Tika 中的代码根据 HWPF 内容生成 HTML,但您应该发现非常相似的内容适用于您的情况。

Tika 类是 https://svn.apache.org/repos/asf/tika/trunk/tika-parsers/src/main/java/org/apache/tika/parser/microsoft/WordExtractor.java

关于 Word 文档需要注意的一件事是,任何一个 Character Run 中的所有内容都应用了相同的格式。因此,段落由一个或多个字符串组成。某些样式应用于段落,其他部分则在运行中完成。根据您感兴趣的格式,它可能位于段落或运行中。