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

Pdfmerger Laravel Package

alexanderpavlov/pdfmerger

A lightweight PHP library for merging multiple PDF files into a single document. Useful for batching reports, invoices, and attachments with simple, programmatic control over input order and output file creation.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require alexanderpavlov/pdfmerger
    

    Register the service provider in config/app.php (if not auto-discovered):

    'providers' => [
        // ...
        AlexanderPavlov\PdfMerger\PdfMergerServiceProvider::class,
    ],
    
  2. First Use Case: Merging Two PDFs

    use AlexanderPavlov\PdfMerger\Facades\PdfMerger;
    
    $mergedPdf = PdfMerger::merge([
        public_path('file1.pdf'),
        public_path('file2.pdf'),
    ])->save(public_path('merged.pdf'));
    
  3. Where to Look First

    • Facade: PdfMerger (for quick usage).
    • Service Provider: PdfMergerServiceProvider (for configuration).
    • Documentation: Check the GitHub repo (if available) for edge cases or advanced usage.

Implementation Patterns

Common Workflows

  1. Merging PDFs from Storage

    $pdfs = Storage::disk('local')->files('pdfs/');
    $merged = PdfMerger::merge($pdfs)->save(storage_path('merged.pdf'));
    
  2. Merging with Custom Output Paths

    $outputPath = storage_path('reports/merged_{date}.pdf');
    PdfMerger::merge($pdfPaths)->save(str_replace('{date}', now()->format('Y-m-d'), $outputPath));
    
  3. Streaming Merged PDFs to Browser

    return response()->streamDownload(
        function () use ($pdfPaths) {
            $merged = PdfMerger::merge($pdfPaths);
            echo $merged->getContent();
        },
        'merged_report.pdf'
    );
    
  4. Integration with Laravel Queues

    MergePdfs::dispatch($pdfPaths, $outputPath)
        ->onQueue('pdf-processing');
    
    // Job class
    public function handle() {
        PdfMerger::merge($this->pdfPaths)->save($this->outputPath);
    }
    
  5. Merging with Page Ranges

    $pdfs = [
        'file1.pdf' => ['pages' => '1-5'], // Merge only pages 1 to 5
        'file2.pdf' => ['pages' => 'all'],
    ];
    PdfMerger::merge($pdfs)->save('output.pdf');
    

Integration Tips

  • Laravel Filesystem: Use Storage facade to dynamically fetch PDF paths.
  • Validation: Validate PDF paths before merging to avoid errors.
  • Logging: Log failures (e.g., missing files) for debugging.
  • Caching: Cache merged PDFs if regenerated frequently (e.g., using Cache facade).

Gotchas and Tips

Pitfalls

  1. PHP5 Compatibility

    • The package is PHP5-only. Ensure your Laravel app (or test environment) uses PHP 5.x if required.
    • Workaround: Use a Docker container or VM with PHP 5 for testing.
  2. Memory Limits

    • Merging large PDFs may hit PHP’s memory_limit. Increase it temporarily:
      ini_set('memory_limit', '512M');
      
    • Tip: Process in chunks or use a queue for large files.
  3. File Permissions

    • Ensure the output directory is writable:
      chmod -R 775 storage/
      
    • Debug: Check Laravel logs (storage/logs/laravel.log) for permission errors.
  4. Encoding Issues

    • Non-ASCII filenames may cause issues. Use Str::slug() or urlencode():
      $safePath = urlencode($outputPath);
      
  5. Silent Failures

    • The package may not throw exceptions for invalid PDFs. Validate files first:
      if (!PdfMerger::isValidPdf($path)) {
          throw new \InvalidArgumentException("Invalid PDF: {$path}");
      }
      

Debugging Tips

  • Check Output: Save merged PDFs to a temporary location to verify content:
    PdfMerger::merge($pdfs)->save(temp_path('debug_merged.pdf'));
    
  • Log Inputs: Log the paths and options passed to PdfMerger for reproducibility.
  • Test with Small Files: Start with tiny PDFs (e.g., 1 page) to isolate issues.

Extension Points

  1. Custom Merge Logic Override the merger class (extend PdfMerger) to add pre/post-processing:

    class CustomPdfMerger extends \AlexanderPavlov\PdfMerger\PdfMerger {
        public function merge(array $pdfs) {
            // Add custom logic (e.g., watermarking)
            return parent::merge($pdfs);
        }
    }
    

    Bind it in the service provider:

    $this->app->bind('pdfmerger', function () {
        return new CustomPdfMerger();
    });
    
  2. Event Listeners Dispatch events before/after merging (e.g., for analytics):

    PdfMerger::merge($pdfs)->save($output)
        ->then(function () {
            event(new PdfMerged($output));
        });
    
  3. Configuration Override defaults in config/services.php (if the package supports it):

    'pdfmerger' => [
        'temp_dir' => storage_path('temp'),
        'debug' => env('PDFMERGER_DEBUG', false),
    ],
    

Quirks

  • No Progress Tracking: The package doesn’t support tracking merge progress for large files.
  • No PDF/A Validation: Output may not comply with PDF/A standards. Use a dedicated library if needed.
  • No Password Protection: Merged PDFs won’t inherit password protection from inputs. Use tcpdf or dompdf for this.
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
codifyo/ts-generator-bundle
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