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

Prince Bundle Laravel Package

amenophis/prince-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation (Legacy Context) Since this bundle targets Symfony 2.3, ensure your project aligns with its constraints. Add the bundle to composer.json:

    composer require amenophis/prince-bundle
    

    Register the bundle in app/AppKernel.php:

    new Amenophis\PrinceBundle\AmenophisPrinceBundle(),
    
  2. Configuration Configure the bundle in app/config/config.yml:

    amenophis_prince:
        binary_path: /path/to/prince/bin/prince  # Absolute path to Prince binary
        timeout: 30                              # Timeout in seconds
    
  3. First Use Case: PDF Generation Inject the PrinceService into a controller/service and generate a PDF from HTML:

    use Amenophis\PrinceBundle\Service\PrinceService;
    
    class PdfController extends Controller
    {
        public function generatePdfAction()
        {
            $html = $this->renderView('path/to/template.html.twig');
            $pdf = $this->get('amenophis_prince')->generate($html, 'output.pdf');
            return new BinaryFileResponse($pdf);
        }
    }
    

Implementation Patterns

Core Workflows

  1. HTML-to-PDF Conversion Use the PrinceService to convert HTML (from Twig, strings, or files) to PDF:

    $service = $this->get('amenophis_prince');
    $pdf = $service->generate($htmlContent, 'output.pdf');
    
  2. Dynamic File Handling Stream PDFs directly to the browser or save them to disk:

    // Stream to browser
    $response = new BinaryFileResponse($pdf);
    $response->setContentDisposition(
        ResponseHeaderBag::DISPOSITION_INLINE,
        'report.pdf'
    );
    return $response;
    
    // Save to disk
    file_put_contents('path/to/output.pdf', $pdf);
    
  3. Twig Integration Pass HTML templates to the service:

    {% extends 'base.html.twig' %}
    {% block content %}
        <h1>Dynamic Content</h1>
        {{ someVariable }}
    {% endblock %}
    
    $html = $this->renderView('template.html.twig', ['someVariable' => 'value']);
    $pdf = $service->generate($html, 'output.pdf');
    
  4. Batch Processing Loop through HTML strings/arrays and generate multiple PDFs:

    $htmls = ['<h1>Doc 1</h1>', '<h1>Doc 2</h1>'];
    foreach ($htmls as $index => $html) {
        $service->generate($html, "doc_{$index}.pdf");
    }
    

Integration Tips

  • Symfony Forms: Use the bundle to generate PDF invoices/receipts from form data.
  • Event Listeners: Trigger PDF generation post-action (e.g., after user registration).
  • Queue Systems: Offload PDF generation to background jobs (e.g., Symfony Messenger) for large files.

Gotchas and Tips

Pitfalls

  1. Deprecated Bundle

    • Symfony 2.3 Only: This bundle will not work with Symfony 3+ or Laravel. Avoid in new projects.
    • No Maintenance: Issues (e.g., PHP 7+ incompatibility) will go unpatched. Use alternatives like spatie/pdf or dompdf for Laravel.
  2. Prince Binary Dependencies

    • Path Configuration: The binary_path in config.yml must point to the Prince executable. Test with:
      /path/to/prince/bin/prince --version
      
    • Permissions: Ensure the web server user (e.g., www-data) has execute permissions on the binary.
  3. Memory/Timeout Issues

    • Large HTML files may exceed PHP’s memory_limit or Prince’s timeout. Adjust:
      amenophis_prince:
          timeout: 60  # Increase if needed
      
      ; php.ini
      memory_limit = 512M
      
  4. Output Handling

    • Binary Data: The generate() method returns raw binary data. Always wrap in BinaryFileResponse for HTTP responses.
    • File Locking: Concurrent writes to the same output file may cause corruption. Use unique filenames or locks.

Debugging

  • Logs: Enable Symfony’s profiler to debug Prince errors:
    # app/config/config_dev.yml
    monolog:
        handlers:
            main:
                type: stream
                path: "%kernel.logs_dir%/%kernel.environment%.log"
                level: debug
    
  • Command-Line Testing: Test Prince directly via CLI to isolate issues:
    echo "<h1>Test</h1>" | /path/to/prince/bin/prince -o test.pdf
    

Extension Points

  1. Custom CSS/JS Inject Prince-specific stylesheets or scripts into your HTML:

    <link rel="stylesheet" href="{{ asset('css/prince-styles.css') }}">
    <script type="text/prince">
        @page { size: A4; }
    </script>
    
  2. Pre/Post-Processing Extend the service by overriding the generate() method in a custom class:

    class CustomPrinceService extends \Amenophis\PrinceBundle\Service\PrinceService
    {
        public function generate($html, $outputFile)
        {
            $html = $this->preProcessHtml($html); // Add headers, etc.
            return parent::generate($html, $outputFile);
        }
    }
    

    Register the service in services.yml:

    services:
        amenophis_prince:
            class: AppBundle\Service\CustomPrinceService
            arguments: ["@service_container"]
    
  3. Fallback Mechanisms Implement a fallback to a simpler library (e.g., Dompdf) if Prince fails:

    try {
        $pdf = $service->generate($html, 'output.pdf');
    } catch (\Exception $e) {
        $pdf = $this->fallbackToDomPdf($html);
    }
    

Laravel Alternatives

Since this bundle is Symfony-specific, Laravel developers should consider:

  • spatie/pdf: Modern, Laravel-friendly wrapper for Prince.
  • dompdf: Pure PHP alternative (less feature-rich but no binary dependency).
  • snappy: Uses wkhtmltopdf (another HTML-to-PDF tool).
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.
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium