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

Browsershot Laravel Package

spatie/browsershot

Convert web pages or raw HTML to images and PDFs in PHP using Puppeteer-driven headless Chrome. Capture screenshots, generate PDFs, fetch rendered body HTML, and inspect triggered network requests—ideal for reports, previews, and testing.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Enhanced Use Case Alignment: The new evaluateOnNewDocument feature (v5.4.0) enables JavaScript execution in the context of a blank PDF document, unlocking advanced PDF manipulation capabilities such as:
    • Dynamic PDF form population (e.g., filling out AcroForms with JavaScript).
    • Post-processing PDFs (e.g., adding headers/footers, watermarks, or dynamic stamps via JavaScript).
    • Complex PDF generation workflows (e.g., merging multiple PDFs or injecting client-side-rendered content into a template).
  • Abstraction Layer Expansion: The feature maintains the PHP-first API while exposing Puppeteer’s page.evaluateOnNewDocument() under the hood, reducing the need for raw Node.js/Puppeteer code.
  • Laravel Synergy: Complements existing Laravel integrations (e.g., Laravel Excel for exporting dynamic data to PDFs) and Laravel Notifications (e.g., attaching interactive PDFs to emails).

Integration Feasibility

  • Dependencies:
    • No breaking changes to Node.js/Puppeteer requirements (still Node.js 22+ and Puppeteer 23+).
    • New JavaScript execution context may introduce additional memory usage for complex PDF manipulations.
  • Laravel Compatibility:
    • Works seamlessly with Laravel’s service container (inject Browsershot and use dependency injection for evaluateOnNewDocument).
    • Supports queued jobs for async PDF generation (critical for performance-sensitive applications).
  • Database/ORM Fit:
    • Enables storing JavaScript logic in the database (e.g., pdf_generation_script column in a templates table) for dynamic PDF customization.

Technical Risk

Risk Area Mitigation Strategy
JavaScript Execution Overhead Benchmark memory/CPU usage for evaluateOnNewDocument in staging; optimize with ->setNodeModulePath() and Docker.
Security Risks Sanitize all JavaScript payloads to prevent PDF-based attacks (e.g., malicious scripts injected via evaluateOnNewDocument). Use a whitelist or sandboxed execution.
Cross-Platform Issues Test on target environments (e.g., Ubuntu 24.04, Windows Server) for Chromium/PDF rendering consistency.
Debugging Complexity Leverage ->debug() or ->saveDebugScreenshot() to inspect intermediate PDF states during JavaScript execution.
Performance Cache static JavaScript logic (e.g., reusable PDF templates) to avoid reprocessing.

Key Questions

  1. Use Case Validation:
    • Will evaluateOnNewDocument be used for dynamic form filling, PDF post-processing, or client-side-rendered content injection?
    • Are there existing PDF libraries (e.g., TCPDF, DomPDF) that could be replaced or augmented with this feature?
  2. Security:
    • How will JavaScript payloads be validated/sanitized (e.g., allowlist of safe functions, sandboxing)?
    • Are there compliance requirements (e.g., GDPR, HIPAA) for PDF content manipulation?
  3. Scaling:
    • Will evaluateOnNewDocument be used in high-volume scenarios (e.g., 1,000+ PDFs/hour)? If so, test queue performance under load.
    • Are there fallback mechanisms for environments where JavaScript execution fails (e.g., degraded mode)?
  4. Testing:
    • How will JavaScript-driven PDF outputs be tested (e.g., unit tests for evaluateOnNewDocument logic, visual regression for PDFs)?
    • Will CI/CD pipelines include validation of PDF structure (e.g., form fields, metadata)?
  5. Deployment:
    • Will this feature require additional Chromium flags (e.g., --enable-features=PDF) for PDF manipulation support?

Integration Approach

Stack Fit

  • PHP/Laravel Stack:
    • Pros: Native PHP API simplifies integration; evaluateOnNewDocument extends Laravel’s PDF capabilities without Node.js context-switching.
    • Cons: JavaScript execution adds complexity to error handling (e.g., debugging Puppeteer’s DevTools Protocol errors).
  • Alternative Stacks:
    • Node.js Backend: For teams comfortable with Puppeteer, direct usage may offer more flexibility (but loses PHP abstraction).
    • Hybrid Approach: Use evaluateOnNewDocument for PDF post-processing while keeping core generation in PHP.
  • Database:
    • Store JavaScript logic in DB (e.g., templates table with script column) for dynamic PDF customization.
    • Use Laravel’s file storage (local/S3) for generated PDFs with metadata (e.g., generated_at, script_hash).

Migration Path

  1. Pilot Phase:
    • Start with simple JavaScript injections (e.g., adding a page number to every PDF).
    • Test evaluateOnNewDocument with static HTML templates to validate output.
  2. Gradual Rollout:
    • Replace legacy PDF libraries (e.g., TCPDF) for form-heavy PDFs (e.g., contracts, surveys).
    • Migrate synchronous PDF generation to queued jobs with evaluateOnNewDocument for scalability.
  3. Optimization:
    • Cache reusable JavaScript logic (e.g., common PDF stamps) to reduce execution overhead.
    • Use ->addChromiumArguments(['--disable-gpu']) to improve performance in headless environments.

Compatibility

Component Compatibility Notes
Laravel Versions No changes; continues to support Laravel 10+.
PHP Versions Requires PHP 8.1+ (unchanged).
Node.js Still requires Node.js 22+ and Puppeteer 23+ (no breaking changes).
Chrome/Chromium Requires Chrome 120+ with PDF support (e.g., --enable-features=PDF).
Storage Systems Unchanged; works with local/S3/PSR-3 storage.
Queue Systems Supports Laravel’s default queues (Redis, database, etc.).

Sequencing

  1. Setup:
    • Update composer.json to spatie/browsershot:^5.4 and run composer update.
    • Ensure Node.js 22+ and Puppeteer 23+ are installed (npm install puppeteer@latest).
  2. Basic Integration:
    • Inject simple JavaScript:
      Browsershot::html($html)
          ->evaluateOnNewDocument('
              document.addEventListener("DOMContentLoaded", () => {
                  document.body.style.fontSize = "12pt";
              });
          ')
          ->save('output.pdf');
      
  3. Core Features:
    • Implement dynamic form filling:
      Browsershot::html($html)
          ->evaluateOnNewDocument('
              document.forms[0].elements[0].value = "'.e($customerName).'";
          ')
          ->save('invoice.pdf');
      
  4. Advanced Features:
    • Use queued jobs for async PDF generation with JavaScript:
      Browsershot::dispatch($html)
          ->evaluateOnNewDocument($script)
          ->onQueue('pdfs')
          ->save('storage/app/pdf/' . $filename);
      
    • Add error handling for JavaScript execution:
      try {
          Browsershot::html($html)->evaluateOnNewDocument($script)->save($path);
      } catch (\Exception $e) {
          Log::error("PDF generation failed: " . $e->getMessage());
          // Fallback to static PDF or notify user
      }
      
  5. Monitoring:
    • Log JavaScript execution errors (e.g., syntax errors, Puppeteer timeouts).
    • Set up health checks for Chromium/PDF rendering (e.g., verify --enable-features=PDF is supported).

Operational Impact

Maintenance

  • Dependency Updates:
    • Node.js/Puppeteer: Monitor for updates to evaluateOnNewDocument support (e.g., new Chromium features).
    • PHP Package: Minor updates are low-risk; major versions may require testing for JavaScript execution stability.
  • Configuration Drift:
    • Chromium Flags: Ensure --enable-features=PDF (or equivalent) is set for PDF manipulation.
    • Mitigation: Use Docker or infrastructure-as-code to pin Chromium versions and flags.
  • Logging:
    • Log JavaScript execution errors and **PDF generation metrics
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.
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
anil/file-picker
broqit/fields-ai