@847834757 MS Word 文档本质上是流动的,因此它们没有任何有关文档布局的信息,也没有“页面”概念。 消费者应用程序(例如 MS Word 或 OpenOffice)将文档内容动态重排到页面中。
正如我从屏幕截图中看到的,空页面是由表格后面的空段落生成的。 在 MS Word 文档中,表格不能是文档的最后一个节点,因此会添加一个空段落,在您的情况下,该段落会移动到新页面。 该段落无法删除,但您可以尝试减小其字体大小。
Document doc = new Document("C:\\Temp\\in.docx");
// Remove empty paragraph from the end of the document.
while (doc.getLastSection().getBody().getLastChild().getNodeType() == NodeType.PARAGRAPH &&
doc.getLastSection().getBody().getLastParagraph().toString(SaveFormat.TEXT).trim().equals("") &&
doc.getLastSection().getBody().getLastParagraph().getChildNodes(NodeType.SHAPE, true).getCount() == 0)
{
if (doc.getLastSection().getBody().getLastParagraph().getPreviousSibling().getNodeType() == NodeType.TABLE)
{
doc.getLastSection().getBody().getLastParagraph().getParagraphBreakFont().setSize(0);
break;
}
else
{
doc.getLastSection().getBody().getLastParagraph().remove();
}
}
doc.save("C:\\Temp\\out.docx");
@847834757 提供的代码有错误。 我已经更正了,漏掉了一个else
:
if (doc.getLastSection().getBody().getLastParagraph().getPreviousSibling().getNodeType() == NodeType.TABLE)
{
doc.getLastSection().getBody().getLastParagraph().getParagraphBreakFont().setSize(0);
break;
}
else
{
doc.getLastSection().getBody().getLastParagraph().remove();
}
但由于MS Word文档格式的特殊性,这种方法仍然不能给出100的保证。