Crane
1
document.updateListLabels();
document.updateFields();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
document.save(stream, SaveFormat.DOCX);
Document docReloaded = new Document(new ByteArrayInputStream(stream.toByteArray()));
docReloaded.updateFields();
当我第一次执行时toc并没有更新到对应的样式,然后我从内存流中重新加载再更新,就生效了,这是为什么呢 
@Crane
在使用 document.updateFields()
方法时,您可能会遇到首次调用时目录(TOC)未更新的问题。这是因为在 Aspose.Words 中,文档的字段在打开、修改和保存时不会自动更新。为了确保在保存文档时字段的值是最新的,通常需要在保存之前调用 updateFields()
方法。
在您的代码中,您首先调用了 document.updateListLabels()
和 document.updateFields()
,然后将文档保存到内存流中。接着,您从内存流中重新加载文档并再次调用 updateFields()
。第一次调用时,TOC 可能没有更新到正确的样式,而在重新加载后,调用 updateFields()
则能成功更新。这是因为在第一次调用时,文档的页面布局和字段可能尚未完全计算和更新,而重新加载文档后,所有的布局和字段信息都被重新计算,从而使得 TOC 能够正确显示。
为了确保 TOC 正确更新,您可以按照以下步骤操作:
- 在修改文档后调用
updateFields()
。
- 如果需要更新页面布局,调用
updatePageLayout()
。
- 最后保存文档。
以下是一个示例代码,展示了如何正确更新 TOC:
Document document = new Document("input.docx");
document.updateListLabels();
document.updateFields(); // 更新字段
ByteArrayOutputStream stream = new ByteArrayOutputStream();
document.save(stream, SaveFormat.DOCX); // 保存到内存流
Document docReloaded = new Document(new ByteArrayInputStream(stream.toByteArray()));
docReloaded.updateFields(); // 重新加载后更新字段
docReloaded.save("output.docx");
通过这种方式,您可以确保 TOC 在文档保存时是最新的。希望这能帮助您解决问题!
Crane
3
我在之前调用了document.updatePageLayout()也不会生效