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

Libmergepdf Laravel Package

iio/libmergepdf

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Installation

    composer require iio/libmergepdf
    

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

    'providers' => [
        // ...
        Iio\LibMergePdf\LibMergePdfServiceProvider::class,
    ],
    
  2. Basic Merge

    use Iio\LibMergePdf\LibMergePdf;
    
    $pdf = new LibMergePdf();
    $pdf->merge('output.pdf', ['file1.pdf', 'file2.pdf']);
    
  3. First Use Case Merge multiple PDFs from a user upload directory and send the result as an attachment:

    $files = request()->file('pdfs')->all();
    $tempFiles = [];
    foreach ($files as $file) {
        $tempFiles[] = $file->store('temp');
    }
    
    $pdf = new LibMergePdf();
    $mergedPath = $pdf->merge('merged.pdf', $tempFiles);
    
    return response()->download($mergedPath)->deleteFileAfterSend(true);
    

Where to Look First

  • Documentation (if available) or the source code for core methods.
  • LibMergePdf class methods: merge(), setOptions(), getOptions().
  • Example usage in tests: tests/.

Implementation Patterns

Common Workflows

  1. Dynamic File Merging Merge PDFs based on user input (e.g., a form selecting multiple files):

    $selectedFiles = request('file_ids'); // Assume IDs from DB
    $paths = File::whereIn('id', $selectedFiles)->pluck('path')->toArray();
    $pdf->merge('merged.pdf', $paths);
    
  2. Streaming Large Files Avoid memory issues by streaming output directly to a response:

    $pdf = new LibMergePdf();
    $pdf->setOutputFile('php://output');
    $pdf->merge('', ['file1.pdf', 'file2.pdf']);
    return response()->streamDownload(function () use ($pdf) {
        echo $pdf->getOutput();
    }, 'merged.pdf');
    
  3. Conditional Merging Skip empty or invalid files before merging:

    $validFiles = array_filter($allFiles, function ($file) {
        return file_exists($file) && filesize($file) > 0;
    });
    $pdf->merge('output.pdf', array_values($validFiles));
    
  4. Integration with Queues Offload merging to a queue job for long-running tasks:

    // MergePdfJob.php
    public function handle() {
        $pdf = new LibMergePdf();
        $pdf->merge(storage_path('app/merged.pdf'), $this->files);
    }
    

Integration Tips

  • Laravel Filesystem: Use Storage::disk('local')->path() for consistent path handling.
  • Validation: Validate PDFs before merging (e.g., check MIME type with mime_type()).
  • Error Handling: Wrap merging in a try-catch to handle exceptions (e.g., corrupt files):
    try {
        $pdf->merge('output.pdf', $files);
    } catch (\Exception $e) {
        Log::error("Merge failed: " . $e->getMessage());
        return back()->withError('Merge failed.');
    }
    

Gotchas and Tips

Pitfalls

  1. Memory Limits

    • Merging large PDFs (e.g., >100MB) may hit PHP’s memory_limit. Use streaming or chunked processing.
    • Fix: Increase memory_limit in php.ini or use set_time_limit():
      ini_set('memory_limit', '512M');
      set_time_limit(300);
      
  2. File Paths

    • Absolute vs. Relative Paths: Always use absolute paths (e.g., storage_path('file.pdf')) to avoid issues.
    • Windows Line Endings: PDFs with \r\n may cause errors. Normalize paths:
      $paths = array_map('str_replace', ['\\', '/'], $paths);
      
  3. Permission Errors

    • Ensure the output directory is writable:
      chmod -R 775 storage/app/public
      
    • Fix: Use storage_path('app') and verify permissions.
  4. Corrupt PDFs

    • Invalid PDFs (e.g., truncated files) will crash the merger.
    • Fix: Validate files before merging:
      function isValidPdf($path) {
          $finfo = finfo_open(FILEINFO_MIME_TYPE);
          $mime = finfo_file($finfo, $path);
          finfo_close($finfo);
          return strpos($mime, 'pdf') === 0;
      }
      

Debugging Tips

  • Enable Verbose Output: Check the library’s logs or wrap in error_log():
    $pdf->setOptions(['verbose' => true]);
    
  • Test with Small Files: Start with 2–3 small PDFs to isolate issues.
  • Check Temporary Files: If merging fails, inspect intermediate files (e.g., temp_* files in /tmp).

Extension Points

  1. Custom Options Override default behavior (e.g., page rotation, compression):

    $pdf->setOptions([
        'page_rotation' => 90, // Rotate all pages
        'compress' => true,   // Reduce file size
    ]);
    
  2. Pre/Post-Processing Hook into the merge process to modify pages (e.g., add watermarks):

    // Use a wrapper class or extend LibMergePdf
    class CustomMergePdf extends LibMergePdf {
        protected function beforeMerge() {
            // Add logic here (e.g., inject a header page)
        }
    }
    
  3. Fallback for Missing Dependencies The library relies on Ghostscript or pdftk. If missing:

    • Fix: Install Ghostscript:
      # Ubuntu/Debian
      sudo apt-get install ghostscript
      
    • Or use a PHP-only alternative like setasign/fpdf for simple cases.
  4. Laravel Artisan Command Create a command for CLI merging:

    // app/Console/Commands/MergePdfs.php
    public function handle() {
        $pdf = new LibMergePdf();
        $pdf->merge('merged.pdf', $this->argument('files'));
    }
    

    Run with:

    php artisan merge-pdfs file1.pdf file2.pdf
    
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.
mehedimi/laravel-amp-mail
happones/laravel-vue-i18n-generator
jwerd/inertia-table
siberfx/flysystem-wasabi
hollyit/token-replace
ippanelcom/laravel-sdk
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