Generating PDF Files in Laravel Using Dompdf: A Complete Guide

Published on : April 26,2023
Generating PDF Files in Laravel Using Dompdf: A Complete Guide

Laravel is a popular PHP web framework that provides a simple and elegant way to build web applications. One of the common requirements in many web applications is the ability to generate PDF files. PDF files are widely used for generating reports, invoices, and other documents that need to be printed or shared with others. In this article, we will look at how to generate PDF files in Laravel using a popular package called "Dompdf".

 

What is Dompdf?

Dompdf is an HTML to PDF converter written in PHP. It can convert HTML documents to PDF format, and it is widely used for generating PDF files in PHP applications. Dompdf is easy to use and provides a simple API for generating PDF files. It also supports CSS, which allows you to apply styles to your PDF documents.

 

Installing Dompdf in Laravel

To use Dompdf in Laravel, we need to install the package using Composer. Open your terminal and navigate to your Laravel project directory. Then, run the following command to install the package:

composer require dompdf/dompdf

After installing the package, we need to add the service provider and alias to our Laravel configuration. Open the config/app.php file and add the following lines to the providers array:

Dompdf\ServiceProvider::class,

And add the following line to the aliases array:

'PDF' => Dompdf\Facade::class,

 

Generating PDF Files in Laravel

Now that we have installed and configured Dompdf in Laravel, let's look at how to generate PDF files. To generate a PDF file, we first need to create an HTML document that we want to convert to PDF. We can use Laravel's view system to create the HTML document. In this example, we will create a simple invoice template.

Create a new view file called invoice.blade.php in the resources/views directory, and add the following code:

htmlCopy code

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Invoice</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            font-size: 14px;
            margin: 0;
            padding: 0;
        }
        .header {
            background-color: #333;
            color: #fff;
            padding: 10px;
        }
        .content {
            padding: 10px;
        }
        .footer {
            background-color: #333;
            color: #fff;
            padding: 10px;
            text-align: right;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>Invoice</h1>
    </div>
    <div class="content">
        <p>Invoice Number: {{ $invoice->number }}</p>
        <p>Date: {{ $invoice->date }}</p>
        <table>
            <thead>
                <tr>
                    <th>Description</th>
                    <th>Price</th>
                    <th>Quantity</th>
                    <th>Amount</th>
                </tr>
            </thead>
            <tbody>
                @foreach ($invoice->items as $item)
                <tr>
                    <td>{{ $item->description }}</td>
                    <td>{{ $item->price }}</td>
                    <td>{{ $item->quantity }}</td>
                    <td>{{ $item->amount }}</td>
                </tr>
                @endforeach
            </tbody>
        </table>
    </div>
    <div class="footer">
        Total: {{ $invoice->total }}
    </div>
</body>
</html>

 

In this example, we have created a simple HTML invoice template that contains

After creating the invoice template, we need to generate the PDF file using Dompdf. To do this, we can use the PDF facade provided by Dompdf. We need to pass the HTML document as a string to the loadHtml() method of the PDF facade. We can then call the output() method to generate the PDF file.

Open the controller where you want to generate the PDF file and add the following code:

use PDF;

public function generatePDF($id)
{
    // Fetch invoice data from database
    $invoice = Invoice::find($id);

    // Generate PDF file
    $pdf = PDF::loadHtml(view('invoice', compact('invoice'))->render());
    return $pdf->download('invoice.pdf');
}

In this example, we have created a method called generatePDF() that takes an id parameter. We first fetch the invoice data from the database using the find() method. We then create a PDF file using the PDF facade by passing the HTML document to the loadHtml() method. We then call the download() method to download the PDF file with the name "invoice.pdf".

Finally, we need to create a route to access the generatePDF() method. Open the routes/web.php file and add the following route:

Route::get('invoice/{id}/pdf', 'InvoiceController@generatePDF');

In this example, we have created a route that maps to the generatePDF() method of the InvoiceController class. We have also added a parameter {id} to the route, which represents the invoice id.

Now, we can access the PDF file by visiting the URL http://localhost:8000/invoice/{id}/pdf. When we visit this URL, Laravel will generate the PDF file and prompt the user to download the file.

 

Conclusion

In this article, we have looked at how to generate PDF files in Laravel using the Dompdf package. We have installed and configured the Dompdf package, created an HTML invoice template, and generated a PDF file from the HTML template. We have also created a route to access the PDF file. Laravel provides a simple and elegant way to generate PDF files using third-party packages like Dompdf.

Categories : Laravel

Tags : Laravel PDF generation Dompdf Laravel Dompdf Laravel PDF generator

Abhay Dudhatra
Abhay Dudhatra
I am a full-stack developer who is passionate about creating innovative solutions that solve real-world problems. With expertise in technologies such as PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter, and Bootstrap, I love to share my knowledge and help others in the industry through writing tutorials and providing tips. Consistency and hard work are my mantras, and I constantly strive to improve my skills and stay up-to-date with the latest advancements in the field. As the owner of Open Code Solution, I am committed to providing high-quality services to my clients and helping them achieve their business objectives.


26 Comments

buy tricor 160mg without prescription fenofibrate 160mg ca fenofibrate order


order zaditor 1 mg pills order zaditor 1mg without prescription order imipramine 25mg for sale


tadalafil 5mg brand buy sildenafil 100mg online sildenafil 50mg brand


buy minoxidil for sale purchase cialis online men's ed pills


purchase aspirin without prescription cost levoflox 250mg purchase zovirax


meloset price melatonin cost buy danazol no prescription


purchase dydrogesterone sale buy generic dapagliflozin 10 mg order empagliflozin 25mg for sale


buy prasugrel 10 mg pill chlorpromazine tablet detrol 2mg generic


cheap etodolac 600mg buy cilostazol pills pletal 100mg price


buy ferrous pills for sale order generic ascorbic acid 500mg buy betapace 40 mg sale


mestinon usa buy piroxicam generic buy rizatriptan 5mg sale


betahistine 16 mg cost betahistine 16mg oral probalan price


purchase latanoprost eye drop buy xalatan cheap exelon price


prilosec 20mg cost buy prilosec 20mg online cheap order metoprolol 50mg generic


premarin pills canadian viagra and healthcare sildenafil citrate


buy generic telmisartan 20mg molnupiravir medication molnupiravir where to buy


cenforce uk buy naproxen 500mg pill chloroquine uk


cialis 5mg brand tadalafil 20mg drug order viagra 50mg online


cheap cefdinir 300 mg buy glucophage generic buy prevacid online cheap


cheap provigil 100mg buy provigil 200mg online deltasone 40mg brand


brand accutane 20mg zithromax over the counter azithromycin for sale online


buy azithromycin 250mg pill omnacortil 5mg tablet neurontin 800mg price


pantoprazole over the counter order phenazopyridine generic pyridium 200mg pill


best no deposit free spins play live poker online lasix 100mg price


casino games real money casino free spins no deposit albuterol without prescription


amantadine 100 mg drug buy dapsone without a prescription buy generic dapsone


Leave a comment

We'll never share your email with anyone else. Required fields are marked *

Related Articles