It's not really complicated. You can only fetch the total number of pages by going to the last page. That's what the script on the help page does.
The example does not work, because the variable $pp is not global. It should be $$pp.
Make sure the script always runs just before printing.
I don't know where you went for the help section, but regardless, here's what I've done for years. (following is script pseudo code):
- Find the records you want to print and sort if needed
- Enter preview mode
- Go to last page
- Get page number and store in variable (or global field - what ever is used on the footer of your layout)
- Enter browse mode
- print the report.
I don't know if there are newer ways to do this. Good luck.