How To Download PDF File Using AJAX In Laravel 9

  Jul 2023
  ITSolutionsGuides
  Category: Laravel
How To Download PDF File Using AJAX In Laravel 9

Hi Developers,

Lets see How To Download PDF File Using AJAX In Laravel 9

Lets install Laravel

Lets install the new laravel project by using the following command

Laravel new laravel_pdf_download

Install Dompdf Package

Now, we will install barryvdh/laravel-dompdf package using the composer command. So, run the following command.

composer require barryvdh/laravel-dompdf

Configuration

After that, we will add the service provider and alias to the app.php config file.

config/app.php

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

Adding the Routes

In this step, we will add a route to the web.php file.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;
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('/', function () {
    return view('welcome');
});


Route::get('pdf', [PDFController::class, 'index']);
Route::get('generate-pdf', [PDFController::class, 'generatePDF']);

Create Controller

Now, we will create a PDFController using the following command.

php artisan make:controller PDFController

app/Http/Controllers/PDFController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use PDF;

class PDFController extends Controller
{
    public function index()
    {
        return view('index');
    }

    public function generatePDF()
    {
        $pdf = PDF::loadView('generate_pdf');

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

        $pdf = public_path($fileName);
        return response()->download($pdf);
    }
}

Create Blade File

Now, we will create an index.blade.php file and load the pdf file and download the pdf file using ajax.

resources/views/index.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>How To Download PDF File Using AJAX In Laravel 9 - ITSolutionsGuides</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:#fff;
        }
        .section{                       
            background:#fff;
        }
        .pdf-btn{
            margin-top:30px;
        }
    </style> 
<body>
    @include('generate_pdf')
    <div class="text-center pdf-btn">
        <button type="button" class="btn btn-dark 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: "{{route('generate.pdf')}}",
            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 = "itsolutionsguides.pdf";
                link.click();
            },
            error: function(blob){
                console.log(blob);
            }
        });
    });

</script>
</html>

Create New Blade File

resources/views/generate_pdf.blade.php

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>How To Download PDF File Using AJAX In Laravel 9 - ITSolutionsGuides</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:#fff;
        }
        .section{
            margin-top:30px;            
            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>How To Download PDF File Using AJAX In Laravel 9 - ITSolutionsGuides</h2>
                    </div>
                    <div class="panel-body">
                        <div class="main-div">
                            <h3>What is the moto of ITSolutionsGuides?</h3>
                           ITSolutionsGuides was started mainly to provide good and quality web solutions for all the developers.As a web developer we all know the struuggles of the web developers while facing any issues. We started ITSolutionsGuides to share our experience to all the developers. Kindly please support us for providing the quality content also feel free to contact us. We have social media accounts also to spread our knowledge across all the platforms.<br><br>                                                      
                        </div>
                    </div>
                </div>
            </div>
        </div>    
    </body>
</html>

Run Laravel Application

Lets see the output by running the application

php artisan serve

We hope it helps everyone. Thanks for supporting ITSolutionsGuides and keep supporting us also follow us in social media platforms.

Subscribe for NewsLetter

Be the first to know about releases and tutorial news and solutions.

We care about your data in our privacy policy.

ITSolutionsGuides

ITSolutionsGuides was started mainly to provide good and quality web solutions for all the developers. We provide tutorials to support all the developers and also we try to provide solutions to the errors we face while coding.

Contact US

ITSolutionsGuides, provide users with an easy-to-use form to reach out for support or inquiries.

whatsapp  gmail  instagram-new--v1  facebook-circled  twitter-circled  linkedin  github  pinterest 

Copyright © 2023 - 2024 All rights reserved | ITSolutionsGuides