Nice idea! Here's a basic function that achieves your goal using a different technique:
function! FitOnPage()
normal! zR
while &foldlevel > 0
if line('w0') == 1 && line('w$') == line('$')
break
endif
normal! zm
endwhile
endfunction
It works by first expanding all the folds. It then closes folds (globally) until the entire document is on screen or all the folds are closed.
It checks if the whole documentfile is on screen simply by moving to the bottom ofchecking if the screenfirst and then seeing if it's atlast lines displayed are the endfirst and last lines of the file.
You could improve this a bit by closing folds individually, but that would be a lot more complicated.