Hello Artisan,
In this laravel 9 pdf file from view tutorial, I am going to show you how to generate and save pdf in Laravel 9 using dom pdf. So from this tutorial, you will learn to generate pdf from view and the way to download it.
Sometimes in web applications, we need to generate and save pdf. In Laravel, we can do it with many pdf manager packages. In this how to generate pdf in laravel 9 tutorial, I will use dom pdf to generate and save pdf files from blade view in Laravel 9 application.
So let's start Laravel 9 PDF and Laravel 9 generate PDF file using DomPDF example from step by step:
Step 1: Install Laravel 9
This is the first step to download a fresh Laravel 9 application to start it from scratch. So run the below command:
composer create-project laravel/laravel example-app
Step 2: Install DomPDF Package
Now the second step, we will install the DomPDF
package using the following composer command, let's run bellow command:
composer require barryvdh/laravel-dompdf
Read also: Merging Multiple PDF File in Single File Example in Laravel
Step 3: Create Controller
In this step, we will create a controller with generate_and_save_pdf()
where we write code of generating pdf. so let's create a controller using the bellow command.
app/Http/Controllers/PDFController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use PDF;
class PDFController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function generatePDF()
{
$users = User::get();
$data = [
'title' => 'Your title',
'date' => date('m/d/Y'),
'users' => $users
];
$pdf = PDF::loadView('myPDF', $data);
return $pdf->download('test.pdf');
}
}
Step 4: Create Route
Now, open routes/web.php
file and update code on it.
routes/web.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::get('generate-pdf', [PDFController::class, 'generate_and_save_pdf']);
Step 5: Create View File
In the last step, let's create myPDF.blade.php to generate the pdf page and we will download this pdf from this page:
resources/views/myPDF.blade.php
Hope this laravel 9 create pdf from view tutorial will help you.
#laravel #laravel-9x