How to convert html to pdf in Laravel 8

Hello guys, in accounting or ecommerce application, you always need to generate PDF files. In this article, we will work on how to convert HTML view to PDF in Laravel 8.

We will use barryvdh/laravel-dompdf Laravel package to generate PDF file. This package is simple to use and provides many customization option without any issue.

In this article we will create Laravel 8 project and add PDF functionality step by step. So lets start first creating Laravel project.

Step-1: Create Laravel project

First create Laravel 8 project using composer from your Terminal or Command prompt.

composer create-project laravel/laravel htmlpdf

Once the project created successfully, go to the project folder in Terminal and generate application key.

php artisan key:generate

Step-2: Install package

Now install barryvdh/laravel-dompdf package with below command.

composer require barryvdh/laravel-dompdf

Step-3: Configure package

After the package installation completes, open config/app.php file and add the below line in providers arrray.

'providers' => [
    ....
    Barryvdh\DomPDF\ServiceProvider::class,
    ....
],

In the same file, set the class alias in aliases array.

'aliases' => [
    ....
    'PDF' => Barryvdh\DomPDF\Facade::class,
    ....
],

Step-4:PDF settings

Run the command and it will create config/dompdf.php file. You can change PDF settings in this file, like paper size, font type, DPI etc.

php artisan vendor:publish --provider="Barryvdh\DomPDF\ServiceProvider"

Step-5: Create route

Create PDF download route in routes/web.php file.

<?php

Route::get('html-pdf', '[email protected]')->name('htmlPdf');

Step-6: Create Controller file

Now create controller with below command to handle PDF download route. This will generate app/Http/Controllers/HTMLPDFController.php

php artisan make:controller HTMLPDFController

Open HTMLPDFController.php file and add htmlPdf() function. Here is the full controller file.

<?php

namespace App\Http\Controllers;

use PDF;
use Illuminate\Http\Request;

class HTMLPDFController extends Controller
{
    /**
     * generate PDF file from blade view.
     *
     * @return \Illuminate\Http\Response
     */
    public function htmlPdf()
    {
        // selecting PDF view
        $pdf = PDF::loadView('htmlView');

        // download pdf file
        return $pdf->download('pdfview.pdf');
    }
}

Note: From Laravel 8 onwards, you have to uncomment $namespace variable in app/Providers/RouteServiceProvider.php file to use set default Controller path to app/Http/Controllers

/**
 * The controller namespace for the application.
 *
 * When present, controller route declarations will automatically be prefixed with this namespace.
 *
 * @var string|null
 */
protected $namespace = 'App\\Http\\Controllers';

Step-7: Create view file

Create view file in ressource/views/htmlPdf.blade.php. This is the file which we will convert to PDF. I have added simple HTML views in the blade file. 

<!DOCTYPE html>
<html lang="en-US">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>HTML 2 PDF</title>
        <style type="text/css">
            .center {
                text-align: center;
            }
        </style>
    </head>
    <body>
        <div class="center">
            <h1>This is heading</h1>
        </div>
        <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>
    </body>
</html>

That's all. Now run the application with below artisan command.

php artisan serve

Open the below url in browser and it will download pdfView.pdf file.

http://localhost:8001/html-pdf

While loading external library like bootstrap you may get error:

ErrorException
fopen(/var/www/html/htmlpdf/storage/fonts//glyphicons_halflings_normal_4ced20531a4f462a8c5c535d4debd2eb.ufm): failed to open stream: No such file or directory

For this solution, create fonts folder into storage folder and provide 777 permission. 

Happy coding!

Tags:

Was this article helpful?

1 out of 1 person found this article helpful.

Leave a comment

Or

1 Comment

SA
malpon nani
August 31, 2021

thanks