Skip to main content

[Laravel] Hướng dẫn lấy nội dung file PDF

Hướng dẫn này sẽ giúp đọc nội dung từ tệp PDF trong laravel thông qua một package spatie/pdf-to-text

Bước 1- Khởi tạo dự án Laravel kèm package spatie/pdf-to-text

Sử dụng lần lượt các lệnh

composer create-project laravel/laravel example-app
composer require spatie/pdf-to-text

Ở đây, chúng tôi đã sử dụng gói spatie/pdf-to-text để đọc tệp pdf. gói này cần phần mềm pdftotext. Vì vậy bạn cần cài đặt vào hệ thống hoặc máy chủ của mình bằng các lệnh sau. vì vậy, hãy chạy lệnh sau:

# Ubuntu
sudo apt-get install poppler-utils
# Mac
brew install poppler
# CentOS / RedHat
yum install poppler-utils

Bước 2 - Tạo Route trong Laravel

 Mở file routes/web.php

<?php
 
use Illuminate\Support\Facades\Route;
 
use App\Http\Controllers\PDFController;
 
/* 
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
 
Route::controller(PDFController::class)->group(function(){
   Route::get('read-pdf-file', 'index');
});

Bước 3 : Tạo Controller để xử lý file pdf

Trong bước này, chúng tôi sẽ tạo một PDFController sẽ thêm phương thức index() để đọc tệp pdf.

app/Http/Controllers/PDFController.php

<?php
     
namespace App\Http\Controllers;
      
use Illuminate\Http\Request;
use Spatie\PdfToText\Pdf;
   
class PDFController extends Controller
{
      
   /**
    * Show the application dashboard.
    *
    * @return \Illuminate\Http\Response
    */
   public function index()
   {
       $text = Pdf::getText(public_path('sample-demo.pdf'));
 
       dd($text);
   }
    
}   

Đặt file pdf sample-demo.pdf trong cùng thư mục public

Bước 4: Test tính năng lấy nội dung file PDF bằng Laravel

Dùng lệnh

php artisan serve

Sau đó mở route đã khai báo ở trên để text

http://localhost:8000/read-pdf-file

Bạn sẽ nhận kết quả

Discover Keyword Ideas
This is demo file
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit
in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum.

Download file PDF demo

Document
sample-demo.pdf
(30.58 KB)

Nguồn :  itsolutionstuff.com