Files
dockerank2/app/Services/PdfExtractionService.php
2026-09-01 07:49:48 -03:00

65 lines
1.6 KiB
PHP
Executable File

<?php
declare(strict_types=1);
namespace App\Services;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Smalot\PdfParser\Parser;
/**
* Service for extracting text content from PDF files.
*/
class PdfExtractionService
{
/**
* Extract text from a PDF file.
*
* @param string $filePath The path to the PDF file
* @return array{success: bool, content: string|null, error: string|null}
*/
public function extract(string $filePath): array
{
if (!file_exists($filePath)) {
return [
'success' => false,
'content' => null,
'error' => 'PDF file not found.',
];
}
try {
$parser = new Parser();
$pdf = $parser->parseFile($filePath);
$text = $pdf->getText();
$text = trim($text);
if (empty($text)) {
return [
'success' => false,
'content' => null,
'error' => 'The PDF appears to be empty or contains no extractable text.',
];
}
return [
'success' => true,
'content' => $text,
'error' => null,
];
} catch (\Exception $e) {
Log::error('PDF extraction error: ' . $e->getMessage(), [
'file' => $filePath,
]);
return [
'success' => false,
'content' => null,
'error' => 'Failed to extract text from PDF: ' . $e->getMessage(),
];
}
}
}