7 - Download file and generate page
You need to isolate that code out of your form submission handler. When you set the Content-Disposition: attachment header it's going to override the browser behavior of loading a new page. 

Instead, you should have your form handler save the output file &amp; generate a success page containing a download link (in case your user doesn't have JS support) and run a JS setTimeout() function that will trigger a download after X seconds. See this SO post for an example. 

The download link path can be generated with hook_menu(). Its callback function will use your code snippet above. Depending on the content of the download (e.g. sensitive personal data), you may need to protect this path. This can be done in a variety of ways.