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

Pdfjs Bundle Laravel Package

cubemage/pdfjs-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require cubemage/pdfjs-bundle
    

    Register the bundle in config/bundles.php:

    return [
        // ...
        CubeMage\PdfJsBundle\PdfJsBundle::class => ['all' => true],
    ];
    
  2. First Use Case: Embed a PDF viewer in a Twig template:

    {{ pdfjs_viewer('path/to/your/document.pdf') }}
    

    This renders a self-contained PDF.js viewer with the specified PDF.

  3. Where to Look First:

    • Twig Functions: Check {{ pdfjs_viewer() }} and {{ pdfjs_form() }} in the README.
    • Assets: The bundle uses Symfony’s assets component. Verify public/pdfjs/ exists after installation.
    • Configuration: Defaults are minimal; check config/packages/cubemage_pdfjs.yaml if customization is needed.

Implementation Patterns

Core Workflows

  1. Basic PDF Rendering:

    {% set pdfPath = app.request.get('file') %}
    {{ pdfjs_viewer(pdfPath, {
        'width': '800px',
        'height': '600px',
        'initialPage': 1
    }) }}
    
    • Pass a file path (absolute or relative to public/) or a URL.
    • Customize viewer dimensions, initial page, and other PDF.js options via associative array.
  2. Handling PDF Forms:

    {{ pdfjs_form('form.pdf', {
        'saveRoute': 'app_pdf_form_save',
        'loadRoute': 'app_pdf_form_load'
    }) }}
    
    • Save Route: Define a Symfony route (e.g., app_pdf_form_save) to handle form submissions:
      # config/routes.yaml
      app_pdf_form_save:
          path: /pdf-form/save
          controller: App\Controller\PdfFormController::save
      
      Controller:
      public function save(Request $request, PdfJsFormHandler $handler): Response
      {
          $data = $request->request->all();
          return $handler->saveFormData('form.pdf', $data);
      }
      
    • Load Route: Optional route to pre-fill form data (e.g., from a database).
  3. Dynamic PDF Sources: Use Twig to generate paths dynamically:

    {% set pdfs = ['doc1.pdf', 'doc2.pdf'] %}
    {% for pdf in pdfs %}
        <div class="pdf-container">
            {{ pdfjs_viewer('uploads/' ~ pdf) }}
        </div>
    {% endfor %}
    
  4. Asset Management:

    • The bundle ships with PDF.js assets in public/pdfjs/. Override them by copying files to this directory or configure a custom path in config/packages/cubemage_pdfjs.yaml:
      cubemage_pdfjs:
          assets_path: '%kernel.project_dir%/public/custom-pdfjs'
      
  5. Integration with Symfony Forms: For server-side form handling, bind the bundle’s form data to a Symfony FormType:

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('field1', TextType::class);
        $builder->add('field2', ChoiceType::class);
    }
    

    Map the submitted data to your entity in the controller.


Gotchas and Tips

Pitfalls

  1. File Paths:

    • Absolute Paths: Use public/-relative paths (e.g., 'uploads/file.pdf') or full URLs (e.g., 'https://example.com/file.pdf'). Avoid server-relative paths (e.g., '/var/www/uploads/file.pdf'), as they break in production.
    • Permissions: Ensure the web server (e.g., www-data) has read access to PDF files.
  2. CORS for Remote PDFs: If loading PDFs from external URLs, configure CORS in your Symfony app or ensure the remote server allows cross-origin requests. PDF.js may block mixed-content (HTTP PDFs on HTTPS pages).

  3. Form Data Serialization:

    • The bundle sends form data as application/x-www-form-urlencoded. For complex data (e.g., nested arrays), use JSON and decode it in the controller:
      $data = json_decode($request->request->get('data'), true);
      
  4. Asset Versioning:

    • Clear the cache (php bin/console cache:clear) if you update PDF.js assets manually. The bundle uses Symfony’s asset versioning, so changes to public/pdfjs/ may not reflect without a cache clear.
  5. PDF.js Configuration:

    • Customize PDF.js behavior by extending the bundle’s default config. Override the pdfjs_config in Twig:
      {{ pdfjs_viewer('file.pdf', {
          'pdfjsConfig': {
              'cMapUrl': 'custom-cmap/',
              'cMapPacked': true
          }
      }) }}
      

Debugging

  1. Console Errors: Check the browser’s Console (F12) for PDF.js errors (e.g., Failed to load PDF). Common causes:

    • Invalid file paths.
    • Missing PDF.js dependencies (ensure public/pdfjs/ is intact).
  2. Network Tab: Verify the PDF file loads correctly (status 200). For remote files, check CORS headers.

  3. Symfony Logs: Enable debug mode (APP_DEBUG=true) to log form submission issues:

    // config/packages/dev/monolog.yaml
    monolog:
        handlers:
            main:
                level: debug
    

Tips

  1. Lazy Loading: Improve performance by lazy-loading the PDF.js viewer:

    <div class="pdf-viewer" data-pdf="{{ asset('uploads/file.pdf') }}">
        {# Loaded via JavaScript #}
    </div>
    

    Use the bundle’s Twig function in JavaScript:

    document.querySelector('.pdf-viewer').innerHTML = pdfjsViewerHtml;
    
  2. Custom Styling: Override the default viewer styles by targeting the generated div.pdfjs-viewer class. Example:

    .pdfjs-viewer {
        border: 1px solid #ccc;
        margin: 1rem 0;
    }
    
  3. Server-Side PDF Processing: Combine with libraries like setasign/fpdf or spipu/html2pdf to generate PDFs dynamically before rendering with PDF.js.

  4. Extension Points:

    • Custom Form Handlers: Extend the PdfJsFormHandler service to add validation or business logic:
      // services.yaml
      services:
          App\Service\CustomPdfFormHandler:
              decorates: 'cubemage_pdfjs.form_handler'
              arguments: ['@.inner']
      
    • Event Listeners: Listen for form submissions via Symfony events (e.g., KernelEvents::VIEW).
  5. Testing: Use Symfony’s WebTestCase to test PDF rendering:

    public function testPdfViewer()
    {
        $client = static::createClient();
        $client->request('GET', '/page-with-pdf');
        $this->assertSelectorTextContains('div.pdfjs-viewer', 'PDF.js');
    }
    
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.
croct/coding-standard
croct/plug-php
nqxcode/phpmorphy
boundwize/pyrameter
testo/facade
develia/commons
dmstr/symfony-system-resources-bundle
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
renatomarinho/laravel-page-speed
develia/geo-bundle
austinheap/laravel-database-encryption
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme