Convert Figma logo to code with AI

barryvdh logolaravel-snappy

Laravel Snappy PDF

2,629
290
2,629
48

Top Related Projects

Convert HTML to an image, PDF or string

Convert HTML to PDF using Webkit (QtWebKit)

Quick Overview

The barryvdh/laravel-snappy package is a Laravel wrapper for the popular wkhtmltopdf library, which allows you to generate PDF files from HTML content. This package simplifies the process of working with PDF generation in Laravel applications.

Pros

  • Seamless Integration with Laravel: The package is designed to work seamlessly with the Laravel framework, making it easy to integrate into existing projects.
  • Flexible Configuration: The package offers a wide range of configuration options, allowing you to customize the PDF generation process to suit your specific needs.
  • Reliable PDF Generation: The package utilizes the wkhtmltopdf library, which is known for its reliability and high-quality PDF output.
  • Asynchronous Processing: The package supports asynchronous PDF generation, which can be useful for long-running PDF generation tasks.

Cons

  • Dependency on wkhtmltopdf: The package relies on the wkhtmltopdf library, which can be challenging to install and configure on some platforms.
  • Limited Customization: While the package offers a good amount of configuration options, some users may find that they need more advanced customization options.
  • Potential Performance Issues: Depending on the complexity of the HTML content and the size of the PDF, the PDF generation process can be resource-intensive and may impact the performance of your application.
  • Lack of Active Maintenance: The package has not been actively maintained for a while, which may be a concern for some users.

Code Examples

Here are a few examples of how to use the barryvdh/laravel-snappy package:

  1. Generating a PDF from a view:
use Barryvdh\Snappy\Facades\SnappyPdf;

Route::get('/pdf', function () {
    $pdf = SnappyPdf::loadView('pdf.document', ['data' => $data]);
    return $pdf->inline('document.pdf');
});
  1. Generating a PDF from a URL:
use Barryvdh\Snappy\Facades\SnappyPdf;

Route::get('/pdf', function () {
    $pdf = SnappyPdf::loadFromUrl('https://example.com/document');
    return $pdf->download('document.pdf');
});
  1. Generating a PDF with custom options:
use Barryvdh\Snappy\Facades\SnappyPdf;

Route::get('/pdf', function () {
    $pdf = SnappyPdf::loadView('pdf.document', ['data' => $data])
        ->setOption('page-size', 'Letter')
        ->setOption('margin-top', 10)
        ->setOption('margin-bottom', 10)
        ->setOption('margin-left', 10)
        ->setOption('margin-right', 10);

    return $pdf->stream('document.pdf');
});
  1. Generating a PDF asynchronously:
use Barryvdh\Snappy\Facades\SnappyPdf;

Route::get('/pdf', function () {
    $pdf = SnappyPdf::loadView('pdf.document', ['data' => $data]);
    $pdf->generateAsync('document.pdf');
    return response()->json(['message' => 'PDF generation in progress']);
});

Getting Started

To get started with the barryvdh/laravel-snappy package, follow these steps:

  1. Install the package using Composer:
composer require barryvdh/laravel-snappy
  1. Publish the package configuration file:
php artisan vendor:publish --provider="Barryvdh\Snappy\ServiceProvider"
  1. Configure the package by editing the config/snappy.php file. You'll need to specify the paths to the wkhtmltopdf and wkhtmltoimage binaries.

  2. Use the package in your Laravel application by importing the SnappyPdf facade and generating PDFs as shown in the code examples above.

Competitor Comparisons

Convert HTML to an image, PDF or string

Pros of Browsershot

  • Uses Puppeteer, allowing for more advanced browser automation and JavaScript rendering
  • Supports capturing full-page screenshots and generating PDFs from JavaScript-heavy pages
  • Offers a wider range of customization options for screenshots and PDFs

Cons of Browsershot

  • Requires Node.js and npm to be installed on the server
  • May have a higher resource usage due to running a headless Chrome instance
  • Potentially slower for simple HTML-to-PDF conversions compared to wkhtmltopdf

Code Comparison

Browsershot:

use Spatie\Browsershot\Browsershot;

Browsershot::url('https://example.com')
    ->fullPage()
    ->save('example.pdf');

Laravel Snappy:

use Barryvdh\Snappy\Facades\SnappyPdf;

SnappyPdf::loadView('pdf.example')
    ->setPaper('a4')
    ->save('example.pdf');

Summary

Browsershot offers more advanced features and better support for JavaScript-heavy pages, but requires additional server dependencies. Laravel Snappy is simpler to set up and may be faster for basic PDF generation, but has limited support for complex web pages. Choose based on your specific project requirements and server environment.

Convert HTML to PDF using Webkit (QtWebKit)

Pros of wkhtmltopdf

  • Standalone command-line tool, not tied to any specific framework
  • More flexible and can be used in various environments
  • Actively maintained with regular updates and bug fixes

Cons of wkhtmltopdf

  • Requires manual installation and configuration
  • Less integrated with Laravel ecosystem
  • May require more code to implement in Laravel projects

Code Comparison

wkhtmltopdf (command-line usage):

wkhtmltopdf http://example.com output.pdf

laravel-snappy (Laravel integration):

use Barryvdh\Snappy\Facades\SnappyPdf;

$pdf = SnappyPdf::loadView('pdf.invoice', $data);
return $pdf->download('invoice.pdf');

Summary

wkhtmltopdf is a versatile, standalone tool for converting HTML to PDF, while laravel-snappy is a Laravel-specific wrapper for wkhtmltopdf. The former offers more flexibility across different environments, but requires manual setup. laravel-snappy provides seamless integration with Laravel, making it easier to use within the framework but limiting its use outside of Laravel projects. Choose based on your specific project requirements and development environment.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Snappy PDF/Image Wrapper for Laravel

Tests Packagist License Latest Stable Version Total Downloads Fruitcake

This package is a ServiceProvider for Snappy: https://github.com/KnpLabs/snappy.

Wkhtmltopdf Installation

Choose one of the following options to install wkhtmltopdf/wkhtmltoimage.

  1. Download wkhtmltopdf from here;
  2. Or install as a composer dependency. See wkhtmltopdf binary as composer dependencies for more information.

Attention! Please note that some dependencies (libXrender for example) may not be present on your system and may require manual installation.

Testing the wkhtmltopdf installation

After installing you should be able to run wkhtmltopdf from the command line / shell.

If you went for the second option the binaries will be at /vendor/h4cc/wkhtmltoimage-amd64/bin and /vendor/h4cc/wkhtmltopdf-amd64/bin.

Attention vagrant users!

Move the binaries to a path that is not in a synced folder, for example:

cp vendor/h4cc/wkhtmltoimage-amd64/bin/wkhtmltoimage-amd64 /usr/local/bin/
cp vendor/h4cc/wkhtmltopdf-amd64/bin/wkhtmltopdf-amd64 /usr/local/bin/

and make it executable:

chmod +x /usr/local/bin/wkhtmltoimage-amd64 
chmod +x /usr/local/bin/wkhtmltopdf-amd64

This will prevent the error 126.

Package Installation

Require this package in your composer.json and update composer.

composer require barryvdh/laravel-snappy

Laravel

Laravel 5.5 uses Package Auto-Discovery, so doesn't require you to manually add the ServiceProvider/Facade. If you also use laravel-dompdf, watch out for conflicts. It could be better to manually register the Facade.

After updating composer, add the ServiceProvider to the providers array in config/app.php

Barryvdh\Snappy\ServiceProvider::class,

Optionally you can use the Facade for shorter code. Add this to your facades:

'PDF' => Barryvdh\Snappy\Facades\SnappyPdf::class,
'SnappyImage' => Barryvdh\Snappy\Facades\SnappyImage::class,

Finally you can publish the config file:

php artisan vendor:publish --provider="Barryvdh\Snappy\ServiceProvider"

Snappy config file

The main change to this config file (config/snappy.php) will be the path to the binaries.

For example, when loaded with composer, the line should look like:

'binary' => base_path('vendor/h4cc/wkhtmltopdf-amd64/bin/wkhtmltopdf-amd64'),

If you followed the vagrant steps, the line should look like:

'binary'  => '/usr/local/bin/wkhtmltopdf-amd64',

For windows users you'll have to add double quotes to the bin path for wkhtmltopdf:

'binary' => '"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf"'

Lumen

In bootstrap/app.php add:

class_alias('Barryvdh\Snappy\Facades\SnappyPdf', 'PDF');
$app->register(Barryvdh\Snappy\LumenServiceProvider::class);

Optionally, add the facades like so:

class_alias(Barryvdh\Snappy\Facades\SnappyPdf::class, 'PDF');
class_alias(Barryvdh\Snappy\Facades\SnappyImage::class, 'SnappyImage');

To customise the configuration file, copy the file /vendor/barryvdh/laravel-snappy/config/snappy.php to the /config folder.

Usage

You can create a new Snappy PDF/Image instance and load a HTML string, file or view name. You can save it to a file, or inline (show in browser) or download.

Using the App container:

$snappy = App::make('snappy.pdf');
//To file
$html = '<h1>Bill</h1><p>You owe me money, dude.</p>';
$snappy->generateFromHtml($html, '/tmp/bill-123.pdf');
$snappy->generate('http://www.github.com', '/tmp/github.pdf');
//Or output:
return new Response(
    $snappy->getOutputFromHtml($html),
    200,
    array(
        'Content-Type'          => 'application/pdf',
        'Content-Disposition'   => 'attachment; filename="file.pdf"'
    )
);

Using the wrapper:

$pdf = App::make('snappy.pdf.wrapper');
$pdf->loadHTML('<h1>Test</h1>');
return $pdf->inline();

Or use the facade:

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

You can chain the methods:

return PDF::loadFile('http://www.github.com')->inline('github.pdf');

You can change the orientation and paper size

PDF::loadHTML($html)->setPaper('a4')->setOrientation('landscape')->setOption('margin-bottom', 0)->save('myfile.pdf')

If you need the output as a string, you can get the rendered PDF with the output() function, so you can save/output it yourself.

See the wkhtmltopdf manual for more information/settings.

Testing - PDF fake

As an alternative to mocking, you may use the PDF facade's fake method. When using fakes, assertions are made after the code under test is executed:

<?php

namespace Tests\Feature;

use Tests\TestCase;
use PDF;

class ExampleTest extends TestCase
{
    public function testPrintOrderShipping()
    {
        PDF::fake();
        
        // Perform order shipping...
        
        PDF::assertViewIs('view-pdf-order-shipping');
        PDF::assertSee('Name');
    }
}

Other available assertions:

PDF::assertViewIs($value);
PDF::assertViewHas($key, $value = null);
PDF::assertViewHasAll(array $bindings);
PDF::assertViewMissing($key);
PDF::assertSee($value);
PDF::assertSeeText($value);
PDF::assertDontSee($value);
PDF::assertDontSeeText($value);
PDF::assertFileNameIs($value);

License

This Snappy Wrapper for Laravel is open-sourced software licensed under the MIT license