From 79d16303746cbc3cf3081af2a965cff14e2ceb09 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jacobo=20Aragunde=20P=C3=A9rez?= Date: Wed, 1 Oct 2025 15:17:00 +0200 Subject: [PATCH] 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. --- .../java/org/apache/poi/xwpf/usermodel/XWPFTable.java | 5 +++-- .../org/apache/poi/xwpf/usermodel/TestXWPFTable.java | 10 ++++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/poi-ooxml/src/main/java/org/apache/poi/xwpf/usermodel/XWPFTable.java b/poi-ooxml/src/main/java/org/apache/poi/xwpf/usermodel/XWPFTable.java index c9fe1cdd1e..33fc2a8d63 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xwpf/usermodel/XWPFTable.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xwpf/usermodel/XWPFTable.java @@ -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; } /** diff --git a/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFTable.java b/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFTable.java index 3bd3205036..8fe1f303c9 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFTable.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFTable.java @@ -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()); + } + } }