怎么在光标所在位置插入下一页分节符

原始文档:
section.docx (18.8 KB)

预期:
reset.section.docx (18.9 KB)

怎么移动到第一个run之前插入分节符?

@Crane

请提供更多信息,例如您使用的代码示例或您希望使用的具体方法。

怎么做?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");

这是正常现象吗,还是我应该以某种方式获取到之前的段落,保存起来

@Crane 您能详细说明一下这个问题吗?我看到上面提出的代码产生了预期的输出。如果没有,您能指出问题所在吗?

插入分节符之后原段落的内容变了

@alexey.noskov 怎么说,就是我在当前段落插入分节符之后,段落的内容与原始内容不同,变成了\f

@Crane 这是分节符。所以这是预料之中的。