In this tutorial, I will show you how to read content from a PDF file in Laravel 12 using the Spatie PDF-to-Text package. The Spatie PDF-to-Text package makes it easy to extract text from any PDF file without writing complex code. This is very useful when you want to:
So, let's get started.
If you haven't installed Laravel 12 yet, you can install it using the following command:
laravel new laravel12-pdf-read
Now install the Spatie PDF-to-Text package using composer:
composer require spatie/pdf-to-text
Now, let's create a controller, route, and form to upload a PDF file.
Run the following command:
php artisan make:controller PDFController
app/Http/Controllers/PDFController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Spatie\PdfToText\Pdf;
class PDFController extends Controller
{
public function index()
{
return view('pdf.upload');
}
public function readPDF(Request $request)
{
// Validate the file
$request->validate([
'pdf_file' => 'required|mimes:pdf|max:2048',
]);
// Upload the file
if ($request->file('pdf_file')) {
$file = $request->file('pdf_file');
$filePath = $file->store('pdfs');
// Read the PDF file content
$text = Pdf::getText(storage_path('app/' . $filePath));
// Display the extracted text content
return view('pdf.result', compact('text'));
}
return redirect()->back()->with('error', 'Something went wrong.');
}
}
All uploaded PDF files will be stored in
storage/app/pdfs
Open your web.php file.
use App\Http\Controllers\PDFController;
Route::get('/upload-pdf', [PDFController::class, 'index'])->name('upload.pdf');
Route::post('/read-pdf', [PDFController::class, 'readPDF'])->name('read.pdf');
Now create a Blade file where users can upload a PDF file:
resources/views/pdf/upload.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Read PDF File in Laravel 12</title>
</head>
<body>
<h2>Upload PDF File</h2>
<form action="{{ route('read.pdf') }}" method="POST" enctype="multipart/form-data">
@csrf
<div>
<label>Select PDF File:</label>
<input type="file" name="pdf_file" required>
</div>
<br>
<button type="submit">Read PDF</button>
</form>
</body>
</html>
Now create another Blade file to display the PDF text content.
resources/views/pdf/result.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Extracted PDF Text Content</title>
</head>
<body>
<h2>Extracted Text Content from PDF</h2>
<pre>{{ $text }}</pre>
<a href="{{ route('upload.pdf') }}">Upload Another PDF</a>
</body>
</html>
Now start your Laravel server:
php artisan serve
The Spatie PDF-to-Text package internally uses the poppler-utils library to extract text from PDF files. Without it, the package will not work and you may get an error like:
PdfToText\PdfCouldNotBeExtracted: PDF could not be extracted.
For Ubuntu / Debian / Linux:
sudo apt-get update
sudo apt-get install poppler-utils
For CentOS / RedHat / Fedora
sudo yum install poppler-utils
For Mac OS
brew install poppler
Verify Installation
pdftotext -v
OR
which pdftotext
You might also like: