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

Pdfparser Laravel Package

prinsfrank/pdfparser

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require prinsfrank/pdfparser
    

    Ensure your project meets the PHP 8.2+ requirement.

  2. Basic Text Extraction:

    use PrinsFrank\PdfParser\PdfParser;
    
    $document = (new PdfParser())->parseFile('path/to/file.pdf');
    $text = $document->getText();
    
  3. First Use Case: Extract metadata from a PDF:

    $title = $document->getInformationDictionary()?->getTitle();
    $author = $document->getInformationDictionary()?->getAuthor();
    

Where to Look First

  • README.md: Covers core functionality, installation, and basic usage.
  • Documentation: Focus on the Document class and its methods (getText(), getPages(), getInformationDictionary()).
  • Benchmarks: Compare performance with alternatives in the benchmark repository.

Implementation Patterns

Common Workflows

  1. Batch Processing:

    $parser = new PdfParser();
    $files = glob('path/to/pdf/*.pdf');
    
    foreach ($files as $file) {
        $document = $parser->parseFile($file);
        $text = $document->getText();
        // Process text (e.g., save to DB, search for keywords)
    }
    
  2. Extracting Images:

    foreach ($document->getPages() as $page) {
        foreach ($page->getImages() as $image) {
            $content = $image->getContent();
            $extension = $image->getImageType()?->getFileExtension();
            file_put_contents("images/{$page->getPageNumber()}_{$extension}", $content);
        }
    }
    
  3. Handling Encrypted PDFs:

    $document = (new PdfParser())->parseFile('encrypted.pdf', password: 'user_password');
    
  4. Positioned Text Extraction:

    foreach ($document->getPages() as $page) {
        $textElements = $page->getPositionedTextElements();
        foreach ($textElements as $element) {
            echo "Text: {$element->getText()}, BBox: {$element->getBoundingBox()}\n";
        }
    }
    

Integration Tips

  • Laravel Service Provider: Bind the parser as a singleton for reusable access:

    $this->app->singleton(PdfParser::class, function ($app) {
        return new PdfParser();
    });
    
  • Queue Jobs for Large Files: Use Laravel queues to process large PDFs asynchronously:

    ParsePdfJob::dispatch('path/to/large_file.pdf')->onQueue('pdf-processing');
    
  • Store Extracted Data: Save metadata or text to a database:

    $metadata = [
        'title' => $document->getInformationDictionary()?->getTitle(),
        'author' => $document->getInformationDictionary()?->getAuthor(),
        'text' => $document->getText(),
    ];
    PdfMetadata::create($metadata);
    
  • Custom Decorators: Extend existing decorators (e.g., Page) to add domain-specific logic:

    class CustomPageDecorator extends Page {
        public function getCustomData() {
            // Add logic here
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Memory Usage:

    • Disable useInMemoryStream for large files to reduce memory footprint:
      $document = (new PdfParser())->parseFile('large_file.pdf', useInMemoryStream: false);
      
    • Use useFileCache for string parsing to avoid high memory usage:
      $document = (new PdfParser())->parseString($pdfString, useFileCache: true);
      
  2. Encrypted PDFs:

    • Always specify the password for encrypted files:
      $document = (new PdfParser())->parseFile('encrypted.pdf', password: 'correct_password');
      
    • Debugging: Check CONTRIBUTING.md for encryption-related issues.
  3. Text Extraction Quirks:

    • Subscript/superscript text may not group correctly in older PDFs. Use the improved algorithm in v3.0.0+.
    • Complex layouts (e.g., tables) may require post-processing to reconstruct structure.
  4. Object Retrieval:

    • Objects are zero-indexed. Page 1 in the document is accessed via $document->getPage(0).
    • Type hints are strict. Ensure correct decorator classes are passed:
      $page = $document->getObject(42, Page::class); // Correct
      $page = $document->getObject(42); // May return a generic object
      
  5. Image Handling:

    • Not all XObjects are images. Verify with $image->isImage() before processing.
    • Some images may lack metadata (e.g., getImageType() returns null). Handle gracefully:
      if (!$image->isImage() || !$image->getImageType()) continue;
      

Debugging Tips

  • Log Parsing Issues: Enable debug mode in the parser (if available) or log raw objects for inspection:

    $document = (new PdfParser())->parseFile('problematic.pdf');
    $rawObject = $document->getObject(123); // Inspect problematic object
    
  • Check PDF Validity: Use tools like PDF.js or PDFtk to validate PDF structure before parsing.

  • Memory Profiling: Use Laravel Telescope or Xdebug to monitor memory usage during parsing.

Extension Points

  1. Custom Object Decorators: Extend existing decorators (e.g., Page, XObject) to add domain-specific methods:

    class CustomPage extends Page {
        public function getHighlightedText(string $keyword) {
            // Implement custom logic
        }
    }
    
  2. Override Parsing Logic: Subclass PdfParser to modify parsing behavior:

    class CustomPdfParser extends PdfParser {
        protected function parseObject(Object $object) {
            // Custom parsing logic
        }
    }
    
  3. Add New Object Types: Implement new decorators for unsupported PDF objects by extending the base Object class.

  4. Hooks for Post-Processing: Use Laravel events or observer patterns to process extracted data after parsing:

    event(new PdfParsed($document));
    

Configuration Quirks

  • PHP Version: Requires PHP 8.2+. Use php -v to verify compatibility.
  • Dependencies: No external dependencies, but ensure ext-fileinfo is enabled for image type detection.
  • Performance Tuning: Adjust useInMemoryStream and useFileCache based on file size and server resources.
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.
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
christhompsontldr/laravel-inky
spatie/mailcoach-vapor
spatie/laravel-javascript-views
spatie/ignition-contracts
earls/stork-command-queue-bundle