HTML to PDF conversion: With DomPDF, you can convert HTML content, including CSS styles and images, into PDF format. This allows you to leverage your existing HTML templates and views to generate professional-looking PDF documents.
Step 1: Install Laravel App
composer create-project laravel/laravel example-GeneratePdf
Step 2: Install DomPDF Package
composer require barryvdh/laravel-dompdf
Step 3: Create Controller
php artisan make:controller PDFController
Add
dummy data
php artisan tinker
User::factory()->count(10)->create()
app/Http/Controllers/PDFController.php
<?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' => 'Welcome to ItSolutionStuff.com',
'date' => date('m/d/Y'),
'users' => $users
];
$pdf = PDF::loadView('myPDF', $data);
return $pdf->download('itsolutionstuff.pdf');
}
}
Step 4: Add Route
<?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, 'generatePDF']);
Step 5: Create View File
resources/views/myPDF.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 10 Generate PDF Example - webthestuff.com</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<h1>{{ $title }}</h1>
<p>{{ $date }}</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua.</p>
<table class="table table-bordered">
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
@foreach($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
</tr>
@endforeach
</table>
</body>
</html>
Run Laravel App:
php artisan serve
Now, Go to web browser, type the given URL and see the output:
http://localhost:8000/generate-pdf