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

Gotenberg Php Laravel Package

gotenberg/gotenberg-php

PHP client for the Gotenberg API to convert documents to PDF using Chromium/LibreOffice. Build requests for URL, HTML, Markdown, and Office files, then stream or save outputs. Compatible with Gotenberg 8.x via client v2.x.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Install the package**:
   ```bash
   composer require gotenberg/gotenberg-php php-http/guzzle7-adapter
  1. Set up Gotenberg (Docker recommended):
    docker run -p 3000:3000 gotenberg/gotenberg:latest
    
  2. First conversion (URL to PDF):
    use Gotenberg\Gotenberg;
    
    $filename = Gotenberg::save(
        Gotenberg::chromium('http://localhost:3000')->pdf()->url('https://example.com'),
        storage_path('app/public')
    );
    

Key Starting Points

  • Documentation: Gotenberg API Docs
  • Common Use Cases:
    • URL → PDF (chromium()->pdf()->url())
    • Local file → PDF (libreOffice()->convert(Stream::path('file.docx')))
    • HTML → PDF (chromium()->pdf()->html(Stream::string('html')))

Implementation Patterns

Core Workflows

1. URL Conversion Pipeline

// Convert URL to PDF with custom options
$request = Gotenberg::chromium(config('gotenberg.url'))
    ->pdf()
    ->waitForSelector('#content') // Wait for dynamic content
    ->singlePage()
    ->url('https://example.com')
    ->outputFilename('report');

// Save or send
$filename = Gotenberg::save($request, storage_path('pdfs'));
// OR
$response = Gotenberg::send($request);

2. Office Document Processing

// Convert multiple Office files
$response = Gotenberg::send(
    Gotenberg::libreOffice(config('gotenberg.url'))
        ->convert(
            Stream::path('document.docx'),
            Stream::path('spreadsheet.xlsx')
        )
        ->allowModifying()
        ->allowCopying()
);

3. Dynamic HTML Generation

// Generate PDF from templated HTML
$html = view('pdf.template', ['data' => $model])->render();
$request = Gotenberg::chromium(config('gotenberg.url'))
    ->pdf()
    ->html(Stream::string('template.html', $html))
    ->assets(Stream::string('styles.css', $css))
    ->outputFilename('invoice_' . $model->id);

4. Batch Processing with Queues

// Queue PDF generation jobs
PdfGenerationJob::dispatch($url, $filename)
    ->onQueue('pdf-conversions');

// Job handler
public function handle() {
    $filename = Gotenberg::save(
        Gotenberg::chromium(config('gotenberg.url'))
            ->pdf()
            ->url($this->url),
        storage_path('pdfs')
    );
    $this->filename = $filename;
}

Integration Tips

  • Laravel Service Provider:

    public function register() {
        $this->app->singleton('gotenberg', function() {
            return Gotenberg::chromium(config('gotenberg.url'));
        });
    }
    
  • Form Request Validation:

    public function rules() {
        return [
            'file' => 'required|file|mimes:doc,docx,xls,xlsx,pdf',
        ];
    }
    
    public function handle() {
        $request = Gotenberg::libreOffice(config('gotenberg.url'))
            ->convert(Stream::path($this->file->path()));
        // ...
    }
    
  • Error Handling Middleware:

    public function handle($request, Closure $next) {
        try {
            return $next($request);
        } catch (GotenbergApiErrored $e) {
            Log::error("Gotenberg failed: {$e->getCorrelationId()}", [
                'response' => $e->getResponse()->getBody()
            ]);
            return response()->view('errors.gotenberg', [], 500);
        }
    }
    

Gotchas and Tips

Common Pitfalls

  1. Connection Issues:

    • Symptom: Timeouts or empty responses
    • Fix: Verify Gotenberg container is running (docker ps) and network access (ping gotenberg from Laravel container)
    • Debug: Check Gotenberg logs (docker logs gotenberg)
  2. Memory Limits:

    • Symptom: Large PDFs fail with "out of memory"
    • Fix: Increase Chromium memory limits in Gotenberg config:
      # docker-compose.yml
      environment:
        CHROMIUM_MEMORY_LIMIT: 2048
      
  3. Dynamic Content:

    • Symptom: Screenshots/PDFs missing loaded content
    • Fix: Use waitForSelector() or adjust timeout:
      ->waitForSelector('#dynamic-content', 10000) // 10s timeout
      
  4. File Paths:

    • Symptom: Stream::path() fails with "file not found"
    • Fix: Use absolute paths or Laravel's storage_path():
      Stream::path(storage_path('app/uploads/document.docx'))
      

Debugging Techniques

  • Correlation IDs:

    try {
        Gotenberg::send($request);
    } catch (GotenbergApiErrored $e) {
        $correlationId = $e->getCorrelationId();
        // Check Gotenberg logs with: docker logs gotenberg | grep $correlationId
    }
    
  • Response Inspection:

    $response = Gotenberg::send($request);
    Log::debug('Headers:', $response->getHeaders());
    Log::debug('Body:', $response->getBody());
    

Configuration Quirks

  1. Gotenberg Version Mismatch:

    • Always align client (gotenberg/gotenberg-php) and server (gotenberg/gotenberg) versions
    • Check compatibility matrix in README
  2. Default Headers:

    • Gotenberg adds User-Agent: Gotenberg-PHP by default. Override with:
      $request->getHeaders()->set('User-Agent', 'MyApp/1.0');
      
  3. Stream Handling:

    • For large files, use Stream::resource() with temporary streams:
      $temp = tmpfile();
      fwrite($temp, $largeData);
      rewind($temp);
      $request->addFormData([
          'file' => new Stream('document.pdf', $temp)
      ]);
      

Extension Points

  1. Custom HTTP Client:

    $client = new Client([
        'base_uri' => config('gotenberg.url'),
        'timeout' => 30,
        'headers' => [
            'Authorization' => 'Bearer ' . config('gotenberg.token'),
        ],
    ]);
    
    Gotenberg::setClient($client);
    
  2. Middleware for Requests:

    $request = Gotenberg::chromium(config('gotenberg.url'))
        ->pdf()
        ->url('https://example.com');
    
    // Add custom headers
    $request->getHeaders()->set('X-Custom-Header', 'value');
    
    // Modify form data
    $request->getBody()->rewind();
    $data = json_decode($request->getBody(), true);
    $data['custom'] = 'value';
    $request->getBody()->write(json_encode($data));
    
  3. Response Transformers:

    $response = Gotenberg::send($request);
    $pdfContent = $response->getBody();
    $pdf = new \Spatie\Pdf\Pdf($pdfContent);
    // Process with Spatie PDF package
    
  4. Webhook Integration:

    $request = Gotenberg::chromium(config('gotenberg.url'))
        ->pdf()
        ->url('https://example.com')
        ->webhookEventsUrl(route('pdf.conversion.webhook'));
    
    // Handle webhook in Laravel route:
    Route::post('/pdf-webhook', function (Request $request) {
        $event = json_decode($request->getContent(), true);
        if ($event['status'] === 'failed') {
            // Handle failure
        }
    });
    

Performance Optimization

  1. Reuse Connections:

    $client = Http\Adapter\Guzzle7Adapter::createWithConfig([
        'base_uri' => config('gotenberg.url'),
        'timeout' => 30,
        'connect_timeout' => 5,
        'pool' => [
            'max_persistent' => 10,
        ],
    ]);
    Gotenberg::setClient($client);
    
  2. Concurrent Processing:

    $urls = ['url1', 'url2', 'url3'];
    $promises = collect($urls)->map(function ($url) {
        return Gotenberg::send(
            Gotenberg::chromium(config('gotenberg.url'))
                ->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.
cadot.eu/make
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