原始文档:
section.docx (18.8 KB)
预期:
reset.section.docx (18.9 KB)
怎么移动到第一个run
之前插入分节符?
怎么做?documentBuilder.moveTo(paragraph);这个只能移动到段落之后,我如果移动到前一个段落之后插入的话,会多出一行
@Crane 您可以使用以下代码来实现这一点:
Document doc = new Document("C:\\Temp\\in.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
// Put empty run at the beginning of the second paragraph.
Run r = new Run(doc);
doc.getFirstSection().getBody().getParagraphs().get(1).prependChild(r);
// Move to the created run and insert section break.
builder.moveTo(r);
builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
doc.save("C:\\temp\\out.docx");
这样操作之后原段落的内容会变化
Document document = new Document("section.docx");
NodeCollection<?> childNodes = document.getChildNodes(NodeType.PARAGRAPH, true);
Node[] array = childNodes.toArray();
Paragraph originalParagraph = null;
String oldText = "";
for (Node childNode : array) {
Paragraph paragraph = ((Paragraph) childNode);
if (paragraph.getText().contains("22")) {
originalParagraph = paragraph;
oldText = originalParagraph.getText();
Run run = new Run(document);
paragraph.prependChild(run);
DocumentBuilder db = new DocumentBuilder(document);
db.moveTo(run);
db.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
}
}
Assertions.assertEquals(originalParagraph.getText(), oldText);
document.save("Res.section.docx");
这是正常现象吗,还是我应该以某种方式获取到之前的段落,保存起来
插入分节符之后原段落的内容变了