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

Knp Snappy Laravel Package

knplabs/knp-snappy

PHP wrapper for wkhtmltopdf/wkhtmltoimage to generate PDFs and images (thumbnails, snapshots) from URLs or HTML. Simple API, configurable binaries and options, with integrations available for Symfony and Laravel.

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Install the Package

    composer require knplabs/knp-snappy
    

    For Laravel, consider using the dedicated bundle:

    composer require barryvdh/laravel-snappy
    
  2. Install wkhtmltopdf Download the correct version (0.12.x) from wkhtmltopdf.org and ensure it's executable. For automated installation via Composer (Linux):

    composer require h4cc/wkhtmltopdf-amd64  # 64-bit
    # or
    composer require h4cc/wkhtmltopdf-i386   # 32-bit
    
  3. Basic Usage Initialize the Pdf class with the binary path:

    use Knp\Snappy\Pdf;
    $snappy = new Pdf('/usr/local/bin/wkhtmltopdf');
    

First Use Case: Generate a PDF from a URL

$snappy = new Pdf('/usr/local/bin/wkhtmltopdf');
header('Content-Type: application/pdf');
echo $snappy->getOutput('https://example.com');

Implementation Patterns

Core Workflows

  1. Generating PDFs

    • From a URL:
      $snappy->getOutput('https://example.com');
      
    • From HTML:
      $snappy->generateFromHtml('<h1>Hello</h1>', 'output.pdf');
      
    • From Multiple URLs (Merged):
      $snappy->getOutput(['https://url1.com', 'https://url2.com']);
      
  2. Generating Images Use the Image class for thumbnails/snapshots:

    use Knp\Snappy\Image;
    $image = new Image('/usr/local/bin/wkhtmltoimage');
    $image->getOutput('https://example.com');
    
  3. Streaming Responses For browser display or downloads:

    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="report.pdf"');
    echo $snappy->getOutput('https://example.com');
    

Integration Tips

  1. Laravel Integration Use barryvdh/laravel-snappy for seamless Laravel integration:

    use Barryvdh\Snappy\SnappyPdf;
    $pdf = SnappyPdf::loadView('pdf.template', ['data' => $data]);
    return $pdf->stream('filename.pdf');
    
  2. Queueing Long-Running Tasks Offload PDF generation to a queue (e.g., Laravel Queues):

    dispatch(new GeneratePdfJob($url, $filename));
    
  3. Dynamic Options Set options dynamically based on context:

    $snappy->setOption('margin-top', '20mm');
    $snappy->setOption('margin-bottom', '20mm');
    $snappy->setOption('orientation', 'Landscape');
    
  4. Caching Cache generated PDFs to avoid reprocessing:

    $cacheKey = 'pdf_' . md5($url);
    if (cache()->has($cacheKey)) {
        return cache()->get($cacheKey);
    }
    $pdf = $snappy->getOutput($url);
    cache()->put($cacheKey, $pdf, now()->addHours(1));
    return $pdf;
    
  5. Error Handling Validate wkhtmltopdf output and handle failures:

    try {
        $pdf = $snappy->getOutput($url);
    } catch (\Knp\Snappy\Exception\GenerationException $e) {
        Log::error('PDF generation failed: ' . $e->getMessage());
        return response()->view('errors.pdf_failed');
    }
    

Gotchas and Tips

Pitfalls

  1. Binary Path Issues

    • Ensure the binary path is absolute and executable.
    • Avoid passing arguments directly in the binary path (post-v1.7.1):
      // ❌ Avoid (deprecated)
      $snappy = new Pdf('/usr/local/bin/wkhtmltopdf --quiet');
      
      // ✅ Correct
      $snappy = new Pdf('/usr/local/bin/wkhtmltopdf');
      $snappy->setOption('quiet', true);
      
  2. Security Risks

    • Never enable --enable-local-file-access for untrusted HTML/JS.
    • Sanitize user input to prevent wkhtmltopdf exploits.
    • Use sandboxing (e.g., Docker, SELinux) for untrusted content.
  3. Memory Limits

    • Large HTML/PDFs may hit PHP memory limits. Increase memory_limit or optimize the input:
      ini_set('memory_limit', '512M');
      
  4. Cross-Platform Paths

    • Use forward slashes (/) or DIRECTORY_SEPARATOR for paths:
      $snappy->setOption('cache-dir', storage_path('app') . DIRECTORY_SEPARATOR . 'cache');
      
  5. Temporary Files

    • Snappy uses temp files. Ensure the temp directory is writable:
      $snappy->setOption('temp-dir', sys_get_temp_dir());
      

Debugging Tips

  1. Check wkhtmltopdf Logs Enable verbose logging to diagnose issues:

    $snappy->setOption('debug-javascript', true);
    $snappy->setOption('log-level', '9');
    
  2. Validate HTML/JS Test HTML/JS in a browser first. Use tools like Puppeteer for debugging.

  3. Process Output Capture wkhtmltopdf stderr for errors:

    $output = $snappy->getOutput($url, ['output' => 'output.pdf']);
    $error = $snappy->getErrorOutput();
    Log::error($error);
    
  4. Common Errors

    • "Binary not found": Verify the binary path and permissions (chmod +x).
    • "Failed to load PDF": Check if the URL/HTML is valid or blocked (e.g., by robots.txt).
    • "Out of memory": Simplify the HTML or increase memory limits.

Extension Points

  1. Custom Options Extend Snappy to support custom wkhtmltopdf options:

    $snappy->setOption('custom-header', ['User-Agent' => 'MyAgent/1.0']);
    
  2. Pre/Post-Processing Hook into the generation process:

    $snappy->generateFromHtml($html, 'output.pdf');
    // Post-process the file (e.g., compress, sign)
    
  3. Event Listeners Use Laravel events to trigger actions before/after PDF generation:

    event(new PdfGenerated($pdfPath, $url));
    
  4. Fallback Mechanisms Implement fallback to alternative libraries (e.g., Dompdf) if wkhtmltopdf fails:

    try {
        $pdf = $snappy->getOutput($url);
    } catch (\Exception $e) {
        $pdf = app(\Dompdf\Dompdf::class)->loadHtml($html)->output();
    }
    

Configuration Quirks

  1. Default Options Reset options to defaults:

    $snappy->resetOptions();
    
  2. Option Order Options are passed in the order they are set. Critical options (e.g., quiet) should be set first.

  3. Windows-Specific On Windows, ensure paths use backslashes or forward slashes:

    $snappy->setOption('cache-dir', 'C:/temp/cache');
    
  4. Docker Environments Mount the wkhtmltopdf binary into the container:

    COPY --from=wkhtmltopdf /usr/local/bin/wkhtmltopdf /usr/local/bin/
    

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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor