How to Add Image to PDF File in Laravel

Hi Artisan, in this tutorial I’m going to share how to add image to PDF file in Laravel application. I’m testing on Laravel 7. Let’s get started:

Table of Contents

  1. Create Laravel Project
  2. Install dompdf Package
  3. Make Controller
  4. Make View File
  5. Define Route

Create Laravel Project

Each Laravel project needs this thing. That’s why I have written an article on this topic. Please see this part from here: Install Laravel and Basic Configurations.

Install dompdf Package

Run this command to install barryvdh/laravel-dompdf package:

composer require barryvdh/laravel-dompdf

Make Controller

Let’s make a controller named PDFController using this command:

php artisan make:controller PDFController

Open the controller and paste this code:

app/Http/Controllers/PDFController.php
<?php

namespace App\Http\Controllers;

use PDF;
use Illuminate\Http\Request;

class PDFController extends Controller
{
    public function makePDF()
    {
        $data = ['title' => 'MyNotePaper.com'];

        $pdf = PDF::loadView('pdf', $data);

        return $pdf->download('mnp.pdf');
    }
}

Make View File

Before making the blade file, I’m keeping a dummy picture at location public/mypic.jpg. Now navigate to resources/views path and create a file named pdf.blade.php.

pdf.blade.php
<!DOCTYPE html>
<html>
<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>The picture:</strong><br/><br/>
<img src="{{ public_path('mypic.png') }}">
</body>
</html>

Define Route

This is the last step. Register a route for makePDF() function:

routes/web.php
Route::get('pdf','PDFController@makePDF');

Now, run the project and see the output by navigating to http://example.com/test route.

That’s it. Thanks for reading.