Sling Academy
Home/PHP/How to return a PDF file in Laravel

How to return a PDF file in Laravel

Last updated: January 16, 2024

Introduction

Generating and returning PDF files in a web application is a common requirement. Laravel, being a robust PHP framework, provides seamless ways to create and deliver PDFs. In this tutorial, we’ll go through different methods of generating and returning PDF files in a Laravel application, complete with code examples and explanations.

Setting Up the Environment

Before diving into PDF generation, ensure that you have a Laravel project up and running. You will also need to install a package that allows you to work with PDFs; a popular choice is barryvdh/laravel-dompdf. To install it, run the following command:

composer require barryvdh/laravel-dompdf

After the installation, register the provider in config/app.php:

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

Basic PDF Generation

Let’s begin by generating a simple PDF. You can create a route and a corresponding controller method like this:

Route::get('/pdf', '[email protected]');

In your controller:

use PDF;

class PdfController extends Controller
{
    public function show()
    {
        $pdf = PDF::loadView('pdfs.simple');
        return $pdf->download('simple.pdf');
    }
}

Create a view file resources/views/pdfs/simple.blade.php containing HTML, which will be converted to a PDF:

<h1>Hello, World!</h1>

Advanced PDF Customization

In real-world applications, you may want to customize your PDF with dynamic data, headers, footers, or even CSS styling. Let’s explore how you can achieve that.

Passing Data to PDF

Pass an array of data to the view:

$data = ['message' => 'Hello World'];
$pdf = PDF::loadView('pdfs.custom', $data);
return $pdf->download('custom.pdf');

In your view pdfs/custom.blade.php, you can then display this data:

≤h1>{{ $message }}</h1>

Styling Your PDF

Laravel DomPDF package allows you to style your PDF using CSS:

<style>
    body {
        font-family: 'DejaVu Sans', sans-serif;
    }
    h1 {
        color: #4A90E2;
    }
</style>
<h1>{{ $message }}</h1>

Handling Large PDFs

If you’re dealing with large documents, you may need to stream the PDF to the user instead of forcing a download:

return $pdf->stream('large.pdf');

This serves the PDF inline, so it can be viewed within the browser.

Using Middleware

For more control, such as requiring user authentication before accessing a PDF, you can use Laravel middleware. Here’s how:

Route::get('/protected-pdf', '[email protected]')->middleware('auth');

This ensures that only authenticated users can access this route.

Saving PDFs on the Server

Sometimes, you might want to save the PDF to your server:

$pdf->save(storage_path('app/public/pdf_name.pdf'));
return response()->download(storage_path('app/public/pdf_name.pdf'));

This will save the PDF in the storage and then return it to the user.

Securing Your PDFs

You can also secure your PDFs with passwords and permissions:

$pdf = PDF::loadView('myPdfView');
$pdf->setEncryption('password');
return $pdf->download('secured.pdf');

This will encrypt the PDF with the specified password.

Testing PDF Generation

To make sure your PDF generation is flawless, you must write tests. You can use Laravel’s built-in testing functionality to make a request and assert that the response is a PDF:

$this->get('/pdf')->assertStatus(200)->assertHeader('Content-Type', 'application/pdf');

Conclusion

This tutorial covered the basics and more advanced options for generating and returning PDF files with Laravel. By adding a package like barryvdh/laravel-dompdf, you enhanced Laravel’s ability to generate custom PDF files that meet the needs of your application, which can lead to better data presentation and documentation for your users.

Next Article: Laravel error: CSS & JS files not loading in production (7 solutions)

Previous Article: Laravel error: SSL operation failed with code 1 (3 solutions)

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array