I have a Word document, in that we have a variables like @DATE. When we read it as XWPFRun from XWPFParagraph, we get two runs 1. “@” and 2. “DATE.
How can I get the font size of “DATE” (2nd run)? I am getting first run “@” font size, but null for second run “DATE”
for (XWPFParagraph p : cell.getParagraphs()) {
for(XWPFRun r1 : p.getRuns()){
iFontSize = r1.getFontSizeAsDouble()
}
}
So here, for the second run “DATE”, getFontSizeAsDouble returns null.
The API documentation of XWPFRun.getFontSizeAsDouble states:
Returns:
value representing the font size (can be null if size not set)
If font size not set, then default font size is used. The default font is stored in document styles.
XWPFDocument.getStyles -> XWPFStyles.getDefaultRunStyle -> XWPFDefaultRunStyle.getFontSizeAsDouble.
If neither default run style nor document styles are present, then I would assume standard font Calibri in size 11.
...
Double dFontSize;
XWPFTableCell cell ...
...
for (XWPFParagraph paragraph : cell.getParagraphs()) {
for(XWPFRun run : paragraph.getRuns()) {
System.out.println(run);
dFontSize = run.getFontSizeAsDouble();
if (dFontSize == null) {
XWPFStyles styles = document.getStyles();
if (styles != null) {
XWPFDefaultRunStyle defaultRunStyle = styles.getDefaultRunStyle();
if (defaultRunStyle != null) {
dFontSize = defaultRunStyle.getFontSizeAsDouble();
}
}
if (dFontSize == null) {
dFontSize = 11d;
}
}
System.out.println(dFontSize);
}
}
....
3
A point to remember is that when you are iterating through the runs in a paragraph, you want to handle multiple runs with different properties, such as font size. In your case, you’re only accessing the font size of the last run in each paragraph, which might not always be the one you’re interested in.
Something like this can better solve your issue:
for (XWPFParagraph p : cell.getParagraphs()) {
for(XWPFRun run : p.getRuns()) {
if(run.text().contains("@DATE")) {
double fontSize = run.getFontSizeAsDouble();
System.out.println("Font size of '@DATE' run: " + fontSize);
break;
}
}
}
The above code will iterate through each run in a paragraph and check if the text within the run contains the pattern “@DATE”. If a match is found, it retrieves the font size of that particular run. Using this approach ensures that you’re getting the font size specifically for the “DATE” portion of “@DATE”.
5
I found Solution using ASPOSE API. Since APACHE POI did not return font size for second run, ASPOSE API is power full then APACHE POI which returns any word in 200 pages of word document. Liked it.
Link to Solution : https://releases.aspose.com/words/java/16-8-0/