删除分节符影响书签标记

     Document document = new Document("input.docx");
        for (int i = document.getSections().getCount() - 2; i >= 0; i--) {
            document.getLastSection().prependContent(document.getSections().get(i));
            document.getSections().get(i).remove();
        }
        document.updateFields();
        document.save("res.bookmark.docx");

input.docx (601.7 KB)

如何保持书签不变呢

@Crane

要在删除分节符的同时保持书签不变,您可以在合并节之前先保存书签的位置,然后在合并后重新创建这些书签。以下是一个示例代码,展示了如何实现这一点:

Document document = new Document("input.docx");

// 保存书签信息
List<Bookmark> bookmarks = new ArrayList<>();
for (Bookmark bookmark : document.getRange().getBookmarks()) {
    bookmarks.add(bookmark);
}

// 合并节
for (int i = document.getSections().getCount() - 2; i >= 0; i--) {
    document.getLastSection().prependContent(document.getSections().get(i));
    document.getSections().get(i).remove();
}

// 重新创建书签
for (Bookmark bookmark : bookmarks) {
    // 在合适的位置重新创建书签
    document.getRange().getBookmarks().add(bookmark.getName(), bookmark.getBookmarkStart().getParentNode());
}

document.updateFields();
document.save("res.bookmark.docx");

在这个示例中,我们首先遍历文档中的所有书签并将它们保存到一个列表中。然后,在合并节的过程中,我们删除了不需要的节。最后,我们在合并后的文档中重新创建这些书签,确保它们的位置保持不变。

请根据您的具体需求调整代码,确保书签的位置和内容符合预期。

 for (int i = document.getSections().getCount() - 2; i >= 0; i--) {
            Section sourceSection = document.getSections().get(i).deepClone();
            document.getSections().get(i).remove();
            document.getLastSection().prependContent(sourceSection);
  }

这样没问题,先克隆再删除

@Crane 请尝试使用以下代码:

Document doc = new Document("C:\\Temp\\in.docx");

for (int i = doc.getSections().getCount() - 2; i >= 0; i--)
{
    Section src = doc.getSections().get(i);
    while (src.getBody().hasChildNodes())
        doc.getLastSection().getBody().prependChild(src.getBody().getLastChild());
    src.remove();
}
doc.updateFields();

doc.save("C:\\temp\\out.docx");

我这种方式会出现什么问题吗,因为我还需要加判断,如果是横向的纸张保持原位置,不合并

@Crane 页面方向和其他页面设置都是在 MS Word 文档中按节设置的。因此,为了保持页面方向,需要单独创建一个节。需要在代码中添加相应的条件。