0

I have a process that will create multiple PDFs (e.g 1000 PDF), save it in a folder, ZIP the files and delete the folder. My problem here is if the user closes the browser without waiting for the process to complete or any of the processes failed for some reason, the generation of PDF files are still ongoing in the server. How can I stop this process from continuing?

  1. PDF generation:
use Barryvdh\DomPDF\Facade as PDF;

$landscape = (if format is landscape == 'landscape' else 'portrait');
foreach ($data as $datum)
{
   $pdf = PDF::loadView('pdf.index', compact('datum'))->setPaper('a4', $landscape);
   $file = public_path('storage/pdf/'.$datum->name.'.pdf';
   $pdf->save($file);
}
  1. Zip the files and delete the folder:
use ZipArchive;

$zip_file = public_path('storage/zipped.zip');
$zip = new ZipArchive();
$zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);

$path = public_path('storage/pdf');
$files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));
foreach ($files as $name => $file)
{
     // We're skipping all subfolders
     if (!$file->isDir()) {
          $filePath     = $file->getRealPath();

          // extracting filename with substr/strlen
          $relativePath = 'pdf/' . substr($filePath, strlen($path) + 1);

          $zip->addFile($filePath, $relativePath);
     }
}
$zip->close();
Storage::disk('public')->deleteDirectory('pdf');
return response()->download($zip_file);

I am using an AJAX call to run the PDF generation and the zip process, but if the PDF generation is called and along the way there was an error out of nowhere, the process does not stop and the files will continue on generated until all of the data are done.

  • Hi thank you for answering, so basically, when the generate.php is running, for example 500 PDF files have already been generated and the user closes the browser. The other 500 PDF will still run right? How can I make it so that when the user closes the browser when the script is running, stop all process/kill the current process (generate.php) and remove the files in the folder... – nazhannasir Dec 09 '20 at 07:30
  • 1
    If the browser sent the request to the server, the process will continue till it finishes, you need to create a function to check if the user still online inside the creating pdf files loop – Burhan Kashour Dec 09 '20 at 07:35

0 Answers0