How to Make PDF File in Laravel 7?

How to Generate pdf in laravel 7

In this simple tutorial, You will learn to install the laravel-dompdf and then we will start our example. In this tutorial i will show an example, You have to write the HTML and PHP code and retrieve data from database. Later, we will export this view as a PDF file.

First of all, you need some software to get started with laravel project : 

  • Xampp
  • Composer
  • Cmd

1st Step

  1. Goto C:\Xampp\htdocs
  2. Shift + Right Click to Open Command prompt here
  3. In Command prompt type (composer require barryvdh/laravel-dompdf) and press ↵ Enter.
  4. Dompdf will immediately begin to install.

2nd Step

Configure package with the Laravel App

‘providers’ => [

 Barryvdh\DomPDF\ServiceProvider::class,

],

‘aliases’ => [

 ‘PDF’ => Barryvdh\DomPDF\Facade::class,

]

3rd Step

Let’s publish all the steps we had done.

In Command prompt type (php artisan vendor:publish) and press ↵ Enter.

4th Step

# Setup blade view to retrieve data from DB for PDF generation

@section(‘content’)

<h1>Customer List</h1>

<a href=”{{ URL::to(‘/datas/pdf’) }}”>Export PDF</a>

<table>

  <thead>

    <tr>

      <th>ID</th>

      <th>Name</th>

      <th>Email</th>

      <th>Phone</th>

    </tr>

  </thead>

  <tbody>

    @foreach($datas as $data)

      <tr>

        <td>{{ $data->id }}</td>

        <td>{{ $data->name }}</td>

        <td>{{ $data->email }}</td>

        <td>{{ $data->phone }}</td>

      </tr>

    @endforeach

  </tbody>

</table>

@endsection

5th Step

use PDF;;  //Include the below line in the header section above the class

6th Step

Now time to create controller with export pdf function

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use PDF;

class CustomerController extends Controller

{

 public function export_pdf()

 {

 $data = datas::get();  // Fetch all customers from database

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

 $pdf->save(storage_path().’_filename.pdf’);  // If you want to store the generated pdf to the server 

 return $pdf->download(‘datas.pdf’);  // Finally you can download the file using download function

 }

}

Final Words

Finally, everything ready now when just click on the export pdf button to start the download. The steps provided by me in this tutorial is easy to perform by any person who is having a basic knowledge of computer. I’m happy to help you to fix that problem. Feel free to comment if any query.

Posted in LaravelTags:

Write a comment