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

Pdf Viewer Bundle Laravel Package

anglemx/pdf-viewer-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require anglemx/pdf-viewer-bundle
    

    Enable the bundle in config/bundles.php:

    Angle\PDFViewerBundle\AnglePDFViewerBundle::class => ['all' => true],
    
  2. Configure Routing: Add to config/routes.yaml:

    angle_pdf_viewer:
      resource: "@AnglePDFViewerBundle/Resources/config/routes.yaml"
    
  3. First Use Case: Redirect to the viewer with a PDF path:

    return $this->redirectToRoute('angle_pdf_viewer_view', ['file' => '/path/to/your/file.pdf']);
    

    Or embed in Twig:

    <a href="{{ path('angle_pdf_viewer_view', {'file': '/path/to/file.pdf'}) }}">View PDF</a>
    
  4. Quick Test: Access /_pdf?file=/bundles/anglepdfviewer/vendor/pdfjs/web/compressed.tracemonkey-pldi-09.pdf to verify the bundle works.


Implementation Patterns

Core Workflows

  1. Embedding PDFs in Views: Use Twig to generate links or embed the viewer directly:

    {% embed('angle_pdf_viewer::viewer.html.twig', {
        file: '/path/to/document.pdf',
        width: 800,
        height: 600
    }) %}
    {% endembed %}
    
  2. Dynamic PDF Paths: Pass dynamic paths via controllers or services:

    $pdfPath = $this->getPdfService()->getPath($userId);
    return $this->render('pdf_viewer.html.twig', ['pdf_path' => $pdfPath]);
    
  3. Customizing Viewer Options: Extend the Twig template (viewer.html.twig) to override default PDF.js settings:

    {{ parent() }}
    <script>
        PDFViewerApplication.options = {
            ...PDFViewerApplication.options,
            defaultZoomValue: 1.5,
            disableAutoFetch: true
        };
    </script>
    
  4. Integration with Forms: Use the viewer for previewing uploaded PDFs:

    <form method="post" enctype="multipart/form-data">
        <input type="file" name="pdf_file">
        {% if uploadedPdf %}
            <a href="{{ path('angle_pdf_viewer_view', {'file': uploadedPdf.path}) }}">Preview</a>
        {% endif %}
    </form>
    
  5. API-Driven PDF Delivery: Serve PDFs via API endpoints and pass paths dynamically:

    // Controller
    public function showPdf(UploadedFile $file): Response
    {
        $tempPath = $file->getRealPath();
        return $this->redirectToRoute('angle_pdf_viewer_view', ['file' => $tempPath]);
    }
    

Gotchas and Tips

Pitfalls

  1. File Path Security:

    • Issue: Directly exposing user-uploaded paths can lead to path traversal attacks.
    • Fix: Validate and sanitize paths before passing them to the viewer. Use Symfony’s UrlGenerator or Asset component for trusted paths:
      $safePath = $this->getParameter('kernel.project_dir').'/uploads/'.$userId.'/file.pdf';
      
  2. CORS and External PDFs:

    • Issue: PDF.js may block external PDFs due to CORS restrictions.
    • Fix: Configure CORS headers in your server (e.g., Nginx/Apache) or use a proxy to fetch external PDFs.
  3. PDF.js Version Lock:

    • Issue: The bundle pins PDF.js to v4.0.379, which may lack critical updates.
    • Fix: Fork the bundle to update PDF.js or use a CDN for the latest version:
      <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/4.0.379/pdf.min.js"></script>
      
  4. Twig Template Overrides:

    • Issue: Overriding templates may break if the bundle’s template structure changes.
    • Fix: Use {% extends %} in custom templates to inherit parent functionality:
      {% extends '@AnglePDFViewer/viewer.html.twig' %}
      {% block pdfjs_options %}
          {{ parent() }}
          <script>PDFViewerApplication.options.collab = { enabled: true };</script>
      {% endblock %}
      
  5. Large PDF Performance:

    • Issue: Slow rendering for large PDFs (>50MB).
    • Fix: Configure PDF.js to load pages on demand:
      <script>
          PDFViewerApplication.options.workerSrc = '/path/to/pdf.worker.min.js';
          PDFViewerApplication.options.maxCanvasPixels = 1000 * 1000; // Limit canvas size
      </script>
      

Debugging Tips

  1. Check Browser Console:

    • Errors in pdf.js often appear in the console. Look for PDF.js vX.X.X logs.
  2. Verify File Access:

    • Ensure the PDF file is readable by the web server. Test with:
      curl -I http://localhost/path/to/file.pdf
      
  3. Disable Cache:

    • Add query strings to bypass cached PDF.js files during development:
      <script src="{{ asset('bundles/anglepdfviewer/pdf.js?v='~now()) }}"></script>
      
  4. Log Routes:

    • Confirm the route is loaded:
      php bin/console debug:router | grep angle_pdf_viewer
      

Extension Points

  1. Custom PDF.js Build:

    • Replace the bundled PDF.js by overriding the asset path in config/packages/angle_pdf_viewer.yaml:
      angle_pdf_viewer:
          pdfjs_path: '/custom/path/to/pdf.js'
      
  2. Add Annotations:

    • Extend the viewer to support annotations using PDF.js plugins:
      <script src="{{ asset('bundles/anglepdfviewer/pdfjs-plugin-annotations.js') }}"></script>
      <script>
          PDFViewerApplication.options.plugins = [new PDFAnnotations()];
      </script>
      
  3. Authentication:

    • Protect the route with Symfony’s security:
      # config/routes.yaml
      angle_pdf_viewer:
          resource: "@AnglePDFViewerBundle/Resources/config/routes.yaml"
          options:
              expose: true
      
      // src/Security/Voter/PdfViewerVoter.php
      public function supportsAttribute($attribute): bool
      {
          return $attribute === 'VIEW_PDF';
      }
      
  4. Event Listeners:

    • Hook into PDF loading events (if the bundle exposes them) to log usage or validate files:
      // src/EventListener/PdfViewerListener.php
      public function onPdfView(PdfViewEvent $event)
      {
          if (!$this->isValidPath($event->getPath())) {
              throw new \RuntimeException('Invalid PDF path');
          }
      }
      
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity