java运行。getFontFamily()为返回null。使用apachepoi的docx文件
我想读一本书。docx文件逐段归档,我想检查每个段落的字体系列、字体大小、边距、对齐方式、颜色等。 这是我的一个例子。docx文件:
这是我的代码:
FileInputStream fis = new FileInputStream("D:/test3.docx");
XWPFDocument docx = new XWPFDocument(fis);
List<XWPFParagraph> paragraphList = docx.getParagraphs();
for (int i = 0; i < paragraphList.size(); i++) {
System.out.println("paragraph " + i + " is:: " + paragraphList.get(i).getText());
for (XWPFRun run : paragraphList.get(i).getRuns()) {
System.out.println("paragraph :: run text is:: " + run.text());
System.out.println("paragraph :: run color is:: " + run.getColor());
System.out.println("paragraph :: run font-famyly is:: " + run.getFontFamily()); //It always return null; why?
System.out.println("paragraph :: run font-name is:: " + run.getFontName()); //It always return null; why?
System.out.println("paragraph :: run text position is:: " + run.getTextPosition()); //It always return -1; why?
System.out.println("paragraph :: run font-size is:: " + run.getFontSize());
System.out.println("paragraph :: run IsBold:: " + run.isBold());
System.out.println("paragraph :: run IsItalic:: " + run.isItalic());
}}
但是fontFamily(对于我选择的每个字体系列)、fontName和textPosition始终为空。 我有另一个代码示例来执行此操作:
XWPFStyles styles = docx.getStyles();
for (int i = 0; i < paragraphList.size(); i++) {
System.out.println("paragraph " + i + " styleID is:: " + paragraphList.get(i).getStyleID());
if (paragraphList.get(i).getStyleID() != null) {
String styleid = paragraphList.get(i).getStyleID();
XWPFStyle style = styles.getStyle(styleid);
if (style != null) {
System.out.println("style name is:: " + style.getName());
if (style.getName().startsWith("heading")) {
System.out.println("This part of text is heading!!");
}
}
}
}
但除标题外,样式通常为空
# 1 楼答案
ApachePOI解析
document.xml
文件的.docx
部分。执行run.getFontFamily()
时,仅当字体系列出现在运行的运行属性中时,才会返回该字体系列。否则它将返回null。例如,考虑这个样本运行在
<w:rPr>
运行属性标签中指定了它的字体系列。在这样的情况下,你必须在层次结构上,看看这个段落是否有一种风格。如果即使是<w:Pr>
段落属性也没有样式,则应用文档默认的字体系列。文档默认值在styles.xml
文件中指定# 2 楼答案
我发现我想检查的字体不是标准的!!因此,对于另一种标准字体,以上所有代码都非常完美
# 3 楼答案
下面是从样式中获取样式的示例代码。使用ApachePOI的xml
希望这能有所帮助