Laravel 9 PDF File Download using JQuery Ajax Request Example

May 10, 2022 . Admin

Hi Guys,

In this example, I will learn you how to download a pdf file using jquery ajax in laravel 9.you can easy and simply download a pdf file using jquery ajax in laravel 9.

In this example, we will install the barryvdh/laravel-dompdf composer package, and then after we will add a new route with a new controller file.

PDF is one of the basic requirements when you are working with erp level project or e-commerce website. we may need to create a pdf file for the report or invoice etc. So, here I will give you a very simple example for create and download file in laravel 9.

Step 1: Download Laravel
Let us begin the tutorial by installing a new laravel application. if you have already created the project, then skip following step.
composer create-project laravel/laravel example-app
Step 2 : Install dompdf package

We need dompdf package for html design to generate pdf So let's open terminal run bellow command to install dompdf package:

composer require barryvdh/laravel-dompdf

After successfully install the package, open the config/app.php file and add the service provider and alias.

config/app.php
'providers' => [
    ....
    Barryvdh\DomPDF\ServiceProvider::class,
],
  
'aliases' => [
    ....
    'PDF' => Barryvdh\DomPDF\Facade::class,
]
Step 3 : Create Route

In this step, We have to create two route for one route is to preview a pdf and the second route is to generate a pdf and download a pdf file. So let's open the web.php file put below route:

routes/web.php
<?php

use App\Http\Controllers\PdfController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('pdf/preview', [PdfController::class, 'index']);
Route::get('pdf/generate', [PdfController::class, 'create']);
Step 4 : Create Controller

Here you can create a new controller as PdfController and add two method in this controller, the first method is a preview and the last one is generate pdf and download pdf. So let's open the terminal and put below command to create the controller file.

php artisan make:controller PdfController

Now we can add two methods in the PdfController file So let's open the PdfController.php file and put it below the code. we will store the pdf file in a public folder.

app/Http/Controllers/PdfController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use PDF;

class PdfController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        return view('pdf.index');
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function create()
    {
        $pdf = PDF::loadView('pdf.pdf');

        $path = public_path('pdf/');
        $fileName =  time().'.'. 'pdf' ;
        $pdf->save($path . '/' . $fileName);

        $pdf = public_path('pdf/'.$fileName);
        return response()->download($pdf);
    }
}
Step 5 : Create blade file

In last step. In this step, we have to create a preview blade file. So mainly we have to create a preview file. So finally you have to create one preview blade file for preview pdf design:

resources/views/pdf/index.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel 9 PDF File Download using JQuery Ajax Request Example</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
    @include('pdf.pdf')
    <div class="text-center pdf-btn">
        <button type="button" class="btn btn-info download-pdf">Download Pdf</button>
    </div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
    $(".download-pdf").click(function(){

        var data = '';
        $.ajax({
            type: 'GET',
            url: '/pdf/generate',
            data: data,
            xhrFields: {
                responseType: 'blob'
            },
            success: function(response){
                var blob = new Blob([response]);
                var link = document.createElement('a');
                link.href = window.URL.createObjectURL(blob);
                link.download = "Sample.pdf";
                link.click();
            },
            error: function(blob){
                console.log(blob);
            }
        });
    });

</script>
</html>
resources/views/pdf/pdf.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel 9 PDF File Download using JQuery Ajax Request Example</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<style type="text/css">
    h2{
        text-align: center;
        font-size:22px;
        margin-bottom:50px;
    }
    body{
        background:#f2f2f2;
    }
    .section{
        margin-top:30px;
        padding:50px;
        background:#fff;
    }
    .pdf-btn{
        margin-top:30px;
    }
</style>  
<body>
    <div class="container">
        <div class="col-md-8 section offset-md-2">
            <div class="panel panel-primary">
                <div class="panel-heading">
                    <h2>Laravel 9 PDF File Download using JQuery Ajax Request Example - Mywebtuts.com</h2>
                </div>
                <div class="panel-body">
                    <div class="main-div">
                            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                        tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
                        cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
                        proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
                        <br>
                        <br>
                            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                        tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
                        cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
                        proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
Run Laravel App: All steps have been done, now you have to type the given command and hit enter to run the laravel app:
php artisan serve
Now, you have to open web browser, type the given URL and view the app output:
localhost:8000/pdf/preview
Preview Design: Preview PDF:

It will help you...

#Laravel 9