Laravel 5 Export to PDF using laravel-dompdf

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.

If you like our content, please consider buying us a coffee.
Thank you for your support!
Buy Me a Coffee

dompdfExport PDFLaravelLaravel PDF
Comments (42)
Add Comment
  • heshan

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

    • Code Briefly

      Hi Heshan

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

      • heshan

        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

  • rassloff

    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….

  • Andrei

    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

    • Code Briefly

      Hi Andrei

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

      Thanks 🙂

    • Jason

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

      • Shraddha

        Thankyou so much

  • ali reza

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

  • Emmanuelle

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

    • Code Briefly

      Hi Emmanuele

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

  • Waseem

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

    Thanks

  • Ax3

    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?

  • Miley Cyrus

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

  • jeco

    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

    • Pankaj Sood

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

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

      • jeco

        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’);
        }

        • Jereh Tejano

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

        • SalkinRah

          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. 🙂

  • Muhammad yasir

    Thanks you very much keep it up!!

  • Appurva Ambagade

    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’);

  • TommyD

    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.

    • mohamed

      same eror are you fix it plz help me

      • mohamed

        same error do you fix it please help me

  • nikhil garg

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

  • shaqayq

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

  • Rvi

    How to add font in storage/fonts folder please help me

  • Arturas

    ErrorException
    file_put_contents(/var/www/biblioteka/storage_filename.pdf): failed to open stream: Permission denied

    lamp linux mint

  • Sohanur Rahman

    Invalid characters passed for attempted conversion, these have been ignored

  • basheer alam

    many many thanks for help code briefly

  • Aleem Ali

    Hey,
    Thanks a lot for sharing the code of PDFDOM..
    I need a help:
    return $pdf->download(‘welcome.pdf’);
    above code is download the pdf but i just want to display the generated pdf in new tab..
    I tried the below code but it’s not working for me..

    $pdf->stream(“welcome.pdf”, array(“Attachment” => 0));

  • Andy

    Hello, I am facing an issue the pdf that is created, is not opening and the viewer is showing an error of damaged or corrupted PDF.

    • Pankaj Sood

      Share more details, it’s hard to reproduce the same issue.

  • Nitha Shivan

    can u help me.I need only to generate pdf after execution of query not download .save it in server and mail the same to someone’s mail

  • Manjeet

    How can we disable copy text from created pdf. ?

  • Pankaj

    how to add watermark on pdf in laravel. if my value get from table? I am using dompdf.

  • Grace

    Hi Pankaj,
    Thank you for the help. I want to download only the values that have been selected in the database with a where clause. In the view my link “export to pdf” will have href=”mypage/{{$test->id}} but I want the $test->id to be an array of all the ids that have been selected in the database and are hold in the $test variable. I am new and don’t understand how I can proceed this. Could help on this.

    Thank you,
    Grace

  • Grace

    Hi Pankaj,
    I wanted to rephrase my question. What if $data hold the result from a select * from table with where clause in the query and I want to pass all its return id in the url to be exported to pdf.

    Thank you,
    Grace

  • Charles Taylor

    Hello,
    Thank you for this information, however i am working in a huge system and i need to generate user cvs in pdf.
    the user have profile and cv table separate, however i join them in one page called details.
    The details.blade.php has @extends(‘layouts.master’) and many more…

    I can generate the page but it comes with all other html stuff such as buttons, links, footer, menu… please help me on how to just generate the content of the details page without links or buttons or footer?

    Thanks in advanced