Prevent NullPointerException in XWPFTable.getWidthType(). (#912)

According to the spec in section "17.4.63 tblW (Preferred Table Width)",
the element tblW is not compulsory and "If this element is omitted, then
the cell width shall be of type auto."

We modify the getter to follow this behavior, preventing a NPE.

It implies a change of behavior in the situation when there is no tblPr,
in that case it used to return NIL, but notice that this behavior was
introduced in commit d4fc5cd6c08338a4132a6348ee1b1b077f9527b8 and has
never been part of a release.
This commit is contained in:
Jacobo Aragunde Pérez 2025-10-01 15:17:00 +02:00 committed by GitHub
parent 05f37a5204
commit 79d1630374
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 13 additions and 2 deletions

View File

@ -1250,12 +1250,13 @@ public class XWPFTable implements IBodyElement, ISDTContents {
* A table width can be specified as an absolute measurement (an integer
* number of twips), a percentage, or the value "AUTO".
*
* @return The width type. Returns {@link TableWidthType#NIL} as a default.
* @return The width type. If table width information does not exist in the document,
* it returns {@link TableWidthType#AUTO}.
* @since 4.0.0
*/
public TableWidthType getWidthType() {
CTTblPr pr = getTblPr(false);
return pr == null ? TableWidthType.NIL : getWidthType(pr.getTblW());
return pr != null && getTblPr().isSetTblW() ? getWidthType(pr.getTblW()) : TableWidthType.AUTO;
}
/**

View File

@ -652,4 +652,14 @@ class TestXWPFTable {
assertEquals(0, tbl.getIndent());
}
}
@Test
public void testGetTableWidthIfNotPresent() throws Exception {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("table-indent.docx")) {
// The first table in this document doesn't have a tblW item.
XWPFTable table1 = doc.getTableArray(0);
assertEquals(-1,table1.getWidth());
assertEquals(TableWidthType.AUTO, table1.getWidthType());
}
}
}