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?
- 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);
}
- 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.