Share, Read & Learn

Laravel 5 Export to PDF using laravel-dompdf

27 46,495

In this article, we will discuss Laravel 5 Export to PDF. I will show an example, so you can easily generate a pdf file for your Laravel App. We will create pdf from a view, in this view, we will write the HTML code and load data dynamically from the database as per the requirement. After that, we will export this view as a PDF file.

Before proceeding, I’m assuming you are familiar with the basics of the Laravel framework. If no then you can start with given articles.

# Setup laravel-dompdf package through the composer

Firstly, we need to install the “barryvdh/laravel-dompdf” package. It’s easy to install using given composer command:

composer require barryvdh/laravel-dompdf

# Configure package with the Laravel App

After executing the above command, time to update Service Provider to the providers and facade to the aliases array in config/app.php.

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

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

Let publish the assets from the vendor using the given artisan command.

php artisan vendor:publish

After executing the above command, list of available packages shown. You can select as per your need. Now, we are selecting the “Provider: Barryvdh\DomPDF\ServiceProvider” and the new file is copied to the config/dompdf.php. This file contains the global settings for the dompdf package.

# Setup blade view template for PDF

We are creating the simple HTML table for this example. You can update this HTML as per your requirement.

<h1>Customer List</h1>

<table>
  <thead>
    <tr>
      <th>ID</th>
      <th>Name</th>
      <th>Email</th>
      <th>Phone</th>
    </tr>
  </thead>
  <tbody>
    @foreach($data as $customer)
      <tr>
        <td>{{ $customer->id }}</td>
        <td>{{ $customer->name }}</td>
        <td>{{ $customer->email }}</td>
        <td>{{ $customer->phone }}</td>
      </tr>
    @endforeach
  </tbody>
</table>

In this, we are creating just HTML template where just generate a table. This table contains the customer details such as customer name, email, phone and etc. You can change the view as per your PDF required.

# Setup blade view to display all the listed records

In this view, we create a view which displays our customer list with the export button. Export button is used to trigger the export pdf functionality.

@section('content')
<h1>Customer List</h1>
<a href="{{ URL::to('/customers/pdf') }}">Export PDF</a>

<table>
  <thead>
    <tr>
      <th>ID</th>
      <th>Name</th>
      <th>Email</th>
      <th>Phone</th>
    </tr>
  </thead>
  <tbody>
    @foreach($data as $customer)
      <tr>
        <td>{{ $customer->id }}</td>
        <td>{{ $customer->name }}</td>
        <td>{{ $customer->email }}</td>
        <td>{{ $customer->phone }}</td>
      </tr>
    @endforeach
  </tbody>
</table>
@endsection

# Setup Model

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{
    public $table = 'customers';
    protected $fillable = [
        'name', 'email', 'mobileno'
    ];
}

# Register routes for our app

Register the route for export pdf. When an URL customer/pdf hits the report generate and store on the server then download start. You can control the storage path as per your need.

Route::get('/customers/pdf','CustomerController@export_pdf');

# Update controller with export pdf function

Here’s our controller function where all logics performed.

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use PDF;

class CustomerController extends Controller
{
  public function export_pdf()
  {
    // Fetch all customers from database
    $data = Customer::get();

    // Send data to the view using loadView function of PDF facade
    $pdf = PDF::loadView('pdf.customers', $data);

    // If you want to store the generated pdf to the server then you can use the store function
    $pdf->save(storage_path().'_filename.pdf');

    // Finally, you can download the file using download function
    return $pdf->download('customers.pdf');
  }
}

Finally, everything’s ready now when we click on the export pdf button then download start. Feel free to comment if any query.

Leave A Reply

Your email address will not be published.

27 Comments
  1. heshan says

    ErrorException (E_NOTICE)
    tempnam(): file created in the system’s temporary directory

    1. Code Briefly says

      Hi Heshan

      Add more details to explain your issue. It’s hard to regenerate the similar situation.

      1. heshan says

        public function generatePDF()

        {

        $students = Student::all();

        $pdf = PDF::loadView(‘admin.index’, compact(‘students’));

        return $pdf->download(‘page.pdf’);

        }

        this is my code when i run the error shows i try to change the temp directory in php.ini but nothing changes

  2. rassloff says

    how can I made the PDF more dynamic. so that the table ends on each side with a summary how mach data were printed on this page. and then on the new page: the tmp summary of the last page as first line of the table….

  3. Andrei says

    Hello! I am using your example but I get this: fopen(/home/sites/public_html/victorylive/storage/fonts//c20bfe36614e3b5d60369198deb5d1ad.ufm): failed to open stream: No such file or directory

    Laravel 5.6.2 and PHP 7.2.0

    1. Code Briefly says

      Hi Andrei

      This example is working fine at my end. Not able to regenerate this issue.
      Please check once at your end.

      Thanks 🙂

    2. Jason says

      You just need to go to /storage and create a /fonts folder with the right permission settings. chmod 777 fonts

      1. Shraddha says

        Thankyou so much

  4. ali reza says

    can we use customized table with external css including it??

    1. Code Briefly says

      Hello Ali,
      Yes, you can use 🙂

  5. Emmanuelle says

    how about in specific ID how can i print it out ?

    1. Code Briefly says

      Hi Emmanuele

      Will you please describe your issue. So I can help you. 🙂

  6. Waseem says

    I am Waseem Asghar and New laravel web developer. Can you please suggest me book for laravel pdf creator.

    Thanks

  7. Ax3 says

    Hi, I need some help. When I genetare the pdf, it does not display any style form the css. I have it on a partial view, and call it using blade’s @include() method to a complete view. But, after that, when I click the button to generate the pdf, it does it but whitout styling it. Any ideas?

  8. Miley Cyrus says

    Your article Awesome Thanks for this information, very informative as well as Modern.

  9. jeco says

    I have an issue, Undefined variable: agencies (View: C:\xampp\htdocs\ecoteneo\resources\views\agencypdf.blade.php)

    i follow your code:

    controller:

    public function export_pdf()
    {

    $agencies = Agency::get();

    $pdf = PDF::loadView(‘agencypdf’, $agencies);

    $pdf->save(storage_path().’_filename.pdf’);

    return $pdf->download(‘agencies.pdf’);
    }

    my blade for pdf:

    Agency List

    Agency
    Address
    Phone

    @foreach($agencies as $Agency)

    {{ $Agency->name }}
    {{ $Agency->email }}
    {{ $Agency->phone }}

    @endforeach

    1. Pankaj Sood says

      Hi Jeco, Use “compact()” as given below.

      $pdf = PDF::loadView(‘agencypdf’, compact(‘agencies’));

      1. jeco says

        Thank you. I have another problem. That code works. I use it in another form and I just copy and paste that code. Now the problem for the another is it returns the blank page.

        if(Auth::user()->campus_id == 0){
        $processes = Process::join(‘bags’,’processes.bag_id’, ‘=’, ‘bags.id’)
        ->join(‘stations’,’processes.station_id’, ‘=’, ‘stations.id’)
        ->select(‘bags.*’,’stations.*’,’processes.*’)
        ->where(‘stations.campus_id’, Session::get(‘test’))
        ->orderBy(‘processes.id’, ‘desc’)
        ->get();

        $pdf = PDF::loadView(‘collectionReportspdf’, compact(‘processes’));

        $pdf->save(storage_path().’_filename.pdf’);

        return $pdf->download(‘collection-reports.pdf’);

        }

        else
        {
        $processes = Process::join(‘bags’,’processes.bag_id’, ‘=’, ‘bags.id’)
        ->join(‘stations’,’processes.station_id’, ‘=’, ‘stations.id’)
        ->select(‘bags.*’,’stations.*’,’processes.*’)
        ->where(‘stations.campus_id’, Auth::user()->campus_id)
        ->orderBy(‘processes.id’, ‘desc’)
        ->get();

        $pdf = PDF::loadView(‘collectionReportspdf’, compact(‘processes’));

        $pdf->save(storage_path().’_filename.pdf’);

        return $pdf->download(‘collection-reports.pdf’);
        }

        1. Jereh Tejano says

          Hi, are you sure that the query is returning any value?

          1. Code Briefly says

            Hi Jereh, please explain your issue.

        2. SalkinRah says

          Hi Jeco,

          I’ve got the same problem as you because I’ve added the laravel expressions “@section” and “@endsection” to my blade view template for PDF.

          These expression tells laravel, that the file is about a template file which should get included into your layout file (you added “@yield(‘content’) here, which always includes the html markup between the expressions mentioned above”).

          If you remove them (mentioned content-expressions), it works fine. 🙂

  10. Muhammad yasir says

    Thanks you very much keep it up!!

  11. Appurva Ambagade says

    Hey, nice tutorial but I’m getting this error Undefined variable: data

    here’s my controller method

    $data = DummyCreate::get();

    $pdf = PDF::loadView(‘DummyCreate.auditlist’,$data);

    $pdf->save(storage_path().’_filename.pdf’);

    return $pdf->download(‘dynamic_pdf.pdf’);

  12. TommyD says

    Hello i have problem, my view template is not showing dynamic variables from database.

    This is my controller:

    public function printPDF()
    { $users = \App\User::get();
    $pdf = PDF::loadView(‘users_pdfview’, compact(‘users’));
    return $pdf->download(‘users.pdf’); }

    This is my PDF view blade:

    ID
    Imię
    Nazwisko
    Email
    Nr telefonu
    Rola

    @foreach($users as $user)

    {{$user->id}}
    {{$user->name}}
    {{$user->nazwisko}}
    {{$user->email}}
    {{$user->telefon}}
    @php if ($user->is_admin==’1′) {
    @endphp
    Admin
    @php }
    else {
    @endphp
    User
    @php }
    @endphp

    @endforeach

    I got only HTML code, for example “{{$user->id}}” is showing as “{{$user->id}}”, it looks like it are not downloading data from database. Can You help me?

    Thanks, Tom.

  13. nikhil garg says

    i am getting this error (Class ‘App\Http\Controllers\Customer’ not found)

  14. shaqayq says

    hi!
    my persian data dont show in pdf
    what is the problem?

    1. Code Briefly says

      Did you add the fonts?