Skip to main content

How to Generate a PDF File in Laravel Using DomPDF

How to Generate a PDF File in Laravel Using DomPDF

Generating PDF files is a common requirement in modern web applications. Whether you need invoices, reports, or downloadable documents, Laravel makes this task simple with the help of the DomPDF library. In this tutorial, we will walk through the complete process of generating a PDF file in Laravel using DomPDF.

What is DomPDF?

DomPDF is a PHP library that converts HTML and CSS into PDF documents. It is lightweight, easy to use, and integrates seamlessly with Laravel. By writing standard HTML and CSS, you can quickly create professional-looking PDFs.

Step 1: Install DomPDF in Laravel

The easiest way to install DomPDF in Laravel is via Composer. Run the following command in your project directory:

composer require barryvdh/laravel-dompdf

Laravel will automatically register the package thanks to package auto-discovery.

Step 2: Create a Route

Next, define a route that will trigger the PDF generation. Open the routes/web.php file and add the following code:


use App\Http\Controllers\PDFController;

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

Step 3: Create a Controller

Now, create a controller to handle the PDF logic:

php artisan make:controller PDFController

Open the generated controller and add the following method:


namespace App\Http\Controllers;

use Illuminate\Http\Request;
use PDF;

class PDFController extends Controller
{
    public function generatePDF()
    {
        $data = [
            'title' => 'Welcome to Laravel PDF',
            'date' => date('m/d/Y')
        ];

        $pdf = PDF::loadView('pdf.sample', $data);
        return $pdf->download('sample.pdf');
    }
}
    

Step 4: Create a Blade View for the PDF

Create a new Blade file at resources/views/pdf/sample.blade.php. This view will contain the HTML structure of your PDF.


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Sample PDF</title>
    <style>
        body {
            font-family: DejaVu Sans, sans-serif;
        }
    </style>
</head>
<body>
    <h1>{{ $title }}</h1>
    <p>Date: {{ $date }}</p>
    <p>
        This PDF was generated using Laravel and DomPDF.
    </p>
</body>
</html>

Step 5: Download or Stream the PDF

DomPDF provides multiple options for handling PDFs:

  • Download: $pdf->download('file.pdf');
  • Stream in Browser: $pdf->stream('file.pdf');

Common Tips and Best Practices

  • Use simple CSS for better rendering results.
  • Avoid heavy JavaScript, as DomPDF does not support it.
  • Use embedded fonts like DejaVu Sans for UTF-8 support.
  • Test your HTML layout in the browser before converting to PDF.

Conclusion

Generating PDF files in Laravel using DomPDF is straightforward and powerful. With just a few steps, you can convert your HTML views into downloadable or viewable PDF documents. This approach is ideal for invoices, reports, certificates, and more.

If you found this tutorial helpful, feel free to share it with other Laravel developers. Happy coding!

Comments

Popular posts from this blog

How to Use L5-Swagger for API Documentation in Laravel

Integrating Swagger in Laravel: Annotations, JSON, and YAML What is Swagger? Swagger (OpenAPI) is a powerful tool for generating interactive API documentation. It helps developers understand and test your API easily. ✅ Step-by-Step Guide to Setup L5-Swagger 1. Install L5-Swagger Package composer require "darkaonline/l5-swagger" 2. Publish Config & View Files This command publishes the config file to config/l5-swagger.php : php artisan vendor:publish --provider "L5Swagger\L5SwaggerServiceProvider" 3. Configure Swagger (Optional) Edit the file config/l5-swagger.php to update: API Title Base Path Directories to scan for annotations 4. Add Swagger Annotations Add these before your controller class: /** * @OA\Info( * version="1.0.0", * title="Your API Title", * description=...

How to Send Emails in Node.js using Nodemailer and Ethereal

How to Send Email in Node.js using Nodemailer Email functionality is essential in modern web applications. Whether you're sending confirmation emails, password resets, or notifications, Node.js with Nodemailer makes this simple. In this blog, we'll walk through setting up email sending using Node.js , Express , and Ethereal Email for testing. ๐Ÿงพ Prerequisites Node.js installed Basic knowledge of Express.js Internet connection ๐Ÿ“ Project Structure project-folder/ ├── index.js ├── .env ├── package.json └── app/ └── controller/ └── emailSendController.js ๐Ÿ“ฆ Step 1: Install Dependencies npm init -y npm install express nodemailer dotenv npm install --save-dev nodemon ๐Ÿ” Configure nodemon (Optional but Recommended) Update your package.json with a custom start script: "scripts": { "start": "nodemon index.js" } ๐Ÿ” Step 2: Create a .env File Create a .env file a...

Realtime Device Tracker using Node.js, Socket.IO & Leaflet

Realtime Device Tracker using Node.js, Socket.IO & Leaflet In this tutorial, you’ll learn how to build a realtime location tracking application that uses the browser’s GPS, Socket.IO for live communication, and Leaflet.js to display users on a map. ๐Ÿš€ Project Overview Backend: Node.js, Express.js, Socket.IO Frontend: HTML, Leaflet.js, Socket.IO client Features: Live GPS tracking, multi-user map, disconnect cleanup ๐Ÿ“ Folder Structure project-root/ ├── app.js ├── package.json ├── src/ │ ├── public/ │ │ ├── css/ │ │ │ └── style.css │ │ └── js/ │ │ └── script.js │ ├── routes/ │ │ └── routers.js │ ├── socket/ │ │ └── socketHandler.js │ └── views/ │ └── index.ejs ๐Ÿง  How It Works Each user shares their location using the browser's navigator.geolocation API. Location is sent to the server via Socket.IO . The server broadcasts each user’s position to all clien...