vaneetjoshi/laravel-pdf

Pure-PHP, shared-hosting friendly PDF Engine with Devanagari/Sanskrit OTL support for Laravel.

Maintainers

Package info

github.com/vaneetjoshi/laravel-pdf

pkg:composer/vaneetjoshi/laravel-pdf

Transparency log

Statistics

Installs: 4

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v1.0.0 2026-08-04 05:59 UTC

This package is auto-updated.

Last update: 2026-08-04 06:03:38 UTC


README

A fluent, pure-PHP PDF builder for Laravel.

Generating PDFs in PHP is traditionally a frustrating experience involving clunky syntax, massive configuration arrays, and layout limitations. This library changes that. It wraps the powerful mPDF engine in a beautiful, chainable Laravel API, making PDF creation an absolute breeze.

Beyond an incredible Developer Experience (DX), this package introduces a custom Two-Pass Letterhead Engine to solve the most complex layout limitations in modern PDF generation. It seamlessly renders full-page repeating borders, background canvases, and persistent headers/footers without triggering bounding-box collisions or margin collapse. Furthermore, it boasts built-in OTL (OpenType Layout) support to render complex Hindi/Sanskrit ligatures flawlessly.

Because it relies purely on PHP, this package is 100% shared-hosting friendly. No Node.js, Puppeteer, or headless browsers are required.

ЁЯМЯ Why Choose This Library?

  • Incredibly Easy API: Say goodbye to raw mPDF arrays. Use elegant, chainable methods like Pdf::paperSize('A4')->margins(10, 10, 10, 10)->loadView('invoice')->stream().
  • Two-Pass Rendering Engine: Flawless full-page borders and backgrounds alongside headers/footers without crashing the layout matrix.
  • Native Sanskrit / Devanagari (OTL): Built-in OpenType Layout engine support to render complex Indian ligatures perfectly out of the box.
  • Direct Memory Workflows: Generate PDFs and attach them directly to emails or return them as Base64 JSON strings without ever touching the disk.

ЁЯУЛ Server Requirements

  • PHP: ^8.2, ^8.3, ^8.4
  • Laravel: ^11.0, ^12.0, ^13.0
  • Extensions: gd or imagick (for image processing), mbstring.

ЁЯЪА Installation

Install via Composer:

composer require vaneetjoshi/laravel-pdf

Publish the configuration file:

php artisan vendor:publish --tag=pdf-config

тЪая╕П CSS Limitations & Gotchas

Because this package wraps mPDF under the hood, it uses an older, specific HTML/CSS parsing engine. To avoid rendering headaches, please follow these rules:

  1. No Flexbox or CSS Grid: Do not use display: flex; or display: grid;. They will be ignored.
  2. Use Tables for Layouts: For columns and grids (like invoices), rely on classic HTML <table width="100%"> layouts.
  3. Header/Footer Fonts: mPDF detaches headers and footers from the main DOM. CSS classes defined in your <style> tags usually will not apply to headers. If you need a custom font in a header, use inline styles: <div style="font-family: devanagari, sans-serif;">.

ЁЯЦЛ Adding Custom Fonts

You can easily register your own fonts (like Poppins, Roboto, etc.) by placing the .ttf files in your designated font folder and mapping them in the published config/pdf.php file:

/* config/pdf.php */
'custom_font_path' => base_path('resources/fonts/'),
'custom_fonts' => [
    'poppins' => [
        'R'  => 'Poppins-Regular.ttf',    // Regular
        'B'  => 'Poppins-Bold.ttf',       // Bold
        'I'  => 'Poppins-Italic.ttf',     // Italic
        'BI' => 'Poppins-BoldItalic.ttf'  // Bold Italic
    ],
    // Our built-in Devanagari support:
    'devanagari' => [
        'R' => 'devanagari.ttf', 
        'useOTL' => 0xFF, // Required for complex Hindi/Sanskrit ligatures
    ],
],

You can now use font-family: poppins, sans-serif; in your Blade views.

ЁЯТ╗ Real-World Implementation Examples

1. Generating a Tax Invoice (Controller & Blade)

Here is a complete example of generating a professional, bordered invoice.

The Controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Vaneetjoshi\LaravelPdf\Facades\Pdf;

class InvoiceController extends Controller
{
    public function generate(Request $request)
    {
        $headerHtml = '
        <div style="border-bottom: 2px solid #000; padding-bottom: 5px;">
            <strong style="font-size: 20px; color: #1a56db;">TRADE VISION VENTURES</strong>
        </div>';

        $footerHtml = '
        <div style="border-top: 1px solid #000; font-size: 10px; text-align: right;">
            Page {PAGENO} of {nbpg}
        </div>';

        $data = [
            'invoice_no' => 'TVV-2026-0803',
            'date' => now()->format('d-M-Y'),
            'total' => 50000
        ];

        return Pdf::paperSize('A4')
            ->orientation('P')
            ->margins(top: 25, right: 15, bottom: 20, left: 15)
            // Add a sleek corporate border
            ->addEdgeBorder([
                'border_line_color' => '#1a56db',
                'border_line_width' => '2px',
                'border_size_mm'    => 5.0,
                'padding_mm'        => 2.0,
            ])
            ->headerHtml($headerHtml, 15)
            ->footerHtml($footerHtml, 10)             ->loadView('pdf.invoice',$data)
            ->stream('Invoice_' . $data['invoice_no'] . '.pdf');
    }
}

The Blade View (resources/views/pdf/invoice.blade.php):

<!DOCTYPE html>
<html>
<head>
    <style>
        body { font-family: dejavusans, sans-serif; font-size: 12px; }
        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        th, td { border: 1px solid #333; padding: 8px; text-align: left; }
    </style>
</head>
<body>
    <h2 style="text-align: center;">TAX INVOICE</h2>
    <p><strong>Invoice No:</strong> {{ $invoice_no }}</p>
    <p><strong>Date:</strong> {{ $date }}</p>

    <table>
        <tr>
            <th>Description</th>
            <th>Amount</th>
        </tr>
        <tr>
            <td>Software License</td>
            <td>INR {{ number_format($total, 2) }}</td>
        </tr>
    </table>
</body>
</html>

2. Emailing a PDF Directly (Without Saving to Disk)

If you want to generate an invoice and email it to a customer immediately without cluttering your server's storage, use the output() method to get the raw binary data and attach it via Laravel's Mail facade.

use Vaneetjoshi\LaravelPdf\Facades\Pdf;
use Illuminate\Support\Facades\Mail;

public function sendInvoiceEmail($user)
{
    $data = ['name' =>$user->name, 'amount' => 1500];

    // 1. Generate the raw PDF binary string in memory
    $pdfData = Pdf::paperSize('A4')
        ->loadView('pdf.invoice', $data)
        ->output();

    // 2. Attach the raw data directly to the email
    Mail::send('emails.billing', $data, function($message) use ($user,$pdfData) {
        $message->to($user->email)
                ->subject('Your Recent Invoice')
                ->attachData($pdfData, 'Invoice.pdf', [
                    'mime' => 'application/pdf',
                ]);
    });

    return response()->json(['message' => 'Invoice emailed successfully!']);
}

3. Creating Complex Borders & Sanskrit Rendering

Perfect for Astrology Reports, Certificates, or intricate documents.

return Pdf::paperSize('A4')
    ->withSanskrit() // Injects .sanskrit-text CSS and enables OTL
    ->addEdgeBorder([
        'border_bg_color'   => '#ffccbc',
        'border_size_mm'    => 12.0,
        // Draw repeating 'Om' symbols around the entire page edge
        'top' => ['text' => 'реР', 'color' => '#bf360c', 'font_size' => 16, 'with_sanskrit' => true, 'repeat' => true, 'gap' => 12.0],
        'bottom' => ['text' => 'реР', 'color' => '#bf360c', 'font_size' => 16, 'with_sanskrit' => true, 'repeat' => true, 'gap' => 12.0],
        'left' => ['text' => 'реР', 'color' => '#bf360c', 'font_size' => 16, 'with_sanskrit' => true, 'repeat' => true, 'gap' => 12.0],
        'right' => ['text' => 'реР', 'color' => '#bf360c', 'font_size' => 16, 'with_sanskrit' => true, 'repeat' => true, 'gap' => 12.0]
    ])
    ->pageBackground('#fffbf0', '[https://example.com/texture.png](https://example.com/texture.png)', '4', 'center center')
    ->loadHtml('<h1 class="sanskrit-text" style="text-align:center;">реР рдЧрдВ рдЧрдгрдкрддрдпреЗ рдирдордГ</h1>')
    ->stream('Kundli.pdf');

ЁЯЫа API Reference

Initialization & Configuration

  • paperSize(string $size) - Set standard paper sizes (A4, Letter, Legal).
  • orientation(string $orientation) - 'P' (Portrait) or 'L' (Landscape).
  • margins(float $top, float $right, float $bottom, float $left) - Set document body margins.
  • displayMode(string $mode) - Set PDF viewer mode ('fullpage', 'fullwidth', etc).
  • withSanskrit() - Enables Devanagari rendering engine.

Layout & Injection

  • loadView(string $view, array $data) - Load a Laravel Blade view.
  • loadHtml(string $html) - Parse a raw HTML string.
  • addStylesheet(string $path) - Inject an external CSS file.
  • headerHtml(string $html, ?float $offsetY) - Inject HTML into the header. (Use inline font-family for custom header fonts).
  • footerHtml(string $html, ?float $offsetY) - Inject HTML into the footer.
  • showPageNumbers(string $position, string $format) - Quick pagination helper (e.g., 'bottom-right', 'Page {PAGENO} of {nbpg}').

Borders, Backgrounds & Security

  • addEdgeBorder(array $options) - Create absolute full-page repeating borders.
  • pageBackground(?string $color, ?string $imageUrl, string $resizeMode, string $position) - Set page canvas background.
  • watermarkText(string $text, float $alpha, string $font) - Add a diagonal text watermark.
  • watermarkImage(string $path, float $alpha) - Add a background image watermark.
  • protect(string $password, array $permissions) - Restrict printing/copying and encrypt the PDF.

Output Methods

  • stream(?string $filename) - Display the PDF in the browser.
  • download(?string $filename) - Force a file download.
  • saveToDisk(string $disk, string $path) - Save directly to Laravel Storage (e.g., 's3', 'public').
  • base64() - Output as a base64 string.
  • output() - Output as a raw binary string.

ЁЯУЪ PdfBuilder Complete API Reference

All methods belong to the Vaneetjoshi\LaravelPdf\PdfBuilder class and can be chained via the Pdf Facade or pdf() helper function.

1. Instantiation & Core Configuration

__construct()

  • Description: Initializes a new instance of PdfBuilder and automatically loads defaults from config/pdf.php.
  • Parameters: None
  • Returns: PdfBuilder
  • Example:
use Vaneetjoshi\LaravelPdf\PdfBuilder;

$builder = new PdfBuilder();

paperSize()

  • Description: Sets the physical paper dimensions of the document.
  • Signature: paperSize(string $size = 'A4'): self
  • Parameters: | Parameter | Type | Default | Accepted / Valid Values | Description | | --- | --- | --- | --- | --- | | $size | string | 'A4' | 'A0'тАУ'A10', 'B0'тАУ'B10', 'Letter', 'Legal', 'Executive', 'Tabloid' | Standard paper size dimension. |
  • Returns: self (Chainable)
  • Example:
Pdf::paperSize('Legal');

orientation()

  • Description: Configures the page orientation (Portrait or Landscape).
  • Signature: orientation(string $orientation = 'P'): self
  • Parameters: | Parameter | Type | Default | Accepted / Valid Values | Description | | --- | --- | --- | --- | --- | | $orientation | string | 'P' | 'P', 'Portrait', 'L', 'Landscape' | Document orientation mode. |
  • Returns: self (Chainable)
  • Example:
Pdf::orientation('L');

margins()

  • Description: Sets the inner content margins (padding) for the main body in millimeters.
  • Signature: margins(float $top = 15, float $right = 15, float $bottom = 15, float $left = 15): self
  • Parameters: | Parameter | Type | Default | Accepted Values | Description | | --- | --- | --- | --- | --- | | $top | float | 15 | Any positive float (mm) | Distance between top page edge and body content. | | $right | float | 15 | Any positive float (mm) | Distance between right page edge and body content. | | $bottom | float | 15 | Any positive float (mm) | Distance between bottom page edge and body content. | | $left | float | 15 | Any positive float (mm) | Distance between left page edge and body content. |
  • Returns: self (Chainable)
  • Note: When using addEdgeBorder(), body margins automatically auto-expand if the configured border size plus padding exceeds these values.
  • Example:
Pdf::margins(top: 30, right: 10, bottom: 20, left: 10);

displayMode()

  • Description: Dictates how PDF viewing software (e.g., Adobe Acrobat, Chrome PDF Viewer) displays the file upon opening.
  • Signature: displayMode(string $mode): self
  • Parameters: | Parameter | Type | Default | Accepted / Valid Values | Description | | --- | --- | --- | --- | --- | | $mode | string | N/A | 'fullpage', 'fullwidth', 'real', 'default', 'none' | PDF display scaling mode. |
  • Returns: self (Chainable)
  • Example:
Pdf::displayMode('fullwidth');

2. Content & Styling Loaders

loadView()

  • Description: Compiles a Blade template view with data and loads the generated HTML as the document body.
  • Signature: loadView(string $view, array $data = []): self
  • Parameters: | Parameter | Type | Default | Accepted Values | Description | | --- | --- | --- | --- | --- | | $view | string | N/A | Valid Blade view path (e.g. 'pdf.invoice') | Dot-notation blade path. | | $data | array | [] | Key-value associative array | Variables passed into the Blade view. |
  • Returns: self (Chainable)
  • Example:
Pdf::loadView('pdf.invoice', ['invoiceNumber' => 'TVV-2026-001', 'total' => 15000]);

loadHtml()

  • Description: Parses a raw HTML markup string directly into the document body.
  • Signature: loadHtml(string $html): self
  • Parameters: | Parameter | Type | Default | Accepted Values | Description | | --- | --- | --- | --- | --- | | $html | string | N/A | Valid HTML string | Raw string containing HTML markup. |
  • Returns: self (Chainable)
  • Example:
Pdf::loadHtml('<h1>Tax Invoice</h1><p>Thank you for your purchase.</p>');

addStylesheet()

  • Description: Reads a local CSS file from disk and injects its contents into the document <head> CSS context.
  • Signature: addStylesheet(string $path): self
  • Parameters: | Parameter | Type | Default | Accepted Values | Description | | --- | --- | --- | --- | --- | | $path | string | N/A | Absolute server path to .css file | File path (e.g., public_path('css/pdf.css')). |
  • Returns: self (Chainable)
  • Example:
Pdf::addStylesheet(public_path('css/pdf-invoice.css'));

withSanskrit()

  • Description: Activates the OpenType Layout (OTL) engine for Devanagari script processing and injects CSS classes for rendering Sanskrit ligatures correctly.
  • Signature: withSanskrit(): self
  • Parameters: None
  • Returns: self (Chainable)
  • Example:
Pdf::withSanskrit()->loadHtml('<p class="sanskrit-text">реР рдЧрдВ рдЧрдгрдкрддрдпреЗ рдирдордГ</p>');

3. Headers, Footers & Pagination

headerHtml()

  • Description: Binds custom HTML to the persistent top page header region (<htmlpageheader>).
  • Signature: headerHtml(string $html, ?float $offsetY = null, ?float $offsetX = null): self
  • Parameters: | Parameter | Type | Default | Accepted Values | Description | | --- | --- | --- | --- | --- | | $html | string | N/A | Valid HTML string | Header markup. Use inline font-family styles for non-default fonts. | | $offsetY | float|null | null | Positive float (mm) | Distance of header from top edge. | | $offsetX | float|null | null | Positive float (mm) | Left & right padding offset in mm. |
  • Returns: self (Chainable)
  • Example:
$header = '<div style="font-family: devanagari, sans-serif; color: red;">реР рдирдордГ рд╢рд┐рд╡рд╛рдп</div>';
Pdf::headerHtml($header, offsetY: 15, offsetX: 10);

footerHtml()

  • Description: Binds custom HTML to the persistent bottom page footer region (<htmlpagefooter>).
  • Signature: footerHtml(string $html, ?float $offsetY = null, ?float $offsetX = null): self
  • Parameters: | Parameter | Type | Default | Accepted Values | Description | | --- | --- | --- | --- | --- | | $html | string | N/A | Valid HTML string | Footer markup. | | $offsetY | float|null | null | Positive float (mm) | Distance of footer from bottom edge. | | $offsetX | float|null | null | Positive float (mm) | Left & right padding offset in mm. |
  • Returns: self (Chainable)
  • Example:
Pdf::footerHtml('<div style="text-align: center;">Company Registration No. 03AAAAA0000A1Z5</div>', offsetY: 10);

showPageNumbers()

  • Description: Automatically injects formatted pagination text into the header or footer.
  • Signature: showPageNumbers(string $position = 'bottom-right', string $format = 'Page {PAGENO} of {nbpg}'): self
  • Parameters: | Parameter | Type | Default | Accepted Values | Description | | --- | --- | --- | --- | --- | | $position | string | 'bottom-right' | 'bottom-right', 'bottom-left', 'bottom-center', 'top-right', 'top-left', 'top-center' | Screen placement for the pagination string. | | $format | string | 'Page {PAGENO} of {nbpg}' | String containing {PAGENO} and {nbpg} | Formatting string. {PAGENO} = Current Page, {nbpg} = Total Pages. |
  • Returns: self (Chainable)
  • Example:
Pdf::showPageNumbers('bottom-center', 'Page {PAGENO} / {nbpg}');

4. Two-Pass Backgrounds & Borders Engine

addEdgeBorder()

  • Description: Triggers the Pass 1 Canvas Engine to draw repeating or solid full-bleed borders around every page edge without colliding with main body margins.
  • Signature: addEdgeBorder(array $options = []): self
  • Parameters: | Parameter | Type | Default | Accepted Options / Structure | Description | | --- | --- | --- | --- | --- | | $options | array | [] | See structure array below | Multi-edge layout configuration array. |
  • Options Array Structure:
[
    'border_bg_color'   => '#ffffff', // (string|null) Outer track hex color
    'border_line_color' => '#000000', // (string) Inner framing line hex color
    'border_line_width' => '1px',     // (string) CSS line thickness ('0' for none)
    'border_size_mm'    => 12.0,     // (float) Total border thickness in mm
    'padding_mm'        => 2.0,      // (float) Distance between line and track in mm
    'inner_margin_mm'   => 5.0,      // (float) Safe margin between line and body text

    // Edge Sections: 'top', 'bottom', 'left', 'right'
    'top' => [
        'text'          => 'реР',      // (string) Text string or character to render
        'image'         => '',       // (string) URL or path to image
        'align'         => 'center', // (string) 'left', 'center', 'right'
        'color'         => '#000000',// (string) Text hex color
        'font_size'     => 12,       // (int) Font size in px
        'with_sanskrit' => true,     // (bool) Enable Devanagari font for this edge
        'repeat'        => true,     // (bool) Repeat text/symbol across the edge length
        'gap'           => 10.0      // (float) Spacing between repeated items in mm
    ]
]
  • Returns: self (Chainable)
  • Example:
Pdf::addEdgeBorder([
    'border_bg_color'   => '#ea5151eb',
    'border_line_color' => '#000000',
    'border_line_width' => '1.5px',
    'border_size_mm'    => 12.0,
    'top' => ['text' => 'реР', 'color' => '#ffffff', 'font_size' => 16, 'with_sanskrit' => true, 'repeat' => true, 'gap' => 15.0]
]);

pageBackground()

  • Description: Paints a uniform background color or repeating texture image across the Pass 1 background canvas.
  • Signature: pageBackground(?string $color = null, ?string $imageUrl = null, string $resizeMode = '4', string $position = 'center center'): self
  • Parameters: | Parameter | Type | Default | Accepted Values | Description | | --- | --- | --- | --- | --- | | $color | string|null | null | Hex color string (e.g., '#fffbf0') | Background fill color. | | $imageUrl | string|null | null | URL or server path to image file | Background pattern or texture URL. | | $resizeMode | string | '4' | '0' (no resize), '1' (fit), '2' (fill), '4' (scale page) | Scaling factor for background image. | | $position | string | 'center center' | Standard CSS background-position | Background image alignment. |
  • Returns: self (Chainable)
  • Example:
Pdf::pageBackground(color: '#fffbf0', imageUrl: '[https://example.com/paper-texture.png](https://example.com/paper-texture.png)');

5. Security & Watermarking

watermarkText()

  • Description: Renders a diagonal semi-transparent text watermark across the center of every page.
  • Signature: watermarkText(string $text, float $alpha = 0.2, string $font = 'dejavusans'): self
  • Parameters: | Parameter | Type | Default | Accepted Values | Description | | --- | --- | --- | --- | --- | | $text | string | N/A | Any text string | Watermark text string (e.g. 'CONFIDENTIAL'). | | $alpha | float | 0.2 | 0.0 (invisible) to 1.0 (opaque) | Transparency level. | | $font | string | 'dejavusans' | Valid font family registered in config | Font family for watermark. |
  • Returns: self (Chainable)
  • Example:
Pdf::watermarkText('CONFIDENTIAL DRAFT', 0.15);

watermarkImage()

  • Description: Renders a semi-transparent image watermark across every page.
  • Signature: watermarkImage(string $path, float $alpha = 0.2, string|array $size = 'D', string|array $position = 'P'): self
  • Parameters: | Parameter | Type | Default | Accepted Values | Description | | --- | --- | --- | --- | --- | | $path | string | N/A | URL or absolute local file path | Path to logo or mark. | | $alpha | float | 0.2 | 0.0 to 1.0 | Transparency level. | | $size | string|array | 'D' | 'D' (default), 'P' (proportional), 'F' (fit), or [w, h] | Sizing algorithm. | | $position | string|array | 'P' | 'P' (center) or [x, y] coordinate array | Screen positioning. |
  • Returns: self (Chainable)
  • Example:
Pdf::watermarkImage(public_path('images/watermark-logo.png'), 0.1);

protect()

  • Description: Encrypts the PDF file with 128-bit encryption and limits user permissions.
  • Signature: protect(string $password, array $permissions = ['print', 'copy']): self
  • Parameters: | Parameter | Type | Default | Accepted Values | Description | | --- | --- | --- | --- | --- | | $password | string | N/A | Any non-empty string | Encryption password. | | $permissions | array | ['print', 'copy'] | Array containing: 'print', 'modify', 'copy', 'annot-forms', 'fill-forms', 'extract', 'assemble', 'print-highres' | Allowed user permissions. |
  • Returns: self (Chainable)
  • Example:
Pdf::protect('secret_password_123', ['print']); // Permits printing, blocks copying

6. Output Generators

stream()

  • Description: Compiles the document and sends HTTP headers to stream the PDF directly inline in the browser.
  • Signature: stream(?string $filename = null): mixed
  • Parameters: | Parameter | Type | Default | Accepted Values | Description | | --- | --- | --- | --- | --- | | $filename | string|null | null | Filename ending in .pdf | Name shown in browser tab. Defaults to 'document.pdf'. |
  • Returns: \Symfony\Component\HttpFoundation\Response
  • Example:
return Pdf::loadView('pdf.invoice')->stream('Tax_Invoice.pdf');

download()

  • Description: Compiles the document and forces the user's browser to download the file.
  • Signature: download(?string $filename = null): mixed
  • Parameters: | Parameter | Type | Default | Accepted Values | Description | | --- | --- | --- | --- | --- | | $filename | string|null | null | Filename ending in .pdf | Download file name. Defaults to 'document.pdf'. |
  • Returns: \Symfony\Component\HttpFoundation\Response
  • Example:
return Pdf::loadView('pdf.invoice')->download('Tax_Invoice.pdf');

saveToDisk()

  • Description: Compiles the document and saves the raw binary file directly to a configured Laravel filesystem disk.
  • Signature: saveToDisk(string $disk = 'public', string $path = 'documents/doc.pdf'): bool
  • Parameters: | Parameter | Type | Default | Accepted Values | Description | | --- | --- | --- | --- | --- | | $disk | string | 'public' | Valid disk name defined in config/filesystems.php (e.g. 's3', 'local') | Target Laravel Storage disk. | | $path | string | 'documents/doc.pdf' | Destination file path | Target folder and file name. |
  • Returns: bool (true on successful write, false on failure)
  • Example:
$success = Pdf::loadView('pdf.invoice')->saveToDisk('s3', 'invoices/2026/INV-001.pdf');

base64()

  • Description: Compiles the document in memory and returns a Base64-encoded string representation. Ideal for API payloads.
  • Signature: base64(): string
  • Parameters: None
  • Returns: string (Base64 string)
  • Example:
$base64String = Pdf::loadView('pdf.invoice')->base64();

return response()->json([
    'status' => 'success',
    'pdf_base64' => $base64String
]);

output()

  • Description: Compiles the document in memory and returns the raw binary PDF stream. Ideal for emailing attachments directly via Mail::attachData().
  • Signature: output(): string
  • Parameters: None
  • Returns: string (Raw PDF binary stream)
  • Example:
$pdfBinary = Pdf::loadView('pdf.invoice')->output();

Mail::send('emails.invoice', $data, function ($message) use ($pdfBinary) {$message->to('client@example.com')
            ->subject('Your Invoice')
            ->attachData($pdfBinary, 'Invoice.pdf', ['mime' => 'application/pdf']);
});