HDTuto.com

How to create PDF file in Laravel 5.6?


Hi Developer, here is an available simple example of generating pdf file from laravel blade view using barryvdh/laravel-dompdf composer package in Laravel 5.6 application. You just need to follow step and get to generate pdf file.

Here we will install barryvdh/laravel-dompdf composer package and then add laravel facade and provider. I give you also simple example to generate pdf file from blade file view in laravel 5.6 application.

so, just follow the following step and get to the code of pdf file generation.

Install Package:

first of all we will install barryvdh/laravel-dompdf composer package by following composer command in your laravel 5.6 application.

composer require barryvdh/laravel-dompdf

After successfully install package, open config/app.php file and add service provider and alias.

config/app.php

'providers' => [

....

Barryvdh\DomPDF\ServiceProvider::class,

],

'aliases' => [

....

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

]

Create Route:

Now we will add routes for demo example, so simply add following route in your route file:

routes/web.php

Route::get('generate-pdf','HomeController@generatePDF');

Create HomeController:

Here,we require to create new controller HomeController that will manage generatePDF method of route. So let's put bellow code.

app/Http/Controllers/HomeController.php

<?php


namespace App\Http\Controllers;


use Illuminate\Http\Request;

use PDF;


class HomeController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function generatePDF()

{

$data = ['title' => 'Welcome to HDTuto.com'];

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


return $pdf->download('hdtuto.pdf');

}

}

Add myPDF.blade.php File:

At last we require to create blade file call myPDF.blade.php. So let's add bellow code:

resources/views/myPDF.blade.php

<!DOCTYPE html>

<html>

<head>

<title>Hi</title>

</head>

<body>


<h1>{{ $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>


</body>

</html>

I hope you found best example.....






February 27, 2018 | Category : PHP Laravel Laravel 5 Laravel 5.6
Related Posts