Not the best way to download something, you're using a framework so that will do the output processing for you, which interferes with your handcoded statements.
Use File::download() instead. It requires a temp file you have to create (it has no support for inline data at the moment), but you can tell the method to delete it once it has been downloaded.
This will makes sure the framework does a proper shutdown and cleanup before sending the file.