Here are the steps on how to read content from a PDF file in Laravel 10:
- Install the
spatie/pdf-to-text
package. This package provides a simple way to extract text from PDF files. You can install it using the following command:
composer require spatie/pdf-to-text
- Install the required dependencies. The
spatie/pdf-to-text
package requires thepoppler-utils
library. You can install this library on your system using the following commands:
apt-get install poppler-utils
brew install poppler
yum install poppler-utils
- Create a route to your controller. In your
routes/web.php
file, add the following route:
Route::get('/pdf/read', 'PDFController@read');
- Create a controller to read the PDF file. Create a new file called
PDFController.php
in yourapp/Http/Controllers
directory. In this file, add the following code:
PHP
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Spatie\PdfToText\Pdf;
class PDFController extends Controller
{
public function read(Request $request)
{
$pdf = new Pdf($request->file('pdf'));
return $pdf->getText();
}
}
- Test the route. In your terminal, run the following command to test the route:
php artisan serve
Then, open a browser and navigate to the following URL:
http://localhost:8000/pdf/read
This will upload the PDF file and display the text content of the file.
Here is an explanation of the code:
- The
PDFController
class extends theController
class. - The
read()
method takes aRequest
object as its argument. - The
Pdf
class is used to create a new PDF object. - The
getText()
method is used to get the text content of the PDF file.