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 Bundle Laravel Package

sensiolabs/gotenberg-bundle

Symfony bundle to generate PDFs and screenshots via the Gotenberg API. Convert from URL, HTML, Markdown, or Office files, then stream or save outputs locally. Supports source-specific options, advanced usage, and profiler/testing integrations.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install Gotenberg (Docker recommended):
    docker run -d --name gotenberg -p 3000:3000 gotenberg/gotenberg:8
    
  2. Install the Bundle:
    composer require sensiolabs/gotenberg-bundle
    
  3. Configure (config/packages/sensiolabs_gotenberg.yaml):
    sensiolabs_gotenberg:
        http_client: 'gotenberg.client'
    
    Add to framework.http_client.scoped_clients:
    framework:
        http_client:
            scoped_clients:
                gotenberg.client:
                    base_uri: 'http://localhost:3000'
    

First Use Case: PDF from URL

use Sensiolabs\GotenbergBundle\GotenbergPdfInterface;

class PdfController {
    public function generatePdf(GotenbergPdfInterface $gotenberg): Response {
        return $gotenberg->url()
            ->url('https://example.com')
            ->generate()
            ->stream();
    }
}

First Use Case: Screenshot from Twig

use Sensiolabs\GotenbergBundle\GotenbergScreenshotInterface;

class ScreenshotController {
    public function generateScreenshot(GotenbergScreenshotInterface $gotenberg): Response {
        return $gotenberg->html()
            ->content('template.html.twig', ['title' => 'Test'])
            ->generate()
            ->stream();
    }
}

Key Files to Explore:

  • config/packages/sensiolabs_gotenberg.yaml (configuration)
  • src/Controller/ (example controllers)
  • templates/ (Twig templates for PDFs)

Implementation Patterns

Common Workflows

1. PDF Generation Patterns

  • From URL:
    $gotenberg->url()
        ->url('https://example.com')
        ->timeout(30) // Optional: Set timeout in seconds
        ->generate()
        ->saveAs('/path/to/file.pdf'); // Save to filesystem
    
  • From Twig Template:
    $gotenberg->html()
        ->content('invoice.html.twig', ['user' => $user])
        ->options(['margin-top' => '20mm', 'margin-bottom' => '20mm'])
        ->generate()
        ->stream(); // Stream directly to browser
    
  • From Office Files:
    $gotenberg->office()
        ->file($filePath) // Local file path
        ->format('pdf')
        ->generate()
        ->saveAs('output.pdf');
    

2. Screenshot Patterns

  • From URL:
    $gotenberg->url()
        ->url('https://example.com')
        ->width(1200) // Optional: Set width in pixels
        ->height(800) // Optional: Set height in pixels
        ->generate()
        ->saveAs('screenshot.png');
    
  • From Markdown:
    $gotenberg->markdown()
        ->content('# Hello World')
        ->generate()
        ->stream();
    

3. Advanced PDF Operations

  • Merge PDFs:
    $gotenberg->merge()
        ->files(['file1.pdf', 'file2.pdf'])
        ->generate()
        ->saveAs('merged.pdf');
    
  • Encrypt PDF:
    $gotenberg->encrypt()
        ->file('input.pdf')
        ->password('secure123')
        ->generate()
        ->saveAs('encrypted.pdf');
    

4. Asset Handling in Twig

Use {{ gotenberg_asset('path/to/image.jpg') }} in Twig templates to reference assets. Configure the assets_directory in sensiolabs_gotenberg.yaml if needed:

sensiolabs_gotenberg:
    assets_directory: '%kernel.project_dir%/public/uploads'

5. Async Processing with Webhooks

Configure webhook endpoints in sensiolabs_gotenberg.yaml:

sensiolabs_gotenberg:
    webhook:
        url: 'https://your-app.com/webhook/gotenberg'
        events: ['pdf:created', 'screenshot:created']

Integration Tips

1. Symfony Router Integration

Use ->route() instead of ->url() to generate PDFs of Symfony routes:

$gotenberg->url()
    ->route('app.invoice_show', ['id' => 123])
    ->generate()
    ->stream();

2. Dependency Injection

Autowire services in controllers:

use Sensiolabs\GotenbergBundle\GotenbergPdfInterface;

class InvoiceController {
    public function __construct(
        private GotenbergPdfInterface $gotenberg
    ) {}
}

3. Command-Line Usage

Create a console command for batch processing:

use Sensiolabs\GotenbergBundle\GotenbergPdfInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class GeneratePdfCommand extends Command {
    protected static $defaultName = 'app:generate-pdf';

    public function __construct(private GotenbergPdfInterface $gotenberg) {
        parent::__construct();
    }

    protected function execute(InputInterface $input, OutputInterface $output): int {
        $gotenberg->url()
            ->url('https://example.com')
            ->generate()
            ->saveAs('output.pdf');
        $output->writeln('PDF generated successfully!');
        return Command::SUCCESS;
    }
}

4. Testing

Use the provided testing utilities:

use Sensiolabs\GotenbergBundle\Test\GotenbergTestCase;

class MyTest extends GotenbergTestCase {
    public function testPdfGeneration() {
        $this->mockPdfGeneration('https://example.com', 'output.pdf');
        // Assertions...
    }
}

Gotchas and Tips

Pitfalls

1. Blank Output

  • Cause: Gotenberg cannot access the URL due to SSL certificate errors or unreachable host.
  • Fix:
    • Add --chromium-ignore-certificate-errors to Gotenberg's Docker command.
    • Configure request_context.base_uri in sensiolabs_gotenberg.yaml to match your Symfony app's URL (e.g., http://host.docker.internal:8000 for Docker setups).

2. Asset Loading Failures

  • Cause: Assets referenced in Twig templates are not accessible from Gotenberg's context.
  • Fix:
    • Use {{ gotenberg_asset() }} instead of hardcoded paths.
    • Ensure assets_directory is correctly configured in sensiolabs_gotenberg.yaml.

3. Timeout Errors

  • Cause: Long-running PDF generation exceeds default timeouts.
  • Fix: Adjust timeouts in the builder:
    ->timeout(60) // 60 seconds
    ->chromiumTimeout(30)
    

4. Memory Limits

  • Cause: Large PDFs or complex pages exceed memory limits.
  • Fix:
    • Increase PHP memory limit in php.ini or .env:
      memory_limit = 512M
      
    • Optimize Chromium settings in Gotenberg:
      sensiolabs_gotenberg:
          chromium:
              args: ['--disable-gpu', '--no-sandbox']
      

5. Docker Networking Issues

  • Cause: Gotenberg cannot resolve Symfony's service name (e.g., symfony).
  • Fix: Use host.docker.internal or configure Docker networks properly.

Debugging Tips

1. Enable Profiler

The bundle includes a Symfony Profiler panel to inspect requests:

  • Ensure framework.profiler is enabled in config/packages/dev/profiler.yaml.
  • Check the "Gotenberg" tab for request details, response times, and errors.

2. Log Gotenberg Requests

Enable debug logging in config/packages/dev/monolog.yaml:

monolog:
    handlers:
        main:
            type: stream
            path: "%kernel.logs_dir%/%kernel.environment%.log"
            level: debug
            channels: ["!event"]
        gotenberg:
            type: stream
            path: "%kernel.logs_dir%/gotenberg.log"
            level: debug
            channels: ["gotenberg"]

3. Inspect Raw Responses

Use ->getResponse() to debug raw responses:

$response = $gotenberg->url()
    ->url('https://example.com')
    ->generate()
    ->getResponse();

if ($response->isSuccessful()) {
    $content = $response->getContent();
    // Log or inspect $content
}

Configuration Quirks

1. Custom HTTP Client

Override the default HTTP client for advanced use cases:

sensiolabs_gotenberg:
    http_client: 'custom.gotenberg.client'

Define the client in `framework.http_client

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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
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