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.


163 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


best casino online casinos ivermectin over the counter canada


buy medrol 4 mg online cheap aristocort 10mg triamcinolone 10mg canada


doubleu casino online casino quick hits free online slots order levoxyl for sale


clomid without prescription order imuran 25mg pills azathioprine 50mg us


aceon for sale buy clarinex 5mg generic how to get allegra without a prescription


vardenafil 10mg pill generic zanaflex zanaflex oral


where can i buy claritin buy ramipril 5mg pills buy dapoxetine 30mg


buy phenytoin buy phenytoin 100 mg pill order oxytrol pill


generic baclofen 10mg buy endep 10mg pill cheap ketorolac


buy amaryl 1mg pill order glimepiride 4mg online order arcoxia sale


lioresal without prescription cost amitriptyline 10mg toradol tablet


generic fosamax 35mg generic fosamax brand macrodantin 100mg


propranolol generic buy inderal pill plavix 75mg cost


pamelor 25 mg oral buy methotrexate 2.5mg generic purchase anacin sale


orlistat 120mg cost order asacol pills buy diltiazem 180mg pill


warfarin 2mg tablet paroxetine 10mg pills buy reglan pill


astelin generic avapro 150mg tablet buy generic avalide online


pepcid online pepcid uk buy tacrolimus no prescription


buy generic nexium online remeron 30mg over the counter cost topiramate 200mg


zyloprim 300mg oral allopurinol 100mg cheap order generic crestor 10mg


imitrex 25mg pill buy sumatriptan 50mg generic buy cheap generic avodart


buspar 10mg for sale buy buspar no prescription order cordarone 100mg pill


order generic zantac 150mg order generic celecoxib 200mg buy celebrex 200mg pill


flomax order online buy ondansetron cheap buy zocor online cheap


assignment company edit letter paper writing websites


buy spironolactone 100mg pills buy generic valacyclovir brand finasteride


aurogra without prescription cost sildenafil 100mg estrace 1mg uk


order generic forcan purchase diflucan for sale purchase ciprofloxacin pill


buy generic lamotrigine 200mg lamictal pills vermox 100mg drug


flagyl for sale brand flagyl 200mg keflex 125mg over the counter


buy generic retin for sale order retin avana 200mg brand


buy cleocin medication buy cleocin sale best ed drug


buy tadacip 20mg pills purchase tadacip pill order indocin 75mg


order tamoxifen 10mg generic nolvadex tablet buy rhinocort sale


lamisil online terbinafine over the counter free slot play


ceftin 250mg pill order generic ceftin 250mg robaxin usa


buy desyrel 100mg purchase trazodone pill purchase clindac a online cheap


essay writing assistance help writing thesis suprax 100mg over the counter


order aspirin 75mg for sale buy generic aspirin over the counter blackjack online


amoxicillin uk order anastrozole online cheap biaxin online buy


do my research paper best casino slots online free casino slots


buy catapres 0.1 mg online cheap clonidine 0.1mg over the counter spiriva 9 mcg us


calcitriol 0.25mg canada cost fenofibrate buy generic tricor online


minocin 50mg cost hytrin 1mg brand buy requip 2mg pills


how do dermatologists treat acne order oxcarbazepine 300mg online buy trileptal online


order uroxatral 10mg online cheap best allergy medications over the counter natural ways to get rid of acid reflux


femara 2.5 mg sale purchase femara online cheap buy abilify 30mg pills


best online rx for sleep mexican diet pills that work get weight loss medication online


buy provera tablets buy cheap generic praziquantel oral hydrochlorothiazide


antidepressant medication to quit smoking arthritis pill medication uk list of standaredc painkillers


brand cyproheptadine 4 mg order nizoral 200mg pills ketoconazole 200mg ca


antiviral drug definition can you buy inhalers over the counter diagnosed with type 2 diabetes


order duloxetine 20mg pills buy glucotrol 10mg pill buy modafinil 200mg without prescription


will lamisil kill toenail fungus buy antifungal pills online stopped taking blood pressure medication


purchase phenergan without prescription purchase phenergan pill buy stromectol pills


duodenitis without bleeding vasodilators for heart failure nursing uti treatment guidelines for elderly


buy deltasone 40mg without prescription order amoxicillin 1000mg pill amoxil 250mg pills


free emergency contraception pharmacy online prescription birth control lasting longer in bed naturally


azithromycin 500mg tablet gabapentin tablet generic gabapentin


best supplement for heartburn farts that smell like food anti gas pills for bloating


ursodiol canada purchase zyrtec sale how to get zyrtec without a prescription


buy furosemide 100mg sale buy furosemide generic albuterol canada


strattera tablet order strattera 25mg buy zoloft generic


augmentin buy online cheap levoxyl generic clomid 100mg cost


buy escitalopram 20mg generic brand prozac 20mg buy naltrexone 50mg generic


order ipratropium online cheap zyvox 600mg sale purchase linezolid generic


buy generic levitra 10mg buy vardenafil 10mg online cheap plaquenil 200mg us


nateglinide 120 mg us buy captopril 25mg pills buy candesartan tablets


cenforce usa buy chloroquine without prescription glucophage where to buy


buy tegretol generic buy lincocin for sale lincomycin us


lipitor 40mg pill buy generic amlodipine zestril 5mg ca


order duricef 500mg online cheap ascorbic acid for sale buy generic combivir


prilosec tablet buy atenolol 50mg online order atenolol 50mg online cheap


dostinex price dostinex 0.5mg usa brand priligy 60mg


oral medrol aristocort for sale online purchase desloratadine for sale


purchase misoprostol sale buy diltiazem 180mg online diltiazem online buy


order nootropil 800 mg betnovate 20gm oral anafranil 50mg sale


buy zovirax no prescription crestor 10mg oral order crestor generic


sporanox us prometrium order online tinidazole 300mg oral


order zetia buy motilium online sumycin cost


order flexeril 15mg pills toradol 10mg canada ketorolac us


colchicine pill inderal 10mg oral buy methotrexate 2.5mg online


oral medication for severe acne isotretinoin 10mg uk acne medication pills names


best allergy pill cheap promethazine alternatives to allergy medication


prescription drug for stomach cramps order generic lincomycin 500mg



purchase deltasone without prescription order prednisone 20mg


common heartburn medication prescription accupril 10mg usa


most common medication prescribed acne order omnacortil 5mg online list of prescription acne creams


best medication for gerd symptoms accupril 10mg uk


brand accutane 10mg accutane over the counter accutane without prescription


online doctors that prescribe ambien buy cheap provigil


order amoxicillin 500mg generic order generic amoxicillin 1000mg buy generic amoxil online


how to buy zithromax order zithromax 500mg sale zithromax 250mg sale


neurontin over the counter neurontin ca


order azipro 500mg pills buy azipro 500mg pill azithromycin where to buy


furosemide uk order lasix 100mg


order prednisolone online cheap order omnacortil 5mg online cheap order prednisolone 40mg without prescription



purchase amoxicillin amoxicillin order order amoxicillin for sale


vibra-tabs online order buy doxycycline 100mg online


purchase albuterol sale purchase albuterol inhalator without prescription albuterol us


buy augmentin 1000mg sale buy augmentin 375mg online cheap


levothroid for sale generic levothyroxine order levoxyl online cheap


buy vardenafil 10mg for sale vardenafil us


serophene canada clomid 50mg without prescription clomid 100mg pills


order rybelsus 14 mg online cheap semaglutide 14 mg for sale semaglutide 14mg usa


buy generic deltasone 10mg order prednisone sale deltasone uk


order semaglutide 14mg generic oral rybelsus 14 mg buy rybelsus pill


buy absorica pill buy accutane 20mg pills order isotretinoin 10mg online cheap


purchase albuterol pills order albuterol pill buy ventolin inhalator online cheap


order amoxicillin generic buy amoxil purchase amoxil generic


augmentin 625mg ca buy generic amoxiclav clavulanate without prescription


azithromycin 250mg usa purchase azithromycin without prescription brand zithromax 250mg


cheap levothroid pills generic levoxyl synthroid 150mcg price


order generic vardenafil 10mg levitra usa purchase levitra sale


online blackjack with friends online slots real money usa online casino


cost plaquenil 200mg plaquenil cost buy plaquenil sale


lyrica 150mg generic lyrica 150mg us pregabalin 75mg brand


cialis india cialis canada order tadalafil 20mg online


buy aristocort 4mg sale purchase aristocort generic buy triamcinolone generic


buy generic desloratadine how to buy desloratadine order clarinex 5mg for sale


order cenforce 50mg without prescription buy cenforce sale cenforce pills


cialis and pharmacy canadian pharmacy viagra www.northwestpharmacy.com canada rx pharmacy


chloroquine ca chloroquine cheap aralen price


generic loratadine 10mg buy claritin 10mg online cheap buy loratadine 10mg


buy xenical 120mg online order orlistat without prescription purchase diltiazem without prescription


buy lipitor purchase atorvastatin pills buy atorvastatin 10mg generic


buy amlodipine 5mg sale order norvasc online norvasc 10mg generic


order zovirax pill oral acyclovir 400mg allopurinol 300mg over the counter


order zestril 2.5mg pills buy zestril 5mg cost zestril 2.5mg


canadian pharmacy store canadian rx pharmacy indian pharma Canadian Pharcharmy Online


crestor 10mg drug buy rosuvastatin no prescription buy zetia without a prescription


generic omeprazole cost prilosec buy omeprazole no prescription


cheap motilium 10mg domperidone 10mg cost sumycin 500mg cheap


metoprolol 50mg pill order metoprolol generic lopressor 100mg pill


generic cyclobenzaprine buy flexeril 15mg generic where to buy baclofen without a prescription


Leave a comment

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

Related Articles