How To Read Content From A PDF File In Laravel 10

How To Read Content From A PDF File In Laravel 10

Here are the steps on how to read content from a PDF file in Laravel 10:

  1. 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
  1. Install the required dependencies. The spatie/pdf-to-text package requires the poppler-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
  1. Create a route to your controller. In your routes/web.php file, add the following route:
Route::get('/pdf/read', 'PDFController@read');
  1. Create a controller to read the PDF file. Create a new file called PDFController.php in your app/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();
    }
}
  1. 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 the Controller class.
  • The read() method takes a Request 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.

Read more post here

Leave a Reply