public function downloadDocument(): \Symfony\Component\HttpFoundation\BinaryFileResponse { try { // Compile the document first $this->compileDocument(); $recordID = $this->record->id; $storage = Storage::disk(config('filament-latex.storage')); // Verify LaTeX source exists $filePath = $storage->path($recordID . '/main.tex'); if (!$storage->exists($recordID . '/main.tex')) { throw new RuntimeException(sprintf( 'LaTeX file not found at: %s', $filePath )); } // Ensure compiled directory exists $compiledPath = $recordID . '/compiled'; $pdfDir = $storage->path($compiledPath); if (!$storage->exists($compiledPath)) { $storage->makeDirectory($compiledPath); } // Build and execute pdflatex command $command = [ '/usr/bin/pdflatex', '-interaction=nonstopmode', '-output-directory=' . $pdfDir, $filePath, ]; $process = new Process($command); $process->setTimeout(30); // Run the process with output logging $process->mustRun(function ($type, $buffer) { logger()->debug($type . ': ' . $buffer); }); // Define and verify PDF path $pdfPath = $compiledPath . '/main.pdf'; $fullPath = $storage->path($pdfPath); if (!$storage->exists($pdfPath)) { throw new RuntimeException(sprintf( 'PDF file not found at: %s after compilation', $fullPath )); } // Verify file is readable if (!is_readable($fullPath)) { throw new RuntimeException(sprintf( 'PDF file exists but is not readable at: %s', $fullPath )); } // Verify file size $size = $storage->size($pdfPath); if ($size === 0) { throw new RuntimeException('Generated PDF file is empty'); } // Log successful compilation logger()->debug('PDF compilation successful', [ 'path' => $fullPath, 'size' => $size ]); // Create BinaryFileResponse directly to match return type return new \Symfony\Component\HttpFoundation\BinaryFileResponse( $fullPath, 200, [ 'Content-Type' => 'application/pdf', 'Content-Disposition' => \Symfony\Component\HttpFoundation\HeaderUtils::makeDisposition( \Symfony\Component\HttpFoundation\ResponseHeaderBag::DISPOSITION_ATTACHMENT, 'document.pdf' ), 'Content-Length' => $size, ], true, // deleteFileAfter false, // inline true, // ignoreEtag true // autoEtag ); } catch (ProcessFailedException $exception) { logger()->error('PDF compilation failed', [ 'error' => $exception->getMessage(), 'output' => $exception->getProcess()->getOutput(), 'errorOutput' => $exception->getProcess()->getErrorOutput(), 'command' => $exception->getProcess()->getCommandLine(), ]); throw new RuntimeException('PDF compilation failed: ' . $exception->getMessage()); } catch (\Exception $e) { logger()->error('Download failed', [ 'error' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine(), ]); throw new RuntimeException('Failed to download document: ' . $e->getMessage()); } }