Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Snappy Bundle Laravel Package

dlin/snappy-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation: Add the bundle and dependencies to composer.json as per the README, then run:

    composer update
    

    Enable the bundle in config/bundles.php (Symfony) or AppKernel.php (Laravel via Symfony bridge):

    Dlin\SnappyBundle\DlinSnappyBundle::class => ['all' => true],
    
  2. Configuration: Publish the default config:

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

    Update config/snappy.php with your wkhtmltopdf binary path (e.g., /usr/local/bin/wkhtmltopdf).

  3. First Use Case: Inject the SnappyPdf service into a controller or command:

    use Dlin\SnappyBundle\Service\SnappyPdf;
    
    class InvoiceController extends Controller
    {
        public function generatePdf(SnappyPdf $snappyPdf)
        {
            $html = '<h1>Invoice #123</h1><p>Generated at '.now().'</p>';
            $pdf = $snappyPdf->getPdf($html);
            return response($pdf, 200, [
                'Content-Type' => 'application/pdf',
                'Content-Disposition' => 'inline; filename="invoice.pdf"'
            ]);
        }
    }
    

Implementation Patterns

Core Workflows

  1. PDF Generation from HTML:

    $snappyPdf->getPdf($htmlString, [
        'orientation' => 'Portrait',
        'margin-top'   => '10mm',
        'margin-right' => '10mm',
        'margin-bottom' => '10mm',
        'margin-left'  => '10mm',
    ]);
    
    • Use for dynamic reports, invoices, or email attachments.
  2. PDF from URL:

    $snappyPdf->getPdfFromUrl('https://example.com/report', [
        'encoding' => 'UTF-8',
        'quiet'    => true,
    ]);
    
    • Ideal for generating PDFs from external web pages (e.g., caching public content).
  3. Image Thumbnails: Use the SnappyImage service (if available in the bundle or via KnpLabs/snappy):

    $snappyImage->getImage($html, $targetPath, [
        'width'  => 800,
        'height' => 600,
    ]);
    

Integration Tips

  • Laravel-Specific: Bind the Symfony service to Laravel’s container in AppServiceProvider:

    $this->app->bind('snappy.pdf', function ($app) {
        return $app->make('snappy.pdf.writer');
    });
    

    Then inject snappy.pdf into controllers.

  • Queueable Jobs: Offload PDF generation to a queue (e.g., snappy:generate-pdf job) to avoid timeouts:

    use Dlin\SnappyBundle\Service\SnappyPdf;
    
    class GeneratePdfJob implements ShouldQueue
    {
        public function handle(SnappyPdf $snappyPdf)
        {
            $pdf = $snappyPdf->getPdf($this->html);
            Storage::put('pdfs/invoice.pdf', $pdf);
        }
    }
    
  • Twig Integration: Create a Twig extension to generate PDFs from templates:

    class SnappyExtension extends \Twig_Extension
    {
        public function getFunctions()
        {
            return [
                new \Twig_SimpleFunction('generate_pdf', [$this->snappyPdf, 'getPdf']),
            ];
        }
    }
    

    Usage in Twig:

    {{ generate_pdf(html_content) }}
    

Gotchas and Tips

Pitfalls

  1. Binary Path Issues:

    • Error: Command not found or Failed to execute command.
    • Fix: Verify wkhtmltopdf is installed and the path in config/snappy.php is correct.
      which wkhtmltopdf  # Linux/Mac
      where wkhtmltopdf   # Windows
      
    • Windows Note: Use the wkhtmltopdf-i386 package if on 32-bit systems.
  2. Memory Limits:

    • Error: Out of memory or timeouts for large HTML.
    • Fix: Increase PHP memory (memory_limit in php.ini) or optimize HTML/CSS (e.g., inline styles, avoid heavy JS).
  3. Encoding Problems:

    • Error: Garbled text in PDFs.
    • Fix: Explicitly set encoding in options:
      $snappyPdf->getPdf($html, ['encoding' => 'UTF-8']);
      
  4. Deprecated Dependencies:

    • The bundle wraps KnpLabs/snappy, which is outdated (last update: 2014). Expect compatibility issues with modern PHP/Symfony.
    • Workaround: Fork the bundle or use a maintained alternative like spatie/pdf.

Debugging

  • Log Output: Enable verbose logging in config/snappy.php:

    'logging' => true,
    

    Check storage/logs/laravel.log for wkhtmltopdf command output.

  • Test Locally: Use a local wkhtmltopdf binary first to avoid deployment issues. Test with:

    wkhtmltopdf --version
    

Extension Points

  1. Custom Commands: Extend the bundle to add custom wkhtmltopdf flags:

    // In a service or config override
    $snappyPdf->setOption('custom-header', ['Accept-Language' => 'en-US']);
    
  2. Event Listeners: Listen for PDF generation events (if the bundle supports them) to log or modify output:

    // Example (hypothetical)
    $snappyPdf->addListener(function ($event) {
        if ($event->getStatus() === 'generated') {
            Log::info('PDF generated', ['size' => $event->getSize()]);
        }
    });
    
  3. Fallback for Missing Binary: Implement a fallback (e.g., DOMPDF) if wkhtmltopdf fails:

    try {
        return $snappyPdf->getPdf($html);
    } catch (\Exception $e) {
        $fallbackPdf = PDF::loadHTML($html)->output();
        return $fallbackPdf;
    }
    

Performance Tips

  • Cache HTML: Store generated HTML in the cache to avoid reprocessing.
  • Pre-render Templates: Use Laravel’s Blade or Twig to pre-render HTML before passing to SnappyPdf.
  • Limit Concurrent Jobs: Use Laravel’s afterCommit() or queue batching to prevent server overload.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui