How can we add the box around the main block depending on the text on particular page?

I need to add box around the main block dynamically depending on the text on a particular page.

Somehow I am able to generate the box on the last page dynamically based on the last element of the document but for the regular pages, I am not getting the end point to draw the box.

Can anyone help me to draw the box depending on the depth of the text block on the regular/normal pages.

Thanks!

Shahnawaz

emoji