Friday, April 14, 2017

Laravel 5.x Install DOM-PDF

Laravel is a strong php based framework today. Its very important that we can create PDF using our application. Laravel & DOM-PDF both makes it easy. Just follow the following steps:

1. Add the following line to "composer.json" in "require" section:

"barryvdh/laravel-dompdf": "^0.8.0"

2. Open command prompt and navigate to project directory & execute following command:

composer update barryvdh/laravel-dompdf --lock

Above command will install dompdf in your project

3. After installation open "conig/app.php" and add following line to providers:

Barryvdh\DomPDF\ServiceProvider::class

4. Add the following line to create an alias for dompdf:

'PDF' => Barryvdh\DomPDF\Facade::class

5. Now create a folder named "fonts" in "storage" folder.

This folder will used to store font cache.

6. Now create a Controller as follows:



<?php
namespace App\Http\Controllers;

use PDF;
use Illuminate\Routing\Controller as BaseController;

class HomeController extends BaseController
{
    public function pdf()
    {
        $pdf = PDF::loadView('home.pdf');
        //return $pdf->download('review.pdf'); //Download        
        return $pdf->stream('review.pdf'); //Stream    
    }
}
?>


7. Now create a view under "resource/views/home" named "pdf.blade.php" with following contents:


<!DOCTYPE html>
<html lang="en" >
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'>
</head>
<body>
<h1>Test PDF</h1>
</body>
</html>


8. Add the following line to "routes/web.php":


Route::get('/pdf', "HomeController@pdf");

9. Now browser {{Base_Url}}/pdf to view your pdf:




10. You are done.

1 comment: