First Commit
This commit is contained in:
Executable
+64
@@ -0,0 +1,64 @@
|
||||
<?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(),
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user