我目前正在使用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();
}
} 请帮帮我。
要提前做好准备。
发布于 2011-04-07 21:48:28
如果您查看Apache Tika,就会发现从HWPF文档中读取一些样式信息是一个很好的示例。Tika中的代码根据HWPF内容生成HTML,但是您会发现一些非常类似的东西也适用于您的情况。
关于word文档需要注意的一点是,任何一个字符运行中的所有内容都应用了相同的格式。因此,一个段落由一个或多个字符串组成。一些样式应用于段落,而其他部分则在管路上完成。根据您感兴趣的格式,它可能在段落中,也可能在运行中。
发布于 2012-03-13 18:28:27
如果你使用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;
}
}
}https://stackoverflow.com/questions/3352116
复制相似问题