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

Filament Pdf Viewer Laravel Package

joaopaulolndev/filament-pdf-viewer

FilamentPHP PDF viewer for displaying documents in your admin UI. Adds a PdfViewerField for forms and an infolist entry to preview PDFs from database records or direct paths/URLs. Compatible with Laravel 11 and Filament 5.x.

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation Update your composer.json to require the new version with Filament 5.3+:

    composer require joaopaulolndev/filament-pdf-viewer:^3.0
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="JoaopauloLndev\FilamentPdfViewer\FilamentPdfViewerServiceProvider"
    
  2. Basic Setup Register the package in your AppServiceProvider or a dedicated service provider:

    FilamentPdfViewer::register();
    

    Note: Ensure your filament/filament package is updated to ^5.3 or higher.

  3. First Use Case: Displaying a PDF in a Resource Add the HasPdfViewer trait to your resource class:

    use JoaopauloLndev\FilamentPdfViewer\Traits\HasPdfViewer;
    
    class MyResource extends Resource
    {
        use HasPdfViewer;
    
        // ...
    }
    

    Define the PDF column in your table:

    public static function table(Table $table): Table
    {
        $table
            ->columns([
                // ...
                Tables\Columns\PdfViewerColumn::make('pdf_column_name'),
            ]);
    }
    
  4. Configuring the Viewer Check the published config at config/filament-pdf-viewer.php for default settings like:

    • Default viewer width/height.
    • Allowed file types.
    • Embed options (e.g., toolbar, search).

Implementation Patterns

Common Workflows

  1. Embedding PDFs in Tables Use PdfViewerColumn for inline preview:

    PdfViewerColumn::make('document')
        ->width('100%')
        ->height('500px')
        ->embed()
        ->label('Document Preview'),
    
  2. Standalone PDF Viewer in Pages Create a custom page with the viewer (ensure Filament ^5.3 compatibility):

    use JoaopauloLndev\FilamentPdfViewer\Widgets\PdfViewer;
    
    class DocumentPage extends Page
    {
        public function mount()
        {
            $this->pdfData = $this->getPdfData(); // Fetch PDF from DB/storage
        }
    
        public function getPdfViewer(): PdfViewer
        {
            return PdfViewer::make()
                ->data($this->pdfData)
                ->width('full')
                ->height('600px');
        }
    }
    
  3. Dynamic PDF Sources Fetch PDFs from:

    • Database (e.g., Storage::disk('public')->url($record->pdf_path)).
    • External URLs (validate with ->allowExternalUrls(true)).
    • Base64-encoded data (pass directly to ->data()).
  4. Integration with Forms Use PdfViewer in a form tab for uploads/previews:

    use JoaopauloLndev\FilamentPdfViewer\Widgets\PdfViewer;
    
    PdfViewer::make('pdf_preview')
        ->data($this->record->pdf_data)
        ->hiddenLabel()
        ->required(false),
    

Advanced Patterns

  1. Customizing the Viewer Extend the default viewer with JS/CSS:

    PdfViewer::make()
        ->extraAttributes(['class' => 'custom-pdf-viewer'])
        ->extraJs('
            document.addEventListener("DOMContentLoaded", function() {
                console.log("PDF viewer loaded!");
            });
        '),
    
  2. Batch Actions Add a bulk PDF download/action:

    use JoaopauloLndev\FilamentPdfViewer\Actions\DownloadPdfAction;
    
    public static function table(Table $table): Table
    {
        $table
            ->actions([
                DownloadPdfAction::make(),
            ]);
    }
    
  3. Caching PDFs Cache rendered PDFs for performance:

    use JoaopauloLndev\FilamentPdfViewer\Facades\PdfViewer;
    
    $cachedPdf = PdfViewer::cache($pdfData, 'pdf_cache_key', now()->addHours(1));
    
  4. Localization Override labels in your resource:

    PdfViewerColumn::make('document')
        ->label(__('filament-pdf-viewer::pdf.preview')),
    

Gotchas and Tips

Common Pitfalls

  1. Filament Version Mismatch

    • Error: Class 'Filament\Resources\Pages\PageConfiguration' not found
    • Fix: Update filament/filament to ^5.3 or higher:
      composer require filament/filament:^5.3
      
  2. CORS Issues with External URLs

    • Ensure your server allows CORS for external PDF sources.
    • Use ->allowExternalUrls(true) but validate URLs server-side to avoid XSS.
  3. Large PDFs Breaking Layouts

    • Set explicit width/height to prevent overflow:
      ->width('800px')->height('600px')
      
    • Use ->responsive() for adaptive sizing.
  4. Base64 Data Size Limits

    • Large base64 strings may cause memory issues. Stream data or compress first:
      $compressedData = gzcompress($base64Data);
      
  5. Permission Errors

    • Verify storage permissions for PDF files:
      chmod -R 755 storage/app/public
      
    • Use ->storageDisk('s3') for cloud storage.

Debugging Tips

  1. Check Console for Errors

    • Open browser dev tools (F12) to debug PDF.js loading issues.
  2. Log PDF Data

    • Verify data before rendering:
      \Log::debug('PDF Data:', ['data' => $pdfData]);
      
  3. Disable Embed for Testing

    • Use ->embed(false) to debug raw PDF rendering.
  4. Clear Cache

    • After config changes:
      php artisan cache:clear
      php artisan view:clear
      

Extension Points

  1. Custom PDF.js Config Override default PDF.js settings in config/filament-pdf-viewer.php:

    'pdfjs' => [
        'cMapUrl' => 'custom/path/to/cmap/',
        'cMapPacked' => true,
    ],
    
  2. Add Annotations/Tools Extend the viewer with custom buttons:

    ->extraJs('
        PDFViewerApplication.options = {
            ...PDFViewerApplication.options,
            secondaryToolbarButtons: [
                { id: "custom-button", label: "Custom Tool", click: () => alert("Clicked!") }
            ]
        };
    ')
    
  3. Hook into PDF Events Use JavaScript events (e.g., pagesinit, pagechange) for custom logic:

    ->extraJs('
        document.getElementById("pdf-viewer").addEventListener("pagesinit", function() {
            console.log("Pages loaded!");
        });
    ')
    
  4. Proxy External PDFs For security, proxy external URLs through your backend:

    // In your controller
    public function proxyPdf($url)
    {
        return response()->streamDownload(
            file_get_contents($url),
            'document.pdf'
        );
    }
    

    Then use the proxied URL in the viewer.

  5. Fallback for Unsupported Browsers Provide a download link as fallback:

    PdfViewerColumn::make('document')
        ->fallbackAction(
            Actions\Action::make('Download PDF')
                ->url(fn ($record) => route('download.pdf', $record))
        ),
    
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.
bugban/symfony
beyonder-capi/workflow-extensions-bundle
beyonder-capi/job-queue-bundle
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin