After researching extensively for a solution, most responses suggest that it is not possible. However, I stumbled upon Paged.js which appears to use the CSS code
a::after { content: target-counter(attr(href), page, decimal); }
effectively filling in the correct page numbers for the Table of Contents. This makes me wonder if they have a CSS polyfill within their library to address this issue. It seems unlikely that browsers support target-counter and ::after directly. Hence, I contemplated finding a CSS polyfill to enable target-counter and page-break-after: avoid, as demonstrated by paged.js.
An alternate approach I considered involves using a PDF parser to analyze all data in the PDF file, implementing regex patterns, loops, and other methods to identify page numbers of specific elements. Perhaps the parser's output could be stored in a JSON file accessible from the Table of Contents. Nonetheless, this method seems time-consuming, especially since another merge operation would be required on the PDF (already done once for the front page).
To elaborate further, I am interested in exploring whether either or both of these solutions are feasible. If so, any guidance on A. obtaining a polyfill for the essential CSS tags, or B. structuring and organizing data retrieved from the PDF parser, would be highly appreciated.