Table of contents

laravel pdf generator

In this post is a Laravel 9 PDF tutorial on how to generate HTML to PDF files using DomPDF. Sometimes in our application, we need to generate a PDF file for reporting or maybe an invoice. Let's do this by using the Laravel DomPDF package which is easier for us because we just use an HTML view and convert it to PDF.

 

So let's start the tutorial and generate Laravel PDF.

 

Step 1: Laravel Installation

If you don't have a Laravel 9 install in your local just run the following command below:

composer create-project --prefer-dist laravel/laravel laravel-pdf-example

cd laravel-pdf-example

 

Step 2: Install dompdf Package

To generate HTML to PDF in Laravel we need to install barryvdh/laravel-dompdf package. Run the following command below:

composer require barryvdh/laravel-dompdf

 

Step 3: Setup Routes and Controller

Let's create routes and controllers for our Laravel PDF generator.

 

routes.php/web.php

<?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('/', function () {
    return view('welcome');
});

Route::get('pdf', [PdfController::class, 'index']);

 

Run the command below to make a controller:

php artisan make:controller PdfController

 

Then edit the PdfController generated. See below:

<?php

namespace App\Http\Controllers;

use PDF;
use Illuminate\Http\Request;

class PdfController extends Controller
{
    public function index() 
    {
    	$pdf = PDF::loadView('pdf.sample', [
    		'title' => 'CodeAndDeploy.com Laravel Pdf Tutorial',
    		'description' => 'This is an example Laravel pdf tutorial.',
    		'footer' => 'by <a href="https://codeanddeploy.com">codeanddeploy.com</a>'
    	]);
    
        return $pdf->download('sample.pdf');
    }
}

 

Step 4: Setup View

Now, let's set up our view for our PDF generator. In this example, I create a pdf folder inside resources/views/ and then create a blade file sample.blade.php. See below sample code:

<!DOCTYPE html>
<html>
<head>
	<title>{{ $title }}</title>
</head>
<body>
	<p>{{ $description }}</p>

	<br>

	<p>Put your text here.</p>

	<p>Place your dynamic content here.</p>

	<br>

	<p style="text-align: center;">{!! $footer !!}</p>
</body>
</html>

 

Now, that our code is ready let's test it by running the commands below:

php artisan serve

 

then run the URL below to your browser:

http://127.0.0.1:8000/pdf

 

Here is the example generated a result of Laravel PDF using dompdf:

 

laravel pdf