In this tutorial, i will tell you how to generate pdf file from HTML view in Laravel PHP by using laravel-dompdf
package.
There are lots of packages too that are using to generate pdf and using HTML and CSS, you can easily set the beautiful layout for pdf file.
Using laravel-dompdf
library, you can easily generate pdf file in your Laravel web application.
Generating pdf files are helpfull when you are sending report in email from large amount of data then you can convert your html view in single pdf file and then attach with your mail.
Dompdf
is a PHP library which is used to generate PDF file from HTML view.
In this step you are going to install laravel-dompdf
package to generate pdf file from HTML view blade file.
You can use composer to download this plugins so copy this command and run in your terminal promp.
composer require barryvdh/laravel-dompdf
Now after downloading libraries you will have to set their service provider and aliase in following path config/app.php
.
- 'providers' => [
- ....
- Barryvdh\DomPDF\ServiceProvider::class,
- ],
- 'aliases' => [
- ....
- 'PDF' => Barryvdh\DomPDF\Facade::class,
- ],
I assume that you have successfully download libraries of laravel-dompdf
so let's start with route file.
add below line of code in your routes.php
which you will get in following path app/Http/routes.php
.
- Route::get('htmltopdfview',array('as'=>'htmltopdfview','uses'=>'ProductController@htmltopdfview'));
Now i am going to create ProductController and assume that you will have product model and table with some dummy data that will be used to list result.
In htmltopdfview method, i am sharing a global variable which you can use anywhere in your application and use pdf class to load view to generate in pdf file.
app/Http/Controllers/ProductController.php
- namespace App\Http\Controllers;
- use App\Http\Requests;
- use Illuminate\Http\Request;
- use App\Product as Product;
- use PDF;
- class ProductController extends Controller
- {
- public function htmltopdfview(Request $request)
- {
- $products = Products::all();
- view()->share('products',$products);
- if($request->has('download')){
- $pdf = PDF::loadView('htmltopdfview');
- return $pdf->download('htmltopdfview');
- }
- return view('htmltopdfview');
- }
- }
Finally you will have to create a view where you will list down all your products and will generate this view in pdf file too.
resources/view/htmltopdfview.blade.php
- <div class="row">
- <a href="{{ route('htmltopdfview',['download'=>'pdf']) }}">Download PDF</a>
- <table>
- <tr>
- <th>Name</th>
- <th>Details</th>
- </tr>
- @foreach ($products as $product)
- <tr>
- <td>{{ $product->name }}</td>
- <td>{{ $product->details }}</td>
- </tr>
- @endforeach
- </table>
- </div>