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

Laravel Pdfmerger Laravel Package

webklex/laravel-pdfmerger

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation: Run composer require webklex/laravel-pdfmerger and add the service provider to config/app.php:
    'providers' => [
        Webklex\PDFMerger\Providers\PDFMergerServiceProvider::class,
    ],
    'aliases' => [
        'PDFMerger' => Webklex\PDFMerger\Facades\PDFMergerFacade::class,
    ]
    
  2. First Use Case: Merge two PDFs and save the result:
    use PDFMerger;
    
    $merger = PDFMerger::init();
    $merger->addPDF(public_path('file1.pdf'), [1, 2]); // Add specific pages
    $merger->addPDF(public_path('file2.pdf'), 'all');   // Add all pages
    $merger->merge();
    $merger->save(storage_path('merged.pdf'));
    

Where to Look First

  • Facade: PDFMerger facade for fluent syntax.
  • Examples: Check the examples/ directory in the package source for use cases.
  • Documentation: The README covers core functionality.

Implementation Patterns

Core Workflows

  1. Dynamic PDF Merging:

    $merger = PDFMerger::init();
    foreach ($pdfFiles as $file) {
        $merger->addPDF($file, ['all' | [1, 2, 3]]);
    }
    $merger->merge()->save($outputPath);
    
    • Useful for generating reports or combining user-uploaded PDFs.
  2. Streaming PDFs from Storage:

    $merger = PDFMerger::init();
    $merger->addString(Storage::disk('s3')->get('file.pdf'), [1]);
    $merger->merge();
    return response($merger->output(), 200, ['Content-Type' => 'application/pdf']);
    
    • Ideal for APIs returning merged PDFs directly.
  3. Conditional Page Selection:

    $pages = request()->input('pages', 'all');
    $merger->addPDF($file, $pages === 'all' ? 'all' : explode(',', $pages));
    
    • Enable user-controlled page selection in forms.
  4. Batch Processing:

    $merger = PDFMerger::init();
    foreach ($batch as $item) {
        $merger->addPDF($item->path, $item->pages);
    }
    $merger->merge()->save("batch_{$batchId}.pdf");
    
    • Merge PDFs from a database query or queue job.

Integration Tips

  • Laravel Queues: Dispatch merging jobs for large files:
    MergePdfJob::dispatch($files, $outputPath);
    
  • Events: Trigger post-merge actions (e.g., notifications):
    event(new PdfMerged($outputPath));
    
  • Testing: Mock the facade for unit tests:
    $this->mock(PDFMerger::class)->shouldReceive('init')->andReturnSelf();
    

Gotchas and Tips

Pitfalls

  1. Memory Limits:

    • Large PDFs may hit PHP’s memory_limit. Use ini_set('memory_limit', '512M') or chunk processing.
    • Fix: Stream files directly to disk instead of loading into memory.
  2. Path Handling:

    • Absolute paths (e.g., /var/www/file.pdf) work, but relative paths may fail in shared hosting.
    • Fix: Use public_path(), storage_path(), or realpath().
  3. Page Indexing:

    • Pages are 1-indexed (not 0-indexed). addPDF($file, [0]) will silently skip the page.
    • Fix: Validate inputs: $pages = array_filter($pages, fn($p) => $p > 0);.
  4. Facade vs. Class:

    • The facade (PDFMerger::init()) and class (new PDFMerger) are interchangeable, but the facade auto-resolves the service container.
    • Tip: Use the facade for dependency injection clarity.
  5. Output Handling:

    • merge() returns the instance, but output() returns raw bytes. Forgetting to call output() after merge() may leave the merger in an invalid state.
    • Fix: Chain methods: $merger->merge()->output().

Debugging

  • Check for Errors:
    try {
        $merger->merge();
    } catch (\Exception $e) {
        Log::error("PDF Merge Failed: " . $e->getMessage());
        return back()->withError($e->getMessage());
    }
    
  • Validate Inputs:
    if (!file_exists($file)) {
        throw new \InvalidArgumentException("File not found: {$file}");
    }
    

Extension Points

  1. Custom Merge Logic: Override the merge() method in a service class:

    class CustomMerger extends \Webklex\PDFMerger\PDFMerger {
        public function merge() {
            // Add pre-merge logic (e.g., watermarking)
            parent::merge();
            // Add post-merge logic
        }
    }
    

    Register the service in config/app.php:

    'PDFMerger' => App\Services\CustomMerger::class,
    
  2. Add Metadata: Use the underlying setPdf() method to inject custom data:

    $merger->addString($pdfData, [1]);
    $merger->setPdf(0, ['Title' => 'Custom Title']); // Set metadata for the first PDF
    
  3. Hooks: Extend the package by publishing config and adding listeners:

    php artisan vendor:publish --provider="Webklex\PDFMerger\Providers\PDFMergerServiceProvider"
    

    Then bind events in EventServiceProvider:

    protected $listen = [
        'pdf.merging' => [YourListener::class],
    ];
    

Performance Tips

  • Avoid Redundant Merges: Cache merged results if the same files are merged frequently.
  • Use addString() for Dynamic Content: If generating PDFs on-the-fly (e.g., with Dompdf), merge them as strings to avoid temporary files:
    $pdfContent = (new Dompdf)->loadHtml($html)->output();
    $merger->addString($pdfContent, [1]);
    
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle