Hello, laravel web developers! In this article, we'll see how to add an image in a PDF file in laravel 11. In laravel 11, we'll create a PDF file using the domPDF composer package and add the image to the PDF file.
You can add images to the PDF using the public_path() and storage_path() laravel functions. You can also add it using the base_64() function.
Laravel 11 Create PDF File with Image
In this step, we'll install the laravel 11 application using the following command.
composer create-project --prefer-dist laravel/laravel laravel-11-example
Then, we'll install laravel-dompdf composer package using the following command.
composer require barryvdh/laravel-dompdf
Next, we'll define the routes into the web.php file.
routes/web.php
Route::get('generate-pdf','PDFController@generatePDF');
Then, we'll create a controller and generate the PDF file.
app/Http/Controllers/PDFController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use PDF;
class PDFController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function generatePDF()
{
$data = ['title' => 'Welcome to Techsolutionstuff'];
$pdf = PDF::loadView('test-pdf', $data);
return $pdf->download('test.pdf');
}
}
Now, we'll create a blade file for the PDF file and add the image to the PDF file.
resources/views/test-pdf.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Hi</title>
</head>
<body>
<h1>Welcome to - {{ $title }}</h1>
<p>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.</p>
<br/>
<strong>Public Folder:</strong>
<img src="{{ public_path('test.jpg') }}" style="width: 200px; height: 200px">
<br/>
<strong>Storage Folder:</strong>
<img src="{{ storage_path('app/public/test.jpg') }}" style="width: 200px; height: 200px">
</body>
</html>
Note: put the image into the public directory path and storage directory path
public/test.jpg
storage/app/public/test.jpg
You might also like: