I've used the code above that solves the problem using regex and it works, but it's quite slow. It reads the entire file to determine the number of pages.
I used it in a web app and pages would sometimes list 20 or 30 PDFs at a time and in that circumstance the load time for the page went from a couple seconds to almost a minute due to the page counting method.
I don't know if the 3rd party libraries are much better, I would hope that they are and I've used pdflib in other scenarios with success.