使用docx4j创建Word文档节时出现多余空白页的解决咨询
解决docx4j创建Word文档时末尾出现额外空节和空白页的问题
问题原因
你在每个节的结束位置都添加了nextPage类型的分节符,包括最后一个节。nextPage分节符会强制新建一页并开启新节,最后一个节之后加这个分节符,自然会生成无内容的空节和空白页。
解决方法
1. 仅在非最后一节末尾添加分节符
创建节时,只在前N-1个节的末尾添加nextPage分节符,最后一个节不需要额外添加分节符,直接把节属性设置到文档的body节点上即可。
调整后的代码示例
先封装一个添加分节符的工具方法:
private void addNextPageSectionBreak(WordprocessingMLPackage wordMLPackage, STPageOrientation orientation) { ObjectFactory factory = Context.getWmlObjectFactory(); P sectionParagraph = factory.createP(); wordMLPackage.getMainDocumentPart().getJaxbElement().getBody().getContent().add(sectionParagraph); SectPr sectPr = factory.createSectPr(); SectPr.Type sectPrType = factory.createSectPrType(); sectPrType.setVal("nextPage"); sectPr.setType(sectPrType); SectPr.PgSz pageSz = factory.createSectPrPgSz(); pageSz.setOrient(orientation); sectPr.setPgSz(pageSz); sectionParagraph.setPPr(factory.createPPr()); sectionParagraph.getPPr().setSectPr(sectPr); }
然后按节创建内容:
// 第1节:添加内容、页眉等操作 // ... 你的第1节内容代码 ... // 添加分节符(后面还有节,所以需要) addNextPageSectionBreak(wordMLPackage, STPageOrientation.LANDSCAPE); // 第2节:添加内容、页眉等操作 // ... 你的第2节内容代码 ... // 这是最后一节,直接设置body的节属性,不再加分节符 ObjectFactory factory = Context.getWmlObjectFactory(); SectPr finalSectPr = factory.createSectPr(); SectPr.PgSz finalPageSz = factory.createSectPrPgSz(); finalPageSz.setOrient(STPageOrientation.PORTRAIT); finalSectPr.setPgSz(finalPageSz); wordMLPackage.getMainDocumentPart().getJaxbElement().getBody().setSectPr(finalSectPr);
2. 移除已生成的末尾空节
如果已经不小心生成了带空节的文档,可以检查文档body的最后一个元素,若为带节属性的空段落,直接移除并将节属性转移到body上:
Body body = wordMLPackage.getMainDocumentPart().getJaxbElement().getBody(); List<Object> content = body.getContent(); if (!content.isEmpty()) { Object lastElement = content.get(content.size() - 1); if (lastElement instanceof P) { P lastPara = (P) lastElement; // 判断是否是带sectPr的空段落 if (lastPara.getContent().isEmpty() && lastPara.getPPr() != null && lastPara.getPPr().getSectPr() != null) { content.remove(lastElement); // 将原空段落的节属性设置到body body.setSectPr(lastPara.getPPr().getSectPr()); } } }
内容的提问来源于stack exchange,提问作者Gopika Ravikumar
相关产品推荐
相关产品推荐

