PDF Studio for Laravel

repository·main·Indexed 41 days ago

https://github.com/sarderiftekhar/pdf-studio

A tool for designing, previewing, and generating high-fidelity PDFs using HTML and TailwindCSS. It supports multiple rendering drivers including Chromium, Cloudflare, Gotenberg, WeasyPrint, wkhtmltopdf, and dompdf. Features include a Template Registry, custom Blade directives for page layout, asynchronous queue rendering, batch processing, and a Visual Builder for defining document layouts via JSON schema.

Tokens
25.5K
Snippets
79
Records
96
Agent score
99%

What's inside PDF Studio for Laravel

  1. Understand the PDF Studio v3 Roadmap and Strategic Goals

    main

    The v3 roadmap for PDF Studio aims to evolve the package from a broad Laravel PDF tool into a high-performance, compliant, and reliable market contender. The primary focus areas for upcoming versions include:

    • Expanded Driver Support: Adding remote and managed renderers like weasyprint, gotenberg, and cloudflare to reduce local operational complexity.
    • Enhanced Rendering Control: Exposing more direct Chromium and print options (e.g., outline, tagged, preferCSSPageSize).
    • Compliance & Accessibility: Adding support for PDF metadata, attachments, and specific archival formats like PDF/A and PDF/UA.
    • Reliability & Debugging: Improving font/Unicode/RTL handling, asset resolution (images/CSS), and providing better tools for diagnosing rendering drift in Docker or CI environments.
    • Large Document Handling: Implementing strategies for segmentation, merging, and managing memory-heavy or JS-heavy (charts) documents.
  2. Planned Driver Subsystem Architecture

    main

    The v3 architecture refactors the driver system into a clearer contract-based model. This allows users to switch between local and remote renderers using the same fluent API while maintaining driver-specific capabilities.

    Core Abstractions:

    • RendererContract: The primary interface for rendering.
    • RemoteRendererContract: Interface for service-backed (HTTP) renderers.
    • DriverCapabilities: A model used to check if a driver supports specific features (e.g., supportsTaggedPdf, supportsJavascript, supportsPageRanges).
    • DriverHealthCheckContract: Used for driver diagnostics.

    Planned Drivers:

    • Chromium: Recommended for TailwindCSS and advanced JS/CSS requirements.
    • Gotenberg: Remote service-backed driver.
    • Cloudflare: Remote service-backed driver.
    • WeasyPrint: Print-native driver for high-fidelity document layouts.
  3. Choose the right PDF Studio driver

    main

    PDF Studio supports multiple drivers, each suited for different rendering needs. Use this decision guide to select the best one for your workload:

    • chromium: Best for highest CSS fidelity and JavaScript execution. Requires Node and a browser runtime locally.
    • cloudflare: Best for managed Chromium rendering without managing local Chrome/Node. Requires an external service dependency.
    • gotenberg: Best for self-hosted remote Chromium rendering. Ideal for isolating rendering workloads from your app nodes.
    • weasyprint: Best for print-native workflows, PDF/A or PDF/UA variants, and document-oriented templates. Does not support browser JavaScript.
    • dompdf: Best for lightweight, simple documents with minimal dependencies. Has limited support for modern CSS (like Flexbox) and no JS support.
    • wkhtmltopdf: Use only for legacy compatibility with existing infrastructure.
    • fake: Use for testing purposes only.
    | Driver | Runtime Model | CSS Fidelity | JS Support | Best Strength |
    |--------|---------------|--------------|------------|---------------|
    | `chromium` | Local Chrome + Browsershot | Excellent | Yes | Best general-purpose HTML fidelity |
    | `cloudflare` | Managed remote Chromium | Excellent | Yes | No local browser management |
    | `gotenberg` | Self-hosted remote Chromium | Excellent | Yes | Good for queue workers and isolated render infra |
    | `weasyprint` | Local binary | Good for print CSS | No browser JS | Great print-native workflows and PDF variants |
    | `dompdf` | PHP package | Limited | No | Easiest install footprint |
    | `wkhtmltopdf` | Local binary | Moderate | Limited | Stable for some legacy stacks |
    | `fake` | Built-in | N/A | N/A | Testing |
  4. Conceptual Model: Core vs. Platform Layers

    main

    PDF Studio is architected around two distinct conceptual layers. While they may not be separate packages yet, the documentation and architecture are moving toward a modular separation:

    Core

    This layer handles the fundamental PDF generation and manipulation logic:

    • Fluent builder API
    • Render pipeline
    • Driver system
    • Document manipulation (merge, split, etc.)
    • Thumbnail generation
    • Testing tools

    Platform

    This layer provides the higher-level services and SaaS-ready features:

    • Preview routes
    • Template registry and builder
    • Versioning and workspaces
    • API rendering
    • Analytics and usage metering
  5. Configure and use PDF Drivers

    main

    PDF Studio supports multiple drivers depending on your needs for CSS fidelity and environment constraints. You can set a global default in config/pdf-studio.php or switch drivers per request.

    Available Drivers

    DriverBest For
    chromiumHigh-fidelity local rendering (Recommended for TailwindCSS)
    cloudflareManaged remote rendering (No local Node required)
    gotenbergSelf-hosted remote Chromium rendering
    weasyprintPrint-native rendering, attachments, and PDF variants
    wkhtmltopdfLegacy compatibility
    dompdfZero external dependencies (Limited CSS)
    fakeTesting only

    Driver Configuration Examples

    Cloudflare:

    'drivers' => [
        'cloudflare' => [
            'account_id' => env('PDF_STUDIO_CLOUDFLARE_ACCOUNT_ID'),
            'api_token' => env('PDF_STUDIO_CLOUDFLARE_API_TOKEN'),
        ],
    ],

    Gotenberg:

    'drivers' => [
        'gotenberg' => [
            'url' => env('PDF_STUDIO_GOTENBERG_URL', 'http://127.0.0.1:3000'),
        ],
    ],

    WeasyPrint:

    'drivers' => [
        'weasyprint' => [
            'binary' => env('PDF_STUDIO_WEASYPRINT_BINARY', 'weasyprint'),
        ],
    ],
    // Set default in config/pdf-studio.php
    'default_driver' => 'chromium',
    
    // Switch per-render
    Pdf::view('report')->driver('dompdf')->download('report.pdf');
  6. Configure Table of Contents (TOC) options

    main

    When working with Table of Contents features, you can control how headings are extracted and displayed using TocOptions.

    Available properties:

    • depth: The maximum heading level to include (e.g., 6 for all <h1> through <h6>).
    • title: The text used for the TOC title. Defaults to 'Table of Contents'.
    • mode: Determines how headings are selected:
      • 'auto': Includes all headings up to the specified depth, but excludes any heading explicitly marked with data-toc="false".
      • 'explicit': Only includes headings that have the data-toc attribute present.
    • bookmarks: Boolean indicating whether to generate bookmarks. Defaults to false.
    use PdfStudio\Laravel\DTOs\TocOptions;
    
    // Customizing TOC behavior
    $options = new TocOptions(
        depth: 3, 
        title: 'Contents', 
        mode: 'explicit'
    );
  7. Handle assets and images in PDF generation

    main

    To prevent images or CSS from disappearing in the generated PDF, follow these best practices:

    1. Inlining: Enable local asset inlining where possible.
    2. Remote Assets: If you must use remote assets, set assets.allow_remote=false unless explicitly required. If required, restrict them using assets.allowed_hosts.
    3. Path Resolution: PDF Studio resolves CSS url(...) assets in both <link> tags and <style> blocks. Use stable absolute URLs or inline assets for remote renderers like Gotenberg or Cloudflare.
  8. Manage large documents and composition

    main

    For large reports that cause timeouts or memory pressure, use the following strategies:

    • Composition: Use Pdf::compose() to render different sections of a document separately and combine them into one.
    • Chunking: Use chunk() or chunkPlan() to split a large PDF into smaller, manageable page ranges.
    • Validation: Use isPdf() or isPdfFile() to verify content before processing, and assertPdf() to fail jobs immediately if the output is invalid.
    • Inspection: Use inspectPdf() to get metadata like page_count and byte_size.
    // Example of composing a large report from multiple views
    Pdf::compose([
        ['view' => 'reports.cover'],
        ['view' => 'reports.summary'],
        ['view' => 'reports.detail'],
    ], driver: 'cloudflare');
    
    // Example of chunking a large PDF into 50-page segments
    $chunks = Pdf::chunk($pdfContent, 50);
  9. Run the test, lint, and static analysis suite

    main

    To ensure code quality and verify changes, run the following commands in sequence:

    1. Run tests: Use Pest to execute the full test suite.
    2. Run linter: Use Pint to fix code style issues.
    3. Run static analysis: Use PHPStan to identify potential bugs or type mismatches.

    If issues are found, fix them before committing your changes.

    ./vendor/bin/pest
    ./vendor/bin/pint
    ./vendor/bin/phpstan analyse
  10. Install optional dependencies

    main

    PDF Studio requires several optional packages depending on the features you need (e.g., Chromium for TailwindCSS, dompdf, or PDF manipulation). You can install them via the Artisan command:

    • Interactive installation: php artisan pdf-studio:install (allows picking features from a list).
    • Bulk installation: php artisan pdf-studio:install --all (installs all optional dependencies).
    # Interactive — choose which features to install
    php artisan pdf-studio:install
    
    # Install everything
    php artisan pdf-studio:install --all
  11. Install PDF Studio for Laravel

    main

    To install PDF Studio, use Composer to require the package and then publish the configuration file. You can also use an interactive installer to pick specific features or install all optional dependencies at once.

    Installation Steps

    1. Install the core package:
      composer require sarder/pdfstudio
    2. Publish the configuration:
      php artisan vendor:publish --tag=pdf-studio-config
    3. Install optional dependencies (choose one):
      • Interactive selection: php artisan pdf-studio:install
      • Install everything: php artisan pdf-studio:install --all

    Manual Dependency Installation

    If you prefer to manage dependencies manually via Composer:

    • Chromium driver: composer require spatie/browsershot ^5.2
    • dompdf driver: composer require dompdf/dompdf ^2.0|^3.0
    • PDF Manipulation (Merge/Watermark): composer require setasign/fpdi ^2.3
    • AcroForm/Password Protection: composer require mikehaertl/php-pdftk ^4.0
    • Barcodes/QR Codes: composer require picqer/php-barcode-generator or composer require chillerlan/php-qrcode
    composer require sarder/pdfstudio
    php artisan vendor:publish --tag=pdf-studio-config
    php artisan pdf-studio:install