PetOffice

How to create temporary file for download and then delete

DrupalPHP

I based this post on this answer on Stackoverflow

my_module.routing.yml

my_module.pdf_link:
  path: '/my-module/pdf/download'
  defaults:
    _title: 'PDF download'
    _controller: '\Drupal\my_module\Controller\MyModuleController::downloadPDF'
  requirements:
    _role: 'authenticated'

MyModuleController

public function downloadPDF() {
  try {
    $pdf_stream = $this->restCallThatReturnAPdfStream();

    if (empty($pdf_stream)) {
      throw new \Exception('PDF stream is empty');
    }

    $headers = [
      'Content-Type' => 'application/pdf',
      'Content-Disposition' => 'attachment;filename="download.pdf"'
    ];

    $temporary_pdf_file = $this->fileSystem->saveData($pdf_stream, 'temporary://mytempfile.pdf', FileSystemInterface::EXISTS_REPLACE); 

    if (!$temporary_pdf_file) {
      throw new \Exception('Failed to save the temporary PDF file');
    }

    $response = new BinaryFileResponse($temporary_pdf_file, 200, $headers, TRUE);
    return $response->deleteFileAfterSend(TRUE);
    
  } catch (\Exception $e) {
    // Log the error or handle it as needed
    \Drupal::logger('pdf_download')->error($e->getMessage());
    return new Response('Error generating PDF', 500);
  }
}