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

Php Weasyprint Laravel Package

pontedilana/php-weasyprint

PHP wrapper for WeasyPrint (v60+) to generate PDFs from URLs or HTML. Snappy-like API with output streaming or file generation, supports WeasyPrint CLI options (encoding, media type, stylesheets, attachments) and timeouts.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Pros:

    • Laravel-Native Integration: Designed as a drop-in replacement for knplabs/snappy (via GeneratorInterface), enabling seamless adoption in Laravel apps using packages like barryvdh/laravel-dompdf or custom PDF generation logic.
    • CSS3 Support: Leverages WeasyPrint’s robust HTML/CSS rendering (Flexbox, Grid, responsive designs), critical for modern web apps transitioning to PDF exports.
    • Extensibility: Supports WeasyPrint’s CLI options (e.g., --timeout, --attachment, --xmp-metadata), allowing fine-grained control over PDF generation (e.g., metadata, attachments, accessibility tags).
    • Symfony Ecosystem Alignment: Built on symfony/process (v6.2+), ensuring compatibility with Laravel’s service container and event systems (e.g., logging, queues).
  • Cons:

    • Python Dependency: Requires WeasyPrint (Python-based), adding infrastructure complexity (e.g., Docker/Python installation, version pinning).
    • No Multi-PDF Merging: Unlike Snappy, this package cannot merge multiple HTML sources into a single PDF (limitation of WeasyPrint’s CLI API).
    • Legacy Image Support: Older WeasyPrint versions (<53) are needed for image generation from HTML (deprecated in this package).

Integration Feasibility

  • Laravel Compatibility:
    • Works with Laravel’s Service Container: Bind the Pdf class as a singleton or context-bound service for dependency injection.
    • Queue/Job Integration: Supports disabling internal timeouts ($pdf->disableTimeout()) to avoid conflicts with Laravel Queues (e.g., shouldQueue()).
    • Blade Templates: Can generate PDFs from Blade-rendered HTML by passing the output to getOutput() or generateFromHtml().
  • Example Integration:
    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(Pdf::class, function ($app) {
            return new Pdf(config('weasyprint.binary_path'));
        });
    }
    
    // routes/web.php
    Route::get('/invoice/{id}', function ($id) {
        $pdf = app(Pdf::class);
        $html = view('invoices.pdf', ['id' => $id])->render();
        return response($pdf->getOutput($html))
            ->header('Content-Type', 'application/pdf');
    });
    

Technical Risk

  • Infrastructure Risks:
    • Python/WeasyPrint Setup: Requires Python 3.8+ and WeasyPrint (≥60.0). Docker containers or server-side Python installation may need configuration (e.g., apt-get install python3-weasyprint).
    • Binary Path: Hardcoding /usr/local/bin/weasyprint is fragile; use environment variables or config files (e.g., .env):
      WEASYPRINT_BINARY=/usr/local/bin/weasyprint
      
  • Performance Risks:
    • Timeout Handling: Default 10-second timeout may be insufficient for complex PDFs (e.g., large tables, external resources). Adjust via setTimeout() or disable in queued jobs.
    • Memory Usage: WeasyPrint processes can consume significant memory for high-fidelity PDFs (e.g., multi-page documents with images). Monitor in production.
  • Security Risks:
    • HTTP Requests: By default, follows redirects (--no-http-redirects can be enabled to mitigate SSRF risks).
    • CSS/JS Injection: User-provided HTML/CSS may introduce vulnerabilities (e.g., XSS via style tags). Sanitize input or use a whitelist (e.g., Laravel’s Purifier).
    • Dependency Vulnerabilities: Relies on symfony/process (patched for CVE-2024-51736) and WeasyPrint (track for updates).

Key Questions

  1. Infrastructure:
    • Can your hosting environment (e.g., shared server, PaaS) support Python/WeasyPrint installation?
    • How will you handle WeasyPrint version upgrades (e.g., Docker images, CI/CD pipelines)?
  2. Performance:
    • What is the expected complexity of generated PDFs (e.g., pages, external resources)? Will the default timeout suffice?
    • Are there plans to offload PDF generation to a microservice or queue worker?
  3. Security:
    • How will you sanitize dynamic HTML content (e.g., user-generated reports) to prevent CSS/JS injection?
    • Are there compliance requirements (e.g., GDPR) for PDF metadata or attachments?
  4. Maintenance:
    • Who will monitor WeasyPrint updates and PHP/Symfony compatibility?
    • Is there a fallback plan if WeasyPrint fails (e.g., degraded mode with a static PDF)?
  5. Use Cases:
    • Do you need multi-PDF merging or advanced features (e.g., OCR, forms)? If so, this package may not suffice.
    • Are there legacy dependencies on knplabs/snappy or dompdf that need migration?

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • Service Container: Register the Pdf class as a singleton or context-bound service for DI.
    • Queues/Jobs: Use disableTimeout() in queued jobs to avoid conflicts with Laravel’s queue workers (e.g., shouldQueue()).
    • Blade Integration: Generate PDFs from Blade templates by passing rendered views to getOutput() or generateFromHtml().
    • API Responses: Return PDFs via response()->stream() or Storage::disk('public')->put() for file downloads.
  • Symfony Compatibility:
    • Supports Symfony 7.0–8.0 and PHP 8.3–8.5, aligning with Laravel’s LTS releases.
    • Uses symfony/process for subprocess management, ensuring consistency with Laravel’s Process facade.
  • Testing:
    • Mock Pdf class in unit tests using PHPUnit’s createMock() or Laravel’s Mockery.
    • Test edge cases: timeouts, malformed HTML, external resource failures.

Migration Path

  1. Assessment:
    • Audit current PDF generation code (e.g., knplabs/snappy, dompdf, or custom solutions).
    • Identify use cases requiring multi-PDF merging or image generation (not supported).
  2. Pilot:
    • Replace a non-critical PDF endpoint (e.g., /reports/pdf) with php-weasyprint.
    • Test with static HTML first, then dynamic content (e.g., Blade templates).
  3. Incremental Rollout:
    • Phase 1: Replace snappy calls in controllers/services with php-weasyprint.
    • Phase 2: Update Blade templates to use php-weasyprint-compatible CSS (e.g., avoid unsupported properties).
    • Phase 3: Migrate queued jobs to use disableTimeout() and monitor performance.
  4. Fallback Strategy:
    • Implement a feature flag to toggle between old and new PDF generators during migration.
    • Cache generated PDFs (e.g., Redis) to reduce WeasyPrint load during rollout.

Compatibility

  • WeasyPrint Version:
    • Requires WeasyPrint ≥60.0. Test with the latest stable version (e.g., 68.0) to ensure compatibility with new CLI options.
    • Use a Docker image (e.g., python:3.11-slim) or system package manager (e.g., apt-get install python3-weasyprint) for consistency.
  • PHP/Laravel:
    • Test with Laravel 10.x (PHP 8.2+) and 11.x (PHP 8.3+). Use composer require php:^8.3 if needed.
    • For Laravel <9.0, use v1.x of this package (last Symfony 6.x compatible version).
  • CSS/HTML:
    • Validate templates against WeasyPrint’s CSS support. Avoid unsupported properties (e.g., @font-face with local files).
    • Use tools like Purifier to sanitize dynamic HTML.

Sequencing

  1. Infrastructure Setup:
    • Install WeasyPrint on all target environments (e.g., staging, production).
    • Configure binary path via .env or config files.
  2. Code Changes:
    • Replace SnappyPdf with Pontedilana\PhpWeasyPrint\Pdf in services/controllers.
    • Update timeout handling (e.g., disable in queues, adjust for complex PDFs).
  3. Testing:
    • Unit tests: Mock Pdf class to test integration with services.
    • Integration tests: Verify PDF generation from Blade templates and URLs.
    • Performance tests: Measure memory/CPU usage for large PDFs.
  4. Deployment:
    • Roll out in stages (e.g., non-production first).
    • Monitor logs
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.
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
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope