Weave 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

Tc Lib Pdf Parser Laravel Package

tecnickcom/tc-lib-pdf-parser

Parse raw PDF data into structured PHP arrays for content inspection, metadata extraction, validation, and migration pipelines. Pure-PHP, PHP 8.2+, with cross-reference and object stream parsing plus typed exceptions.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the package via Composer:

    composer require tecnickcom/tc-lib-pdf-parser
    

    Require the autoloader in your Laravel project (handled automatically by Composer).

  2. First Use Case: Extract Text from a PDF

    use Tecnickcom\TCPDF\Parser\Parser;
    
    $parser = new Parser();
    $result = $parser->parseFile('path/to/your/file.pdf');
    
    // Access parsed content (e.g., text, metadata)
    $text = $result->getText();
    echo $text;
    
  3. Where to Look First

    • Documentation: GitHub README (limited but functional).
    • Source Code: Focus on Tecnickcom/TCPDF/Parser/Parser.php for core functionality.
    • Examples: Check the tests/ directory in the repo for usage patterns.

Implementation Patterns

Workflows

  1. Batch Processing Use Laravel’s queue system to process large PDFs asynchronously:

    use Illuminate\Support\Facades\Queue;
    use Tecnickcom\TCPDF\Parser\Parser;
    
    Queue::push(function () {
        $parser = new Parser();
        $result = $parser->parseFile(storage_path('pdfs/example.pdf'));
        // Store extracted data in DB or filesystem
    });
    
  2. Metadata Extraction Extract PDF metadata (author, title, etc.) for indexing:

    $metadata = $result->getInfo();
    $title = $metadata['Title'] ?? 'Untitled';
    
  3. Text Search Combine with Laravel’s Scout or database full-text search:

    $text = $result->getText();
    $searchTerm = 'contract';
    if (Str::contains(strtolower($text), strtolower($searchTerm))) {
        // Trigger action (e.g., flag document)
    }
    

Integration Tips

  • Laravel Storage: Store parsed PDFs in storage/app/public and use the filesystem facade to manage paths.
  • Service Provider: Bind the Parser class to Laravel’s container for dependency injection:
    // app/Providers/AppServiceProvider.php
    $this->app->bind(Parser::class, function () {
        return new Parser();
    });
    
  • Artisan Commands: Create a custom command to process PDFs on demand:
    use Illuminate\Console\Command;
    use Tecnickcom\TCPDF\Parser\Parser;
    
    class ProcessPdfCommand extends Command
    {
        protected $signature = 'pdf:parse {path}';
        public function handle(Parser $parser) {
            $result = $parser->parseFile($this->argument('path'));
            // Process result...
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Encoding Issues

    • PDFs may use non-UTF-8 encodings. Force UTF-8 conversion:
      $text = mb_convert_encoding($result->getText(), 'UTF-8', 'auto');
      
    • Debug Tip: Use dd($result->getText()) to inspect raw output for encoding artifacts.
  2. Complex PDFs (Tables, Images)

    • The parser may struggle with scanned PDFs (images) or highly formatted content (e.g., tables). Pre-process with OCR (e.g., spatie/pdf-to-text) if needed.
    • Workaround: Use parse() instead of parseFile() for in-memory parsing of simpler PDFs.
  3. Memory Limits

    • Large PDFs may hit PHP’s memory limit. Increase in .env:
      MEMORY_LIMIT=1024M
      
    • Tip: Stream parsing for huge files (not natively supported; consider chunking with fopen).
  4. Metadata Inconsistencies

    • Some PDFs may return null for metadata fields. Validate before use:
      $author = $metadata['Author'] ?? null;
      

Debugging

  • Log Parsing Errors:
    try {
        $result = $parser->parseFile($path);
    } catch (\Exception $e) {
        Log::error("PDF parse failed: {$e->getMessage()}");
    }
    
  • Inspect Raw Output: Dump the $result object to understand its structure:
    dd(get_object_vars($result));
    

Extension Points

  1. Custom Parsing Logic Extend the Parser class to add domain-specific logic:

    class CustomPdfParser extends Parser {
        public function extractContracts() {
            $text = $this->getText();
            // Add regex or NLP to detect contracts
        }
    }
    
  2. Event Listeners Trigger events after parsing (e.g., store extracted data):

    event(new PdfParsed($result, $path));
    

    Register in EventServiceProvider:

    protected $listen = [
        PdfParsed::class => [PdfProcessor::class],
    ];
    
  3. Laravel Scout Integration Index parsed text for search:

    use Laravel\Scout\Searchable;
    
    class Document implements Searchable {
        public function toSearchableArray() {
            return [
                'text' => $this->pdfParser->parseFile($this->path)->getText(),
            ];
        }
    }
    

Config Quirks

  • No Native Laravel Config: The package has no built-in config file. Use environment variables or a custom config file (e.g., config/pdf_parser.php) to store paths or defaults.
  • Default Parser Settings: Override defaults via the constructor:
    $parser = new Parser([
        'encoding' => 'UTF-8',
        'mergeBlocks' => true,
    ]);
    
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.
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus
adachsoft/php-code-style