How to insert two TOC fields in the document using Java

Hi There,

We’re merging two different words documents, each document has its own TOC.
However after merging those two documents can we update the page number of the second TOC?

We’re using below code to generate TOC.

com.aspose.words.Document doc = new com.aspose.words.Document(filePath);
DocumentBuilder builder = new DocumentBuilder(doc);
builder.insertTableOfContents("\\o \"1-3\" \\h \\z \\u");
doc.updateFields();
doc.save(filePath);

Awaiting for your response.

Cheers,
Naveed Khan

@naveekhan

You can update the TOC fields using Document.updateFields method. If your both documents contains the TOC field, we suggest you please remove them from documents and insert TOC field in your final document using DocumentBuilder.insertTableOfContents method.

If you still face problem, please attach the following resources here for testing:

  • Your input Word documents.
  • Please attach the output Word file that shows the undesired behavior.
  • Please attach the expected output Word file that shows the desired behavior.
  • Please create a simple Java application ( source code without compilation errors ) that helps us to reproduce your problem on our end and attach it here for testing.

As soon as you get these pieces of information ready, we will start investigation into your issue and provide you more information. Thanks for your cooperation.

PS: To attach these resources, please zip and upload them.

Hey Tahir,

Thanks for quick response.
The requirement is, we wanted to keep TOC of both the document separately after merging.

we’re merging documents using below Aspose code.

  dstDoc.appendDocument(srcDoc, ImportFormatMode.KEEP_SOURCE_FORMATTING);

we have below queries ?

  1. Please let us know if Aspose can create multiple TOCs in a single document?
  2. Also please let us know, Is there any way we can merge two documents and keep their TOC’s after merge & update the page number of second TOC?

Cheers,
Naveed Khan

@naveekhan

Please note that Aspose.Words mimics the behavior of MS Word.

Yes, you can create multiple TOC fields in a single document.

In this case, we suggest you following solution.

  1. Import your first document into Aspose.Words’ DOM.
  2. Bookmark all of its content by moving the cursor to the start and end of document and insert BookmarkStart and BookmarkEnd nodes.
  3. Do the same for second document.
  4. Insert the table of content at the start of both documents with bookmark switch e.g. { TOC \b bookmarkname }.
  5. Join the documents and update the field.

We suggest you please read the following articles.
Using Multiple Tables of Contents
Using DocumentBuilder to Modify a Document
Use DocumentBuilder to Insert Document Elements