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 Bundle Laravel Package

knplabs/knp-snappy-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require knplabs/knp-snappy-bundle
    

    Add to config/bundles.php (Symfony 4.4+ auto-discovers, but explicit inclusion ensures clarity):

    Knp\Bundle\SnappyBundle\KnpSnappyBundle::class => ['all' => true],
    
  2. Configuration: Edit config/packages/knp_snappy.yaml to specify the binary path (default: wkhtmltopdf):

    knp_snappy:
        pdf:
            enabled:    true
            binary:     '/usr/local/bin/wkhtmltopdf' # Adjust path
            options:    []
            timeout:    60000
        image:
            enabled:    true
            binary:     '/usr/local/bin/wkhtmltoimage'
            options:    []
            timeout:    60000
    
  3. First Use Case: Generate a PDF from a Twig template in a controller:

    use Knp\Snappy\Pdf;
    
    public function generatePdf(Pdf $pdfGenerator)
    {
        $html = $this->renderView('pdf/template.html.twig', ['data' => $data]);
        $pdf = $pdfGenerator->generateFromHtml($html);
        return new Response($pdf, 200, ['Content-Type' => 'application/pdf']);
    }
    

Implementation Patterns

Core Workflows

  1. PDF Generation:

    • From Twig: Use Pdf service with generateFromHtml().
    • From File: Stream HTML files directly:
      $pdf = $pdfGenerator->generateFromFile('path/to/template.html.twig');
      
    • Custom Options: Pass WKHTMLTOPDF flags via options:
      knp_snappy:
          pdf:
              options: ['--margin-top', '20mm', '--orientation', 'Landscape']
      
  2. Image Generation:

    • Convert HTML to images (e.g., for email previews):
      use Knp\Snappy\Image;
      $image = $imageGenerator->generateFromHtml($html, 'screenshot.png');
      
  3. Streaming Large Files:

    • Avoid memory issues by streaming directly to a response:
      $response = new Response();
      $pdfGenerator->generateFromHtml($html)->stream($response, 'invoice.pdf');
      return $response;
      
  4. Dynamic Templates:

    • Combine with Twig’s embed for reusable components:
      {% embed 'base_pdf_layout.html.twig' %}
          {{ include('content/' ~ section ~ '.html.twig') }}
      {% endembed %}
      

Integration Tips

  • Symfony Forms: Pass form data to Twig:
    $formView = $this->renderView('form.html.twig', ['form' => $form->createView()]);
    
  • Queue Jobs: Offload PDF generation to a queue (e.g., Symfony Messenger):
    $this->messageBus->dispatch(new GeneratePdfJob($html, $userId));
    
  • Cache Templates: Cache compiled Twig templates for repeated use:
    $cachedHtml = $this->get('twig')->createTemplate($template)->render($context);
    

Gotchas and Tips

Pitfalls

  1. Binary Path Issues:

    • Error: Command not found or Failed to execute binary.
    • Fix: Verify wkhtmltopdf/wkhtmltoimage is installed and path is correct. Use absolute paths in config.
    • Debug: Test binary manually:
      /usr/local/bin/wkhtmltopdf --version
      
  2. Memory Limits:

    • Error: Allowed memory size exhausted for large PDFs.
    • Fix: Increase PHP memory (ini_set('memory_limit', '2G')) or stream output.
  3. Font/Encoding Issues:

    • Error: Garbled text or missing fonts.
    • Fix: Install fonts on the server or specify custom font paths in WKHTMLTOPDF options:
      options: ['--enable-local-file-access', '--custom-header', 'Accept-Encoding', 'gzip']
      
  4. Twig Auto-escaping:

    • Error: HTML tags rendered as text.
    • Fix: Disable escaping in Twig or use |raw filter:
      {{ content|raw }}
      

Debugging

  • Log WKHTMLTOPDF Output: Redirect stderr to a log file in config:

    options: ['--quiet', '--debug-javascript']
    

    Or use Symfony’s logger:

    $pdfGenerator->getBinary()->setLogger($this->get('logger'));
    
  • Validate HTML: Use browser dev tools to test HTML rendering before PDF generation.

Extension Points

  1. Custom Binary Wrapper: Extend Knp\Snappy\Binary\Binary to add pre/post-processing:

    class CustomBinary extends Binary
    {
        protected function getCommand(array $options)
        {
            $options[] = '--custom-flag';
            return parent::getCommand($options);
        }
    }
    

    Register as a service:

    knp_snappy.pdf.binary: '@custom_binary'
    
  2. Event Listeners: Hook into PDF generation lifecycle (e.g., modify content before conversion):

    use Knp\Snappy\Event\GenerateEvent;
    
    public function onGenerate(GenerateEvent $event)
    {
        $event->setHtml($this->modifyHtml($event->getHtml()));
    }
    

    Bind in services.yaml:

    Knp\SnappyBundle\EventListener\GenerateListener:
        tags:
            - { name: kernel.event_listener, event: knp_snappy.generate, method: onGenerate }
    
  3. Async Generation: Use Symfony’s Process component to run WKHTMLTOPDF asynchronously:

    $process = new Process(['/usr/local/bin/wkhtmltopdf', '--quiet', $input, $output]);
    $process->start();
    

Configuration Quirks

  • Disable Components: Set enabled: false for PDF/image generation if using only one feature.
  • Timeout Adjustments: Increase timeout for large documents (default: 60s):
    timeout: 120000 # 2 minutes
    
  • Environment-Specific Binaries: Use %kernel.project_dir% or environment variables:
    binary: '%env(WKHTMLTOPDF_BINARY)%'
    
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.
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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