how to create file programmatically only login users download it
Create a private file field as you would if they were regular private files.

Hook in to the file download function: https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_file_download/7

Let Drupal handle permissions,  create your file dynamically.