I am working on a Java 8 project where I need to modify a Word document template (.docx) using Apache POI v4.1.2. The template contains multiple sections with tables, paragraphs, and images. My task is to delete certain sections based on specific criteria and then update the content with new details to generate a final report.
I have successfully implemented the section deletion functionality. However, after deleting sections, the page numbers in the template change, and these changes are not reflected in the Table of Contents (TOC). I need assistance in programmatically updating the page numbers in the TOC with complete automation.
I have already tried xwpfDocument.enforceUpdateFields()
, but it resulted in a popup on the document open, which is unacceptable to the stakeholders. Therefore, I'm looking for a programmatic solution to either update the stale TOC page numbers with the new ones Without any popup or create a new TOC or TOC Like structure with Section and Subsection headings with the page numbers.
Additionally, I have a constraint on using Apache POI. Changing the library at this point may not be a feasible solution as most of the logic is already written and working as expected. Also, I can not use Macro based approach due to security concerns.
Could anyone guide how to achieve this automated update or addition of TOC page numbers using Java and Apache POI? Any code snippets, suggestions, or any alternative approaches/hacks would be greatly appreciated.
Thank you in advance for your help!