我目前正在使用 apache poi 进行 Java 项目。 现在在我的项目中我想将 doc 文件转换为 pdf 文件。转换成功完成,但我只得到 pdf 中的文本,没有任何文本样式或文本颜色。 我的 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();
}
}
请帮助我。
提前致谢。
最佳答案
如果您查看 Apache Tika,就会发现有一个从 HWPF 文档中读取一些样式信息的好示例。 Tika 中的代码根据 HWPF 内容生成 HTML,但您应该会发现非常相似的内容适用于您的情况。
关于 Word 文档需要注意的一件事是,任何一个 Character Run 中的所有内容都应用了相同的格式。因此,段落由一个或多个字符串组成。某些样式应用于段落,其他部分则在运行中完成。根据您感兴趣的格式,它可能位于段落或运行中。
关于java - Apache POI HWPF - 将 doc 文件转换为 pdf 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3352116/