### Installation and Setup Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/docs/index.html Instructions for installing PDF Studio via Composer and setting up its features. ```APIDOC ## Installation and Setup ### Composer Installation Install the package using Composer: ```bash $ composer require sarder/pdfstudio ``` ### Feature Installation Run the install command to select features: ```bash $ php artisan pdf-studio:install ``` **Available Features:** - Chromium PDF driver - Dompdf PDF driver - PDF manipulation - Barcodes & QR codes ``` -------------------------------- ### Basic PDF Generation Examples Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/docs/index.html Provides simple examples of generating PDFs directly from controllers using the fluent API. ```APIDOC ## Basic PDF Generation ### Description Generate PDFs with just a few lines of code. The fluent API simplifies the process of creating PDFs from your application's views. ### Download PDF Generate and download a PDF directly from a controller: ```php return Pdf::view('invoices.show') ->data(['invoice' => $invoice]) ->download('invoice.pdf'); ``` ### Save PDF to Cloud Storage Render a PDF using a specific driver and save it to cloud storage (e.g., S3): ```php Pdf::view('reports.quarterly') ->driver('chromium') ->format('A4') ->save('reports/q4.pdf', 's3'); ``` ### Asynchronous PDF Rendering Dispatch PDF rendering jobs to background workers for handling heavy loads: ```php RenderPdfJob::dispatch( view: 'invoices.show', data: $invoice->toArray(), outputPath: 'inv-001.pdf', disk: 's3' ); ``` ``` -------------------------------- ### Install PDF Studio Drivers Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/README.md Commands to install necessary dependencies for specific PDF rendering engines via Composer. ```bash # Chromium (recommended for TailwindCSS) composer require spatie/browsershot # dompdf (zero external dependencies) composer require dompdf/dompdf ``` -------------------------------- ### Install PDF Studio via Composer Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/docs/user-guide.html Commands to install the package and publish necessary configuration and migration files for Laravel projects. ```bash composer require sarder/pdfstudio php artisan vendor:publish --tag=pdf-studio-config php artisan vendor:publish --tag=pdf-studio-migrations php artisan migrate php artisan pdf-studio:install ``` -------------------------------- ### Install PDF Studio using Composer and Artisan Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/docs/index.html Install the PDF Studio package via Composer and then run the interactive Artisan command to select desired features. This method ensures a bloat-free installation tailored to your needs. ```bash $ composer require sarder/pdfstudio $ php artisan pdf-studio:install ``` -------------------------------- ### Install PDF Studio Dependencies Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/README.md Install optional dependencies for PDF Studio interactively or all at once. The command automatically skips already installed packages and provides Composer output. It also reminds the user about missing extensions like `imagick`. ```bash # Interactive — choose which features to install php artisan pdf-studio:install # Install everything php artisan pdf-studio:install --all ``` -------------------------------- ### Driver Switching Example Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/docs/index.html Demonstrates how to switch between different PDF rendering drivers within the PDF Studio library. ```APIDOC ## Driver Switching ### Description PDF Studio supports multiple rendering engines, allowing you to switch drivers on a per-render basis with a single method call. ### Drivers - Chromium - Dompdf - wkhtmltopdf - Gotenberg - WeasyPrint - Cloudflare ### Usage Examples ```php // Render using the Chromium driver and download Pdf::view('invoice') ->driver('chromium') ->download(); // Render using the Dompdf driver and save to a file Pdf::view('invoice') ->driver('dompdf') ->save('inv.pdf'); // Render using the Gotenberg driver and stream the output Pdf::view('invoice') ->driver('gotenberg') ->stream(); ``` ``` -------------------------------- ### Install PDF Studio via Composer Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/docs/compare.html Commands to install the PDF Studio package into a Laravel project and run the necessary installation command. This requires a PHP environment with Composer installed. ```bash composer require sarder/pdfstudio php artisan pdf-studio:install ``` -------------------------------- ### Render PDFs with Drivers Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/README.md Examples of rendering PDFs using different drivers, including per-render switching and advanced rendering options. ```php Pdf::view('report')->driver('dompdf')->download('report.pdf'); Pdf::view('report')->driver('cloudflare')->download('report.pdf'); Pdf::view('reports.quarterly') ->driver('chromium') ->pageRanges('1-3') ->scale(0.95) ->download('quarterly-report.pdf'); ``` -------------------------------- ### Install PDF Studio Optional Dependencies Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/README.md Installs optional dependencies for PDF Studio, such as drivers for PDF rendering or packages for PDF manipulation. The interactive mode allows selecting specific features. ```bash php artisan pdf-studio:install php artisan pdf-studio:install --all ``` -------------------------------- ### Install Individual PDF Studio Dependencies Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/README.md Installs specific optional dependencies for PDF Studio individually using Composer. This allows for granular control over which features are enabled. ```bash composer require spatie/browsershot # Chromium PDF driver composer require dompdf/dompdf # Dompdf PDF driver composer require setasign/fpdi # Merge, watermark, split PDFs composer require mikehaertl/php-pdftk # AcroForm fill, password protection composer require picqer/php-barcode-generator # @barcode Blade directive composer require chillerlan/php-qrcode # @qrcode Blade directive ``` -------------------------------- ### Configure PDF Studio Drivers Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/README.md Configuration examples for setting the default driver and specific settings for remote or binary-based rendering engines. ```php // config/pdf-studio.php 'default_driver' => 'chromium'; 'drivers' => [ 'cloudflare' => [ 'account_id' => env('PDF_STUDIO_CLOUDFLARE_ACCOUNT_ID'), 'api_token' => env('PDF_STUDIO_CLOUDFLARE_API_TOKEN'), ], 'gotenberg' => [ 'url' => env('PDF_STUDIO_GOTENBERG_URL', 'http://127.0.0.1:3000'), ], 'weasyprint' => [ 'binary' => env('PDF_STUDIO_WEASYPRINT_BINARY', 'weasyprint'), ], ]; ``` -------------------------------- ### Install PDF Studio Drivers Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/docs/user-guide.html Commands to install various PDF rendering engines supported by the package. Choose the driver based on your requirements for CSS support, PDF/A compliance, or system dependencies. ```bash # Chromium (recommended for TailwindCSS) composer require spatie/browsershot # dompdf (no external binaries needed) composer require dompdf/dompdf # Gotenberg (Docker-based, supports PDF/A) docker run --rm -p 3000:3000 gotenberg/gotenberg:8 # WeasyPrint (Python-based, supports PDF/A, PDF/UA, attachments) pip install weasyprint ``` -------------------------------- ### SaaS Hosted Rendering API Endpoints (Bash) Source: https://context7.com/sarderiftekhar/pdf-studio/llms.txt Provides examples of using cURL to interact with the SaaS hosted PDF rendering API. It covers synchronous rendering with HTML or Blade views, asynchronous rendering with job queuing, and polling job status. Authentication is done via Bearer tokens. The API endpoints are for POST requests to '/api/pdf-studio/render' and '/api/pdf-studio/render/async', and GET requests to '/api/pdf-studio/render/{job-uuid}'. ```bash # Sync render - immediate PDF response curl -X POST https://yourapp.com/api/pdf-studio/render \ -H "Authorization: Bearer sk_abc123..." \ -H "Content-Type: application/json" \ -d '{ "html": "

Invoice #42

", "filename": "invoice-42.pdf" }' # Render with Blade view and options curl -X POST https://yourapp.com/api/pdf-studio/render \ -H "Authorization: Bearer sk_abc123..." \ -H "Content-Type: application/json" \ -d '{ "view": "pdf.invoice", "data": {"invoice": {"id": 42, "total": 1200}}, "options": {"format": "A4", "landscape": false}, "driver": "chromium" }' # Async render - queue job curl -X POST https://yourapp.com/api/pdf-studio/render/async \ -H "Authorization: Bearer sk_abc123..." \ -H "Content-Type: application/json" \ -d '{ "view": "pdf.report", "data": {"month": "January"}, "output_path": "reports/jan.pdf", "output_disk": "s3" }' # Poll job status curl https://yourapp.com/api/pdf-studio/render/{job-uuid} \ -H "Authorization: Bearer sk_abc123..." # Response: {"id": "...", "status": "completed", "bytes": 14200, "render_time_ms": 312.5} ``` -------------------------------- ### Clone Repository and Install Dependencies (Bash) Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/CONTRIBUTING.md This snippet shows how to clone the PDF Studio repository and install its PHP dependencies using Composer. Ensure you have Git and Composer installed locally. ```bash git clone https://github.com/sarderiftekhar/pdf-studio.git cd pdf-studio composer install ``` -------------------------------- ### Install PDF Studio via Composer Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/README.md Installs the PDF Studio package using Composer. This is the primary step for integrating the package into a Laravel project. ```bash composer require sarder/pdfstudio ``` -------------------------------- ### PDF Manipulation Example Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/docs/index.html Illustrates how to perform PDF manipulation tasks such as merging, watermarking, and protecting documents. ```APIDOC ## PDF Manipulation ### Description Beyond rendering, PDF Studio offers comprehensive control for manipulating PDF documents, including merging, splitting, watermarking, and protection. ### Features - Merge documents - Split documents - Add watermarks - Password-protect PDFs - Fill forms - Embed files - Generate thumbnails ### Usage Example ```php // Merge documents, add a watermark, and protect with a password, then download Pdf::merge([ storage_path('cover.pdf'), Pdf::view('report')->render(), ]) ->watermark('CONFIDENTIAL') ->protect('secret') ->download('final.pdf'); ``` ``` -------------------------------- ### Generate high-fidelity PDFs with Chromium Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/docs/driver-guide.md Demonstrates how to render a view using the Chromium driver with explicit wait conditions to ensure fonts and network resources are fully loaded before generation. ```php Pdf::view('reports.full') ->driver('chromium') ->waitForFonts() ->waitForNetworkIdle() ->waitForSelector('#ready', ['visible' => true]) ->download('report.pdf'); ``` -------------------------------- ### Manage PDF Studio with Artisan Commands (Bash) Source: https://context7.com/sarderiftekhar/pdf-studio/llms.txt This section outlines the available Artisan commands for managing PDF Studio. These commands facilitate installation, template listing, cache clearing, diagnostics, and publishing configuration and migration files. ```bash # Run installation wizard php artisan pdf-studio:install php artisan pdf-studio:install --all # Install all optional dependencies # List registered templates php artisan pdf-studio:templates # Clear caches php artisan pdf-studio:cache-clear # Clear CSS cache php artisan pdf-studio:cache-clear --render # Clear render cache # Run diagnostics php artisan pdf-studio:doctor # Publish config and migrations php artisan vendor:publish --tag=pdf-studio-config php artisan vendor:publish --tag=pdf-studio-migrations ``` -------------------------------- ### Test PDF Operations with PdfFake Source: https://context7.com/sarderiftekhar/pdf-studio/llms.txt Provides examples of using the PdfFake facade to assert PDF generation, storage, merging, security features, and metadata without performing actual rendering. ```php use PdfStudio\Laravel\Facades\Pdf; it('generates an invoice PDF', function () { $fake = Pdf::fake(); $controller = new InvoiceController(); $controller->download($invoice); $fake->assertRendered(); $fake->assertDownloaded('invoice.pdf'); }); it('merges multiple PDFs', function () { $fake = Pdf::fake(); Pdf::merge(['/path/to/doc1.pdf', '/path/to/doc2.pdf']); $fake->assertMerged(); }); it('applies watermark and protection', function () { $fake = Pdf::fake(); Pdf::html('

Secret

') ->watermark('CONFIDENTIAL') ->protect(ownerPassword: 'secret') ->render(); $fake->assertWatermarked(); $fake->assertProtected(); }); ``` -------------------------------- ### Render PDFs via remote Gotenberg infrastructure Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/docs/driver-guide.md Shows the configuration for offloading PDF generation to a self-hosted Gotenberg service, including network idle and delay settings for stability. ```php Pdf::view('reports.full') ->driver('gotenberg') ->waitForNetworkIdle() ->waitDelay(500) ->download('report.pdf'); ``` -------------------------------- ### Synchronous PDF Download in Vue 3 (Composition API) Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/docs/user-guide.html A Vue 3 Composition API example demonstrating how to trigger a synchronous PDF download. It uses the `fetch` API to call a backend proxy endpoint, which in turn generates and returns the PDF. The downloaded PDF is then saved to the user's device. It's crucial to proxy API requests to keep keys server-side. Dependencies: Vue 3, fetch API. ```javascript import { ref } from 'vue' export function usePdfRender() { const status = ref('idle') // idle | pending | completed | failed const jobId = ref(null) const error = ref(null) async function startRender(payload) { status.value = 'pending' error.value = null // Step 1: dispatch async job via your backend proxy const res = await fetch('/api/pdf/async', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload), }) const { id } = await res.json() jobId.value = id // Step 2: poll until done const interval = setInterval(async () => { const poll = await fetch(`/api/pdf/status/${id}`) const job = await poll.json() if (job.status === 'completed') { status.value = 'completed' clearInterval(interval) } else if (job.status === 'failed') { status.value = 'failed' error.value = job.error clearInterval(interval) } }, 2000) } return { status, jobId, error, startRender } } ``` -------------------------------- ### Verify Driver Configuration with Artisan Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/docs/driver-guide.md Use the PDF Studio CLI tool to validate driver connectivity and environment configuration. This command helps diagnose issues with remote services like Gotenberg or Cloudflare. ```bash php artisan pdf-studio:doctor php artisan pdf-studio:doctor --driver=gotenberg ``` -------------------------------- ### Interact with PDF Studio API Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/docs/index.html Examples of using cURL to trigger PDF rendering and retrieve analytics data via the built-in SaaS API. ```bash curl -X POST /api/pdf-studio/render \ -H "Authorization: Bearer sk_..." \ -d '{"view":"invoice","data":{"id":42}}' curl /api/pdf-studio/analytics ``` -------------------------------- ### Verify PDF Studio Configuration with Doctor Command (Bash) Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/docs/driver-guide.md Runs the 'pdf-studio:doctor' artisan command to verify the PDF Studio environment. This command checks for binary availability, temp storage access, font configuration, default driver selection, Cloudflare/Gotenberg setup, and asset policy configuration. It is a crucial step for troubleshooting and ensuring proper setup. ```bash php artisan pdf-studio:doctor ``` -------------------------------- ### Compose Large Report with PDF Studio (PHP) Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/docs/driver-guide.md Composes a large report by combining multiple views ('reports.cover', 'reports.summary', 'reports.detail') using the PDF Studio library. It specifies the 'cloudflare' driver for processing. Ensure the PDF Studio library is installed and configured. ```php Pdf::compose([ ['view' => 'reports.cover'], ['view' => 'reports.summary'], ['view' => 'reports.detail'], ], driver: 'cloudflare'); ``` -------------------------------- ### Use PDF Studio Fluent API Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/docs/user-guide.html Demonstrates how to use the fluent API to render a registered template and return a download response. ```php Pdf::template('invoice') ->data(['id' => 123]) ->download('invoice-123.pdf'); ``` -------------------------------- ### Render PDFs with Multiple Drivers Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/docs/index.html Demonstrates how to switch between different rendering engines like Chromium, Dompdf, and Gotenberg using a fluent API. ```php Pdf::view('invoice') ->driver('chromium') ->download(); Pdf::view('invoice') ->driver('dompdf') ->save('inv.pdf'); Pdf::view('invoice') ->driver('gotenberg') ->stream(); ``` -------------------------------- ### Generate PDFs using the Pdf Facade Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/docs/user-guide.html Demonstrates how to use the Pdf facade to download, stream, save, or render PDFs from views or raw HTML strings. ```php use PdfStudio\Laravel\Facades\Pdf; // Download a PDF immediately return Pdf::view('invoices.show') ->data(['invoice' => $invoice]) ->download('invoice.pdf'); // Stream inline in browser return Pdf::view('reports.quarterly') ->data(['report' => $report]) ->inline('report.pdf'); // Save to Storage (S3, local, etc.) Pdf::view('statements.monthly') ->data(['account' => $account]) ->driver('chromium') ->format('A4') ->landscape() ->save('statements/2024-01.pdf', 's3'); // Render from raw HTML $result = Pdf::html('

Hello

')->render(); echo $result->bytes; echo $result->renderTimeMs; ``` -------------------------------- ### GET /api/pdf-studio/render/{job-uuid} Source: https://context7.com/sarderiftekhar/pdf-studio/llms.txt Retrieves the status and metadata of a previously submitted asynchronous rendering job. ```APIDOC ## GET /api/pdf-studio/render/{job-uuid} ### Description Checks the current status of an asynchronous PDF rendering job. ### Method GET ### Endpoint /api/pdf-studio/render/{job-uuid} ### Parameters #### Path Parameters - **job-uuid** (string) - Required - The unique ID returned by the async render endpoint. ### Response #### Success Response (200) - **id** (string) - Job ID. - **status** (string) - Current status (e.g., pending, completed, failed). - **bytes** (integer) - File size in bytes. - **render_time_ms** (float) - Time taken to render in milliseconds. #### Response Example { "id": "550e8400-e29b-41d4-a716-446655440000", "status": "completed", "bytes": 14200, "render_time_ms": 312.5 } ``` -------------------------------- ### Publish and Run PDF Studio Migrations Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/README.md Publishes and runs database migrations for PDF Studio, which are necessary for Pro or SaaS features. This sets up the required database tables. ```bash php artisan vendor:publish --tag=pdf-studio-migrations php artisan migrate ``` -------------------------------- ### Usage Metering - Hook Billing Provider Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/docs/user-guide.html Example of how to hook into the BillableEvent to send usage data to a billing provider like Stripe. ```APIDOC ## Usage Metering - Hook Billing Provider (PHP Example) ### Description Example of how to hook into the BillableEvent to send usage data to a billing provider like Stripe. ### Method N/A (This is an event listener setup) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php use PdfStudio\Laravel\Events\BillableEvent; use Illuminate\Support\Facades\Event; // AppServiceProvider::boot() Event::listen(BillableEvent::class, function (BillableEvent $event) { // $event->workspaceId // $event->eventType ('render') // $event->quantity (1 per render) // $event->metadata (['bytes' => ..., 'render_time_ms' => ...]) // Example for Stripe Stripe::meterEvent('pdf_render', [ 'stripe_customer_id' => $workspace->stripe_id, 'value' => $event->quantity, ]); }); ``` ### Response #### Success Response N/A (This is an event listener setup) #### Response Example N/A ``` -------------------------------- ### Async and Batch PDF Rendering Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/README.md Methods for dispatching PDF generation to background queues, batch processing, and composing multiple sections into a single document. ```php use PdfStudio\Laravel\Jobs\RenderPdfJob; RenderPdfJob::dispatch(view: 'invoices.show', outputPath: 'invoices/inv-001.pdf'); Pdf::batch([ ['view' => 'invoices.show', 'outputPath' => 'inv-1.pdf'], ['view' => 'invoices.show', 'outputPath' => 'inv-2.pdf'] ]); $result = Pdf::compose([ ['html' => '

Cover

'], ['view' => 'pdf.invoice'] ], driver: 'chromium'); ``` -------------------------------- ### Shell Commands for Deployment and Version Control Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/docs/plans/2026-03-08-v2.1-implementation-plan.md Utility commands for downloading external dependencies and committing feature changes to the repository. ```bash curl -o resources/css/bootstrap.min.css https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css git add src/Pipeline/BootstrapInjector.php resources/css/bootstrap.min.css tests/Unit/Pipeline/BootstrapInjectorTest.php git commit -m "feat(bootstrap): add BootstrapInjector pipeline step with bundled CSS" ``` -------------------------------- ### Migrate from barryvdh/laravel-snappy to PDF Studio Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/docs/compare.html This snippet demonstrates migrating PDF generation code from barryvdh/laravel-snappy to PDF Studio. It shows the updated facade and method calls for loading views and downloading PDFs, including passing data. ```php Before use Barryvdh\Snappy\Facades\SnappyPdf; return SnappyPdf::loadView('report', $data) ->download('report.pdf'); After (PDF Studio) use PdfStudio\Laravel\Facades\Pdf; return Pdf::view('report') ->data($data) ->download('report.pdf'); ``` -------------------------------- ### Switch Rendering Drivers in PDF Studio Source: https://context7.com/sarderiftekhar/pdf-studio/llms.txt Demonstrates how to switch between different rendering drivers like Chromium, dompdf, wkhtmltopdf, Gotenberg, Cloudflare, and WeasyPrint based on specific requirements for CSS fidelity, dependencies, or managed rendering. ```php use PdfStudio\Laravel\Facades\Pdf; // Chromium driver (default) - full CSS/TailwindCSS support Pdf::view('report') ->driver('chromium') ->download('report.pdf'); // dompdf driver - no external dependencies Pdf::view('simple-invoice') ->driver('dompdf') ->download('invoice.pdf'); // wkhtmltopdf driver - good CSS without Node.js Pdf::view('certificate') ->driver('wkhtmltopdf') ->download('certificate.pdf'); // Gotenberg driver - self-hosted remote rendering Pdf::view('report') ->driver('gotenberg') ->download('report.pdf'); // Cloudflare Browser Rendering - managed cloud rendering Pdf::view('report') ->driver('cloudflare') ->download('report.pdf'); // WeasyPrint driver - print-native with PDF variants Pdf::view('document') ->driver('weasyprint') ->pdfVariant('pdf/a-3u') ->download('document.pdf'); ``` -------------------------------- ### Create archival-grade PDF/A documents Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/docs/driver-guide.md Configures the WeasyPrint driver to generate PDF/A-3u compliant documents with custom metadata for long-term archival purposes. ```php Pdf::view('reports.archive') ->driver('weasyprint') ->metadata(['title' => 'Archive Copy']) ->pdfVariant('pdf/a-3u') ->download('archive.pdf'); ``` -------------------------------- ### Manage Workspaces and Access Control Source: https://context7.com/sarderiftekhar/pdf-studio/llms.txt Shows how to create workspaces, assign member roles, perform programmatic access checks, and protect routes using middleware. ```php use PdfStudio\Laravel\Models\Workspace; use PdfStudio\Laravel\Models\WorkspaceMember; use PdfStudio\Laravel\Models\Project; use PdfStudio\Laravel\Contracts\AccessControlContract; // Create workspace $workspace = Workspace::create(['name' => 'Acme Corp', 'slug' => 'acme']); // Add members with roles: owner, admin, member, viewer WorkspaceMember::create([ 'workspace_id' => $workspace->id, 'user_id' => $user->id, 'role' => 'admin', ]); // Check access programmatically $access = app(AccessControlContract::class); $access->canAccess($user->id, $workspace->id); $access->canManage($user->id, $workspace->id); // Protect routes with middleware Route::middleware('pdf-studio.workspace')->group(function () { Route::get('/workspaces/{workspace}/templates', [TemplateController::class, 'index']); }); ``` -------------------------------- ### Manage and inspect large PDF documents Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/docs/driver-guide.md Provides methods for validating, inspecting, and chunking large PDF documents, including support for both raw content and file-based operations. ```php $pdf = Pdf::view('reports.annual') ->driver('gotenberg') ->render(); $looksValid = Pdf::isPdf($pdf->content()); $summary = Pdf::inspectPdf($pdf->content()); Pdf::assertPdf($pdf->content(), 'rendered annual report'); $pageCount = Pdf::pageCount($pdf->content()); $ranges = Pdf::chunkRanges($pdf->content(), 50); $chunks = Pdf::chunk($pdf->content(), 50); $storedLooksValid = Pdf::isPdfFile(storage_path('app/reports/annual.pdf')); $storedSummary = Pdf::inspectPdfFile(storage_path('app/reports/annual.pdf')); Pdf::assertPdfFile(storage_path('app/reports/annual.pdf'), 'stored annual report'); ``` -------------------------------- ### Workspace Member Roles Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/docs/user-guide.html Defines the roles available for workspace members and their associated permissions. Includes examples of creating workspaces, adding members with roles, and checking permissions programmatically. ```APIDOC ## Role Hierarchy ### Description Defines the roles available for workspace members and their associated permissions. ### Roles | Role | canAccess | canManage | Description | |--------|-----------|-----------|------------------------------| | `owner` | ✅ | ✅ | Full control | | `admin` | ✅ | ✅ | Manage members and settings | | `member` | ✅ | ❌ | View and render | | `viewer` | ✅ | ❌ | View only | ### Usage Examples (PHP) #### Create a workspace and add a member ```php use PdfStudio\Laravel\Models\Workspace; use PdfStudio\Laravel\Models\WorkspaceMember; // Create a workspace $workspace = Workspace::create([ 'name' => 'Acme Corp', 'slug' => 'acme', ]); // Add a member with a role WorkspaceMember::create([ 'workspace_id' => $workspace->id, 'user_id' => $user->id, 'role' => 'admin', ]); ``` #### Check permissions programmatically ```php use PdfStudio\Laravel\Contracts\AccessControlContract; $access = app(AccessControlContract::class); $access->canAccess($user->id, $workspace->id); $access->canManage($user->id, $workspace->id); ``` #### Protect routes ```php use Illuminate\Support\Facades\Route; Route::middleware('pdf-studio.workspace')->group(function () { Route::get('/workspaces/{workspace}/templates', ...); }); ``` ``` -------------------------------- ### Configure advanced Chromium and driver-specific options Source: https://context7.com/sarderiftekhar/pdf-studio/llms.txt Explains how to apply advanced rendering configurations such as wait strategies, accessibility tagging, metadata, and PDF/A archiving for specific drivers. ```php use PdfStudio\Laravel\Facades\Pdf; // Full-featured render with all options Pdf::view('reports.quarterly') ->driver('chromium') ->data(['report' => $report]) ->pageRanges('1-3,5') // Only include specific pages ->preferCssPageSize() // Use @page CSS rules for sizing ->scale(0.95) // Scale content to 95% ->waitForFonts() // Wait for web fonts to load ->waitForNetworkIdle() // Wait for network activity to stop ->waitDelay(750) // Additional wait in milliseconds ->waitForSelector('#report-ready', ['visible' => true]) // Wait for element ->waitForFunction('window.chartLoaded === true') // Wait for JS condition ->taggedPdf() // Generate accessible tagged PDF ->outline() // Include document outline/bookmarks ->metadata([ 'title' => 'Q4 2024 Quarterly Report', 'author' => 'Finance Department', 'subject' => 'Financial Analysis', 'keywords' => 'quarterly, finance, 2024', ]) ->download('quarterly-report.pdf'); // PDF/A variant for archival (WeasyPrint driver) Pdf::view('legal.contract') ->driver('weasyprint') ->pdfVariant('pdf/a-3u') ->attachFile(storage_path('app/source-data.csv'), 'source.csv', 'text/csv') ->download('contract-archive.pdf'); ``` -------------------------------- ### Get Usage and Summary Data (PHP) Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/docs/user-guide.html Retrieves usage and summary statistics for a given workspace within a specified date range. This function is useful for monitoring resource consumption. ```php $records = $meter->getUsage($workspace->id, now()->startOfMonth(), now()->endOfMonth()); $summary = $meter->getSummary($workspace->id, now()->startOfMonth(), now()->endOfMonth()); // → ['render' => 1432] ``` -------------------------------- ### Manage Template Versioning Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/docs/user-guide.html Provides services to snapshot, list, restore, and diff template definitions. Requires database migrations to be executed before use. ```PHP use PdfStudio\Laravel\Contracts\TemplateVersionServiceContract; $versioning = app(TemplateVersionServiceContract::class); $version = $versioning->create( definition: $registry->get('invoice'), author: 'Jane Smith', changeNotes: 'Updated payment section layout', ); $definition = $versioning->restore('invoice', versionNumber: 3); ``` -------------------------------- ### Add Facade Static Method Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/docs/plans/2026-03-08-v2.1-implementation-plan.md Exposes thumbnail generation functionality via the Pdf Facade, allowing static access to file-based thumbnail creation. ```php public static function thumbnailFromFile(string $path, int $page = 1, int $width = 300, string $format = 'png', int $quality = 85): \PdfStudio\Laravel\Thumbnail\ThumbnailResult { $content = file_get_contents($path); if ($content === false) { throw new \PdfStudio\Laravel\Exceptions\RenderException("Cannot read file: {$path}"); } $generator = static::getFacadeApplication()->make(\PdfStudio\Laravel\Thumbnail\ThumbnailGenerator::class); return $generator->generate($content, $page, $width, $format, $quality); } ``` -------------------------------- ### Integrate Billing with BillableEvent Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/README.md This example shows how to listen for the BillableEvent in your AppServiceProvider to integrate with a billing provider like Stripe. It extracts relevant information from the event and uses it to meter usage for a specific workspace. ```php // In AppServiceProvider::boot() use PdfStudio\Laravel\Events\BillableEvent; Event::listen(BillableEvent::class, function (BillableEvent $event) { // $event->workspaceId // $event->eventType (e.g. 'render') // $event->quantity (always 1 per render) // $event->metadata (['bytes' => ..., 'render_time_ms' => ...]) Stripe::meterEvent('pdf_render', [ 'stripe_customer_id' => Workspace::find($event->workspaceId)->stripe_id, 'value' => $event->quantity, ]); }); ``` -------------------------------- ### Switching PDF Rendering Drivers in PHP Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/docs/index.html Illustrates how to dynamically switch between different PDF rendering drivers (Chromium, dompdf, Gotenberg) on a per-render basis using a fluent API in PHP. This allows flexibility in choosing the best engine for specific needs without configuration changes. ```php Pdf::view('report')->driver('chromium')->download('report.pdf'); Pdf::view('report')->driver('dompdf')->download('report.pdf'); Pdf::view('report')->driver('gotenberg')->download('report.pdf'); ``` -------------------------------- ### Apply Code Style with Composer Pint (Bash) Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/CONTRIBUTING.md This command uses Laravel Pint to automatically format the code according to the project's style guide. It's essential for maintaining code consistency. ```bash composer lint ``` -------------------------------- ### Template Versioning Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/docs/user-guide.html Snapshot template definitions, browse history, restore previous versions, and diff changes between versions. Requires migrations. ```APIDOC ## Template Versioning ### Description Snapshot template definitions at any point, browse history, restore previous versions, and diff changes between versions. ### Requirements Run `php artisan vendor:publish --tag=pdf-studio-migrations && php artisan migrate` to enable this feature. ### PHP Usage ```php use PdfStudio\Laravel\Contracts\TemplateVersionServiceContract; $versioning = app(TemplateVersionServiceContract::class); // Save current state as a new version $version = $versioning->create( definition: $registry->get('invoice'), author: 'Jane Smith', changeNotes: 'Updated payment section layout', ); // List history (newest first) $versions = $versioning->list('invoice'); // Restore a specific version to a TemplateDefinition DTO $definition = $versioning->restore('invoice', versionNumber: 3); // See what changed between versions $changes = $versioning->diff('invoice', fromVersion: 2, toVersion: 3); // → ['view', 'default_options'] ``` ``` -------------------------------- ### Run Project Tests Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/README.md Commands to run tests and code analysis for the PDF Studio project. This includes running all tests, performing static analysis with PHPStan, and linting code with Laravel Pint. ```bash composer test # run all tests composer analyse # PHPStan level 6 composer lint # Laravel Pint ``` -------------------------------- ### Rendering PDF via API using cURL Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/docs/index.html Provides an example of how to render a PDF using the PDF Studio API via a cURL request. It includes setting the authorization header, content type, and sending JSON data for view and data parameters. ```bash curl -X POST https://app.com/api/pdf-studio/render \ -H "Authorization: Bearer sk_abc123..." \ -H "Content-Type: application/json" \ -d '{"view": "pdf.invoice", "data": {"id": 42}}' ``` -------------------------------- ### Implement BootstrapInjector Pipeline Step Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/docs/plans/2026-03-08-v2.1-implementation-plan.md Creates a pipeline class that injects minified Bootstrap CSS into the RenderContext. Includes logic to handle file existence and conditional execution based on compiled HTML content. ```php compiledHtml ?? ''; if ($html === '') { return $next($context); } $cssPath = __DIR__.'/../../resources/css/bootstrap.min.css'; if (!file_exists($cssPath)) { return $next($context); } $context->compiledCss = file_get_contents($cssPath); return $next($context); } } ``` -------------------------------- ### Merging PDFs with Page Range Selection in PHP Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/docs/index.html Shows how to merge multiple PDF documents, including dynamically rendered views, with options for page range selection. This example demonstrates combining a cover page, a report view, and an appendix into a single PDF. ```php $merged = Pdf::merge([ storage_path('cover.pdf'), Pdf::view('report')->render(), storage_path('appendix.pdf'), ]); ``` -------------------------------- ### cURL: Render PDF via Hosted Rendering API Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/docs/user-guide.html This example demonstrates how to use the PDF Studio Hosted Rendering API with cURL to generate PDFs. It shows requests for direct HTML rendering and rendering from a Blade view with data and options, including specifying the rendering driver. ```curl curl -X POST https://yourapp.com/api/pdf-studio/render \ -H "Authorization: Bearer sk_abc123..." \ -H "Content-Type: application/json" \ -d '{ "html": "

Invoice #42

", "filename": "invoice-42.pdf" }' # → application/pdf download # With a Blade view, data, and options: curl -X POST .../render \ -d '{ "view": "pdf.invoice", "data": {"invoice": {"id": 42}}, "options": {"format": "A4", "landscape": false}, "driver": "chromium" }' ``` -------------------------------- ### PDF Render Caching with Laravel Source: https://context7.com/sarderiftekhar/pdf-studio/llms.txt Details how to implement caching for rendered PDFs to improve performance by avoiding redundant rendering of identical content. Examples show how to set a cache duration, retrieve cached results, bypass the cache for fresh renders, and clear the cache using Artisan commands. ```php use PdfStudio\Laravel\Facades\Pdf; // Cache for 1 hour (3600 seconds) $result = Pdf::html('

Static Report

') ->cache(3600) ->render(); // Second call returns cached result instantly $result2 = Pdf::html('

Static Report

') ->cache(3600) ->render(); echo $result2->renderTimeMs; // 0 (from cache) // Bypass cache for fresh render $fresh = Pdf::html('

Static Report

') ->cache(3600) ->noCache() ->render(); // Clear render cache via artisan // php artisan pdf-studio:cache-clear --render ``` -------------------------------- ### Download PDFs from Livewire Components (PHP) Source: https://context7.com/sarderiftekhar/pdf-studio/llms.txt Demonstrates how to download PDFs directly from Livewire components using the Pdf::livewireDownload() method. This method ensures a seamless download experience without interfering with Livewire's functionality. It requires the 'pdf-studio/laravel' package and a view file for the PDF content. ```php use PdfStudio\Laravel\Facades\Pdf; // In a Livewire component class InvoiceComponent extends Component { public Invoice $invoice; public function downloadInvoice() { return Pdf::view('invoices.show') ->data(['invoice' => $this->invoice]) ->livewireDownload('invoice.pdf'); } } // Get base64 for embedding in views $result = Pdf::html('

Report

')->render(); $base64 = $result->toBase64(); $dataUri = 'data:application/pdf;base64,' . $base64; ``` -------------------------------- ### Per-Page Header/Footer Control in Laravel Source: https://context7.com/sarderiftekhar/pdf-studio/llms.txt Shows how to precisely control the visibility of headers and footers on specific pages within a generated PDF. Examples include hiding headers on the first page, footers on the last page, showing headers only on designated pages, and excluding headers or footers from particular pages. ```php use PdfStudio\Laravel\Facades\Pdf; // Hide header on first page (cover page) Pdf::view('report') ->data(['report' => $report]) ->headerExceptFirst() ->download('report.pdf'); // Hide footer on last page Pdf::view('document') ->footerExceptLast() ->download('document.pdf'); // Show header only on specific pages Pdf::view('book') ->headerOnPages([2, 3, 4, 5, 6]) // Header on pages 2-6 only ->download('book.pdf'); // Exclude header/footer from specific pages Pdf::view('presentation') ->headerExcludePages([1, 10]) // No header on pages 1 and 10 ->footerExcludePages([1]) // No footer on page 1 ->download('presentation.pdf'); ``` -------------------------------- ### Generate PDF Thumbnails with Laravel Source: https://context7.com/sarderiftekhar/pdf-studio/llms.txt Provides examples for generating thumbnail images from rendered PDFs or existing PDF files using the Pdf Studio Laravel package. It shows how to create thumbnails from views, specify dimensions, format, quality, and page number, and how to access thumbnail properties after generation. ```php use PdfStudio\Laravel\Facades\Pdf; // Generate thumbnail from rendered PDF $thumbnail = Pdf::view('report') ->data(['report' => $report]) ->thumbnail(width: 300, format: 'png', quality: 85, page: 1); // Save thumbnail file_put_contents(storage_path('thumbnails/report.png'), $thumbnail->content()); // Generate thumbnail from existing PDF file $thumbnail = Pdf::thumbnailFromFile( path: storage_path('app/documents/report.pdf'), page: 1, width: 400, format: 'jpg', quality: 90 ); // Access thumbnail properties echo $thumbnail->width; // Actual width echo $thumbnail->height; // Actual height echo $thumbnail->format; // 'png' or 'jpg' echo $thumbnail->bytes; // File size ``` -------------------------------- ### Publish PDF Studio Configuration Source: https://github.com/sarderiftekhar/pdf-studio/blob/main/README.md Publishes the configuration file for PDF Studio, allowing customization of its settings. This command makes the configuration file accessible for modification. ```bash php artisan vendor:publish --tag=pdf-studio-config ```