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

smalot/pdfparser

Standalone PHP library to parse PDF files and extract content. Reads objects/headers, metadata, and ordered page text; supports compressed PDFs and various encodings. Configure parsing via custom configs. Note: no support for secured PDFs or form data.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require smalot/pdfparser
    

    Ensure your project uses PHP 7.1+.

  2. Basic Usage:

    use Smalot\PdfParser\Parser;
    
    $parser = new Parser();
    $pdf = $parser->parseFile('/path/to/document.pdf');
    $text = $pdf->getText();
    
  3. Key Methods:

    • parseFile(): Parse a PDF file from disk.
    • parseContent(): Parse PDF content from a string.
    • parseStream(): Parse PDF content from a stream (e.g., HTTP request).
    • getText(): Extract all text from the PDF.
    • getPagesText(): Extract text from specific pages (e.g., $pdf->getPagesText([1, 2])).

First Use Case

Extract metadata and text from an uploaded PDF in a Laravel controller:

use Smalot\PdfParser\Parser;

public function processPdf(Request $request)
{
    $request->validate(['pdf' => 'required|file|mimes:pdf']);

    $parser = new Parser();
    $pdf = $parser->parseFile($request->file('pdf')->getRealPath());

    return response()->json([
        'metadata' => $pdf->getMetadata(),
        'text' => $pdf->getText(),
        'pages' => $pdf->getPagesText(),
    ]);
}

Implementation Patterns

Core Workflows

  1. Text Extraction:

    • Use $pdf->getText() for full document text.
    • Use $pdf->getPagesText([$pageNumbers]) for targeted pages.
    • Example: Extract text from pages 1–3:
      $text = $pdf->getPagesText(range(1, 3));
      
  2. Metadata Handling:

    • Access metadata via $pdf->getMetadata():
      $metadata = $pdf->getMetadata();
      // Example: $metadata['Author'], $metadata['Title']
      
  3. Streaming Parsing:

    • Parse from a stream (e.g., HTTP upload):
      $parser = new Parser();
      $pdf = $parser->parseStream($request->pdf);
      
  4. Custom Configurations:

    • Override default behavior with CustomConfig:
      use Smalot\PdfParser\Config\CustomConfig;
      
      $config = new CustomConfig();
      $config->setOption('ignore_images', true); // Skip image XObjects
      $parser = new Parser($config);
      

Integration Tips

  • Laravel Storage: Parse files stored in Laravel's filesystem:

    use Illuminate\Support\Facades\Storage;
    
    $path = Storage::path('uploads/document.pdf');
    $pdf = $parser->parseFile($path);
    
  • Queue Jobs: Offload parsing to a queue (e.g., PdfParseJob):

    PdfParseJob::dispatch($filePath)->onQueue('pdf');
    
  • Service Provider: Bind the parser in AppServiceProvider for dependency injection:

    $this->app->singleton(Parser::class, function () {
        return new Parser(new CustomConfig());
    });
    
  • Validation: Validate PDF content before processing:

    $text = $pdf->getText();
    if (str_contains($text, 'confidential')) {
        abort(403, 'Access denied');
    }
    

Gotchas and Tips

Pitfalls

  1. Memory Limits:

    • Large PDFs may exhaust memory. Use setMemoryLimit() in CustomConfig:
      $config->setMemoryLimit(512); // MB
      
    • Stream parsing (parseStream) is more memory-efficient for large files.
  2. Malformed PDFs:

    • The library may crash on corrupted files. Handle exceptions:
      try {
          $pdf = $parser->parseFile($path);
      } catch (\Smalot\PdfParser\Exceptions\ParseException $e) {
          Log::error("PDF parse error: " . $e->getMessage());
          return response()->json(['error' => 'Invalid PDF'], 400);
      }
      
  3. Encrypted PDFs:

    • The library ignores encryption (no decryption support). Use external tools (e.g., pdftotext) for secured files.
  4. Text Extraction Quirks:

    • Images/forms may appear as empty strings. Exclude them with:
      $config->setOption('ignore_images', true);
      $config->setOption('ignore_forms', true);
      
  5. Line Endings:

    • PDFs with mixed line endings (e.g., \r\n vs \n) may cause parsing issues. Normalize input if needed.

Debugging Tips

  • Log Raw Data: Inspect raw PDF content for debugging:

    $rawContent = file_get_contents($path);
    Log::debug('PDF Header:', substr($rawContent, 0, 100));
    
  • Check Object Structure: Dump parsed objects to understand the PDF structure:

    $objects = $pdf->getObjects();
    dd($objects[1]->getData()); // Inspect object #1
    
  • Validate Metadata: Ensure metadata keys exist before accessing:

    $author = $pdf->getMetadata()['Author'] ?? 'Unknown';
    

Extension Points

  1. Custom Text Processing: Override formatContent() in a subclass:

    class CustomParser extends Parser {
        protected function formatContent($content) {
            $content = parent::formatContent($content);
            return str_replace(['[REDACTED]', '(REDACTED)'], '', $content);
        }
    }
    
  2. Hooks for Post-Processing: Use events or callbacks after parsing:

    $pdf = $parser->parseFile($path);
    $text = $pdf->getText();
    $processedText = app()->call([TextProcessor::class, 'process'], ['text' => $text]);
    
  3. Performance Optimization:

    • Cache parsed PDFs in Laravel's cache:
      $cacheKey = 'pdf_text_' . md5($path);
      $text = Cache::remember($cacheKey, now()->addHours(1), function () use ($pdf) {
          return $pdf->getText();
      });
      
  4. Testing:

    • Mock the parser in tests:
      $mockParser = Mockery::mock(Parser::class);
      $mockParser->shouldReceive('parseFile')->andReturn($mockPdf);
      

Config Quirks

  • Default Options: Review CustomConfig options:

    $config->setOption('ignore_comments', true); // Skip PDF comments
    $config->setOption('ignore_inline_images', true); // Skip inline images
    
  • Character Encoding: Force UTF-8 encoding if needed:

    $config->setOption('charset', 'UTF-8');
    
  • Page Order: Extract pages in reverse order:

    $pages = array_reverse($pdf->getPagesText());
    
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.
nexmo/api-specification
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
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata