In this tutorial we are going to learn how to generate pdf in laravel. I have seen a lot of people struggling to convert html to pdf in laravel and could not find the easy one.
The one we are going to see in this tutorial of laravel pdf generator with image is for starters. I am going to make another tutorial soon on how to export HTML to pdf in which you can control almost any aspect of the page.
Let’s get started.
What are we going to do?
- Install DOM PDF Wrapper package By Barrdyvdh into our project.
- Create a new blade template for the view and add some text and images that we need to export into the pdf.
- Create PdfController and write the implementation to export html to pdf in laravel.
I assume by now you have your dummy laravel project ready to get started. Rest we will catch along the way.
How to Generate Pdf in Laravel?
Step – 1
First, we need to install the DOM PDF wrapper package by barryvdh. You can also view their documentation in thisĀ link.
composer require barryvdh/laravel-dompdf
Register it inside config/app.php
in both providers and alias section.
1 2 3 4 |
'providers' => [ ... Barryvdh\DomPDF\ServiceProvider::class, ], |
1 2 3 4 |
'aliases' => [ ... 'PDF' => Barryvdh\DomPDF\Facade::class, ] |
Step – 2
For the sample we are going to load a custom view where there will be some text and images and later we are going to use it for export.
I will quickly a page with some text and image with bootstrap 4. You can use the sample below too or integrate into your own app.
So, create a new file inside resources/views
as index.blade.php
and write this code below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>How to Export HTML to Pdf in Laravel</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"> </head> <style> body { margin: 0; padding: 0; font-size: 14px; background-image: linear-gradient(315deg, #9fa4c4 0%, #9e768f 74%); font-family: sans-serif; background-size: cover; } h1 { font-size: 22px; } .container { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 600px; padding: 30px; background: #fff; box-sizing: border-box; border-radius: 10px; box-shadow: 0 15px; 50px rgba(0, 0, 0, .2) } .image { width: 200px; height: 200px; background: url(authr.jpg); background-size: cover; float: left; margin: 30px 30px 30px 0; } </style> <body> <div class="navbar navbar-expand-lg navbar-light bg-light print-hide"> <a class="navbar-brand" href="#">Laravel Export PDF</a> <div class="collapse navbar-collapse"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a href="javascript:void(0)" class="nav-link" onclick="export2Pdf()">Download PDF</a> </li> </ul> </div> </div> <div class="container"> <div class="image"></div> <h1>Some Random Text Title Content</h1> <div class="content"> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Blanditiis dicta dolorem, expedita ipsum maiores quas sapiente vero. Beatae dolore dolores ducimus eos, iusto laborum possimus quibusdam reprehenderit soluta vero voluptatibus?. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ab alias asperiores atque, blanditiis consequuntur cupiditate, delectus ea facilis ipsam laborum magni maiores molestiae natus porro quod recusandae saepe sequi sint!. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ad architecto esse facere ipsum ratione. Adipisci animi cumque eligendi excepturi harum praesentium quia. Aperiam cum, error molestiae quae quaerat repudiandae unde?. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aut consequatur culpa cum debitis deserunt dolor, et expedita fugiat labore minus modi nam nostrum provident quam quasi quo veniam voluptas voluptates. </p> </div> </div> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> </body> </html> |
Serve your application to see how your view is going to look. Your view should look a gradient background with a text similar to featured image this if you are using the dummy content of this tutorial.
Step – 3
let’s create one pdf controller and load the view that we have just created with the help of routes.
Go to your terminal and enter.
php artisan make:controller PdfController
Once PdfController.php
is created open it and create a function to return the index.blade.php
the view that you have just created with a dummy content.
1 2 3 4 5 6 7 8 9 10 |
namespace App\Http\Controllers; use Illuminate\Http\Request; class PdfController extends Controller { public function index() { return view('index'); } } |
Register inside your routes too.
web/routes.php
1 |
Route::get('/', [App\Http\Controllers\PdfController::class, 'index']); |
Now, let export our content to PDF. Create a new route in routes/web.php
.
1 |
Route::get('/export-pdf', [App\Http\Controllers\PdfController::class, 'exportPdf']); |
Create a function called exportPdf() inside PdfController as these piece of codes below:-
1 2 3 4 5 6 7 8 |
public function exportPdf() { $pdf = PDF::loadView('index'); // <--- load your view into theDOM wrapper; $path = public_path('pdf_docs/'); // <--- folder to store the pdf documents into the server; $fileName = time().'.'. 'pdf' ; // <--giving the random filename, $pdf->save($path . '/' . $fileName); $generated_pdf_link = url('pdf_docs/'.$fileName); return response()->json($generated_pdf_link); } |
Finally, add this piece of javascript in your blade file before your </body>
tag.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<script> const export2Pdf = async () => { let printHideClass = document.querySelectorAll('.print-hide'); printHideClass.forEach(item => item.style.display = 'none'); await fetch('http://localhost:8000/export-pdf', { method: 'GET' }).then(response => { if (response.ok) { response.json().then(response => { var link = document.createElement('a'); link.href = response; link.click(); printHideClass.forEach(item => item.style.display=''); }); } }).catch(error => console.log(error)); } </script> |
If you do not want some part of your dom to render in pdf. Then just add print-hide
class and the javascript logic will automatically discard that part of dom in the browser.
Press download and check to see your downloaded file. If the splits of the file in confusing you here your final code should look like.
PdfController.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php namespace App\Http\Controllers; use Barryvdh\DomPDF\Facade as PDF; class PdfController extends Controller { public function index() { return view('index'); } public function exportPdf() { $pdf = PDF::loadView('index'); // <--- load your view into theDOM wrapper; $path = public_path('pdf_docs/'); // <--- folder to store the pdf documents into the server; $fileName = time().'.'. 'pdf' ; // <--giving the random filename, $pdf->save($path . '/' . $fileName); $generated_pdf_link = url('pdf_docs/'.$fileName); return response()->json($generated_pdf_link); } } |
index.blade.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 |
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>How to Export HTML to Pdf in Laravel</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"> </head> <style> body { margin: 0; padding: 0; font-size: 14px; background-image: linear-gradient(315deg, #9fa4c4 0%, #9e768f 74%); font-family: sans-serif; background-size: cover; } h1 { font-size: 22px; } .container { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 600px; padding: 30px; background: #fff; box-sizing: border-box; border-radius: 10px; box-shadow: 0 15px; 50px rgba(0, 0, 0, .2) } .image { width: 200px; height: 200px; background: url(authr.jpg); background-size: cover; float: left; margin: 30px 30px 30px 0; } </style> <body> <div class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Laravel Export PDF</a> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a href="javascript:void(0)" class="nav-link" onclick="export2Pdf()">Download PDF</a> </li> </ul> </div> </div> <div class="container"> <div class="image"></div> <h1>Some Random Text Title Content</h1> <div class="content"> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Blanditiis dicta dolorem, expedita ipsum maiores quas sapiente vero. Beatae dolore dolores ducimus eos, iusto laborum possimus quibusdam reprehenderit soluta vero voluptatibus?. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ab alias asperiores atque, blanditiis consequuntur cupiditate, delectus ea facilis ipsam laborum magni maiores molestiae natus porro quod recusandae saepe sequi sint!. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ad architecto esse facere ipsum ratione. Adipisci animi cumque eligendi excepturi harum praesentium quia. Aperiam cum, error molestiae quae quaerat repudiandae unde?. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aut consequatur culpa cum debitis deserunt dolor, et expedita fugiat labore minus modi nam nostrum provident quam quasi quo veniam voluptas voluptates. </p> </div> </div> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> <script> const export2Pdf = async () => { let printHideClass = document.querySelectorAll('.print-hide'); printHideClass.forEach(item => item.style.display = 'none'); await fetch('http://localhost:8000/export-pdf', { method: 'GET' }).then(response => { if (response.ok) { response.json().then(response => { var link = document.createElement('a'); link.href = response; link.click(); printHideClass.forEach(item => item.style.display=''); }); } }).catch(error => console.log(error)); } </script> </body> </html> |
routes/web.php
1 2 |
Route::get('/', [App\Http\Controllers\PdfController::class, 'index']); Route::get('/export-pdf', [App\Http\Controllers\PdfController::class, 'exportPdf']); |
That is it on how to generate pdf in laravel. Have any other suggestion for laravel pdf generator with image options? Let us know via comments.
Leave a Reply