2010-07-28 74 views
6

我目前正在使用apache poi工作Java项目。 现在在我的项目中,我想将doc文件转换为pdf文件。转换成功完成,但我只以pdf格式获取文本,而不是任何文本样式或文本颜色。 我的pdf文件看起来像一个黑色&白色。虽然我的文档文件是彩色的,并有不同风格的文字。Apache POI HWPF - 将doc文件转换为pdf的问题

这是我的代码,

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(); 
      } 
} 

请帮助我。

Thnx提前。

回答

4

如果您看看Apache Tika,可以从HWPF文档中阅读一些样式信息。 Tika中的代码根据HWPF内容生成HTML,但您应该发现一些非常类似的东西适用于您的案例。

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

有一点需要注意的Word文档的是,一切都在任意一个字符运行应用了相同的格式。段落因此由一个或多个字符运行组成。一些样式适用于段落,其他部分则在运行中完成。取决于你对格式的兴趣,因此可能在段落或跑步上。

3

如果您使用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; 
     } 
    } 
} 
相关问题