请问怎么将一个分页符和文本从一个段落中分开

源文档:
aa.docx (39.8 KB)

这个源文档中有一个段落是:page break 1 引言
请问怎么处理可以将 page break 和 1 引言 分开为两个段落
我的处理:这样的处理会导致新增一个空标题
DocumentBuilder builder = new DocumentBuilder(document);
RunCollection runs = para.getRuns();
Arrays.stream(runs.toArray()).filter(run → run.getText().contains(ControlChar.PAGE_BREAK)).forEach(run → {
builder.moveTo(run);
builder.insertBreak(BreakType.PARAGRAPH_BREAK);
});

@ouchli 由于分页符是段落 ParagraphFormat.PageBreakBefore 或特殊字符 ControlChar.PageBreak 的格式属性,因此它不能出现在单独的段落中。 要模仿 MS Word 的行为,应使用以下代码来实现结果:

Arrays.stream(runs.toArray()).filter(run -> run.getText().contains(ControlChar.PAGE_BREAK)).forEach(run -> {
    Node nextRun = run.getNextSibling();
    while (nextRun.getNodeType() != NodeType.RUN) {
        nextRun = nextRun.getNextSibling();
    }

    nextRun.getParentNode().insertBefore(new Run(doc, ControlChar.PAGE_BREAK), nextRun);
});

你好,请问我如何为一个文档的第一页之前插入一个空白页,并在这个空白页中添加一个段落

@ouchli 您可以创建一个部分,并将其添加为首页:

Document doc = new Document("input.docx");
      
Section newFirstSection = new Section(doc);
newFirstSection.ensureMinimum();

doc.insertBefore(newFirstSection, doc.getFirstSection());
newFirstSection.getBody().appendParagraph("This is the new first page content");

doc.save("output.docx");

但我认为最简单的方法是创建一个包含段落的文档,然后附加另一个文档。

那如果要创建文档并附件的话,该如何做呢

@ouchli 代码如下:

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder();

builder.writeln("Simple paragraph");

Document newDoc = new Document("input.docx");
doc.appendDocument(newDoc, ImportFormatMode.KEEP_SOURCE_FORMATTING);

doc.save("output.docx");