How to Read Content from PDF File in Laravel?

 

To read content from a PDF file in Laravel, you can utilize a library called "spatie/pdf-to-text". This library allows you to extract text from PDF files. Here's how you can install and use it:


1. Install the Package:

You can install the "spatie/pdf-to-text" package using Composer. Open your terminal and navigate to your Laravel project directory, then run the following command:


composer require spatie/pdf-to-text


2. Usage in Your Controller or Service:

After installing the package, you can use it in your controller or service. For example, let's assume you have a controller named "PdfController". In this controller, you can use the following code to read the content from a PDF file:


<?php


namespace App\Http\Controllers;


use Illuminate\Http\Request;

use Spatie\PdfToText\Pdf;


class PdfController extends Controller

{

    public function readPdfContent(Request $request)

    {

        // Get the uploaded PDF file from the request

        $pdfFile = $request->file('pdf');


        // Check if a file was uploaded

        if ($pdfFile) {

            // Get the path of the uploaded file

            $pdfPath = $pdfFile->path();


            // Read the content from the PDF file

            $pdfText = Pdf::getText($pdfPath);


            // Return the PDF content or process it as needed

            return response()->json(['content' => $pdfText]);

        }


        // Return an error response if no PDF file was uploaded

        return response()->json(['error' => 'No PDF file uploaded'], 400);

    }

}


3. Create a Route:

Don't forget to create a route that maps to the "readPdfContent" method in your controller. Open your "routes/web.php" file and add the following route definition:


Route::post('/read-pdf', 'PdfController@readPdfContent');


4. Create a Form in Your View:

Finally, create a form in your view that allows users to upload a PDF file. For example:


<form action="{{ route('read-pdf') }}" method="POST" enctype="multipart/form-data">

    @csrf

    <input type="file" name="pdf">

    <button type="submit">Read PDF</button>

</form>


When a user submits the form, the "readPdfContent" method in your controller will be invoked. The PDF content will be extracted and returned as a JSON response. You can adapt this example to fit your specific requirements and integrate it into your Laravel application.