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

8

我目前正在使用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();  
             }  
 }  

我希望你能帮助我。

提前感谢你。

2个回答

4
如果您使用WordExtractor,将只获取文本。尝试使用CharacterRun类,您将获得带有样式的文本。请参考以下示例代码。
Range range = doc.getRange();
for (int i = 0; i < range.numParagraphs(); i++) {
    org.apache.poi.hwpf.usermodel.Paragraph poiPara = range.getParagraph(i);
    int j = 0;
    while (true) {
        CharacterRun run = poiPara.getCharacterRun(j++);
        System.out.println("Color "+run.getColor());
        System.out.println("Font size "+run.getFontSize());
        System.out.println("Font Name "+run.getFontName());
        System.out.println(run.isBold()+" "+run.isItalic()+" "+run.getUnderlineCode());
        System.out.println("Text is "+run.text());
        if (run.getEndOffset() == poiPara.getEndOffset()) {
            break;
        }
    }
}

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文档中的每个字符运行中的所有内容都应用了相同的格式。因此,一个段落由一个或多个字符运行组成。一些样式应用于段落,而其他部分则应用于运行。根据您感兴趣的格式,可能在段落或运行中进行。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接