Hello, web developers! In this article, we'll see how to add an image to a pdf file in laravel 10. Here, we'll create a PDF file with the image in laravel 10. Whether you're creating invoices, reports, or any other document, this step-by-step guide will empower you to seamlessly integrate images into your PDFs.
In this article, we'll how to add an image to a PDF file in laravel 10. Also, we are using barryvdh/laravel-dompdf package to generate PDF files in laravel 10.
Ensure you have Laravel 10 installed on your machine. If not, you can create a new project with:
composer create-project laravel/laravel mypdfproject
cd mypdfproject
We'll need the barryvdh/laravel-dompdf package for handling PDFs. Install it using Composer:
composer require barryvdh/laravel-dompdf
Add the service provider and facade to your config/app.php
:
'providers' => [
// ...
Barryvdh\DomPDF\ServiceProvider::class,
],
'aliases' => [
// ...
'PDF' => Barryvdh\DomPDF\Facade::class,
],
Create a new controller for handling PDF generation:
php artisan make:controller PDFController
In your PDFController.php
file, use the following code to add an image to the PDF:
use PDF;
use Illuminate\Http\Request;
class PDFController extends Controller
{
public function generatePDF()
{
$data = [
'imagePath' => public_path('images/test.jpg'),
'title' => "Add images to PDF files in Laravel 10 - Vidvatek"
// Add other data as needed
];
$pdf = PDF::loadView('pdf.document', $data);
return $pdf->stream('document.pdf');
}
}
Create a new Blade view file, document.blade.php
, in the resources/views/pdf/
directory. Use the following code to embed the image in the PDF:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Laravel 10 Add Image to PDF File Example - Vidvatek</title>
</head>
<body>
<h2>{{ $title }}</h2>
<img src="{{ $imagePath }}" alt="Image">
<br><br/>
<strong>Public Folder:</strong>
<img src="{{ public_path('laravel_10.jpg') }}" style="width: 100%;">
<br/>
<strong>Storage Folder:</strong>
<img src="{{ storage_path('app/public/laravel.png') }}" style="width: 100%;">
</body>
</html>
In your web.php
file, define a route to trigger the PDF generation:
use App\Http\Controllers\PDFController;
Route::get('/generate-pdf', [PDFController::class, 'generatePDF']);
Run your Laravel application:
php artisan serve
You might also like:
- Read Also: How to Send Email with PDF Attachment in Laravel 10
- Read Also: Convert HTML to PDF in Python: Step-by-Step Guide
- Read Also: Select2 Autocomplete Search Using Ajax in Laravel 10
- Read Also: How to Send Bulk Mail using Queue in Laravel 10