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.
## Getting Started
### Minimal Setup
1. **Install the package**:
```bash
composer require gotenberg/gotenberg-php php-http/guzzle7-adapter
docker run -p 3000:3000 gotenberg/gotenberg:latest
use Gotenberg\Gotenberg;
$filename = Gotenberg::save(
Gotenberg::chromium('http://localhost:3000')->pdf()->url('https://example.com'),
storage_path('app/public')
);
chromium()->pdf()->url())libreOffice()->convert(Stream::path('file.docx')))chromium()->pdf()->html(Stream::string('html')))// 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);
// Convert multiple Office files
$response = Gotenberg::send(
Gotenberg::libreOffice(config('gotenberg.url'))
->convert(
Stream::path('document.docx'),
Stream::path('spreadsheet.xlsx')
)
->allowModifying()
->allowCopying()
);
// 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);
// 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;
}
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);
}
}
Connection Issues:
docker ps) and network access (ping gotenberg from Laravel container)docker logs gotenberg)Memory Limits:
# docker-compose.yml
environment:
CHROMIUM_MEMORY_LIMIT: 2048
Dynamic Content:
waitForSelector() or adjust timeout:
->waitForSelector('#dynamic-content', 10000) // 10s timeout
File Paths:
Stream::path() fails with "file not found"storage_path():
Stream::path(storage_path('app/uploads/document.docx'))
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());
Gotenberg Version Mismatch:
gotenberg/gotenberg-php) and server (gotenberg/gotenberg) versionsDefault Headers:
User-Agent: Gotenberg-PHP by default. Override with:
$request->getHeaders()->set('User-Agent', 'MyApp/1.0');
Stream Handling:
Stream::resource() with temporary streams:
$temp = tmpfile();
fwrite($temp, $largeData);
rewind($temp);
$request->addFormData([
'file' => new Stream('document.pdf', $temp)
]);
Custom HTTP Client:
$client = new Client([
'base_uri' => config('gotenberg.url'),
'timeout' => 30,
'headers' => [
'Authorization' => 'Bearer ' . config('gotenberg.token'),
],
]);
Gotenberg::setClient($client);
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));
Response Transformers:
$response = Gotenberg::send($request);
$pdfContent = $response->getBody();
$pdf = new \Spatie\Pdf\Pdf($pdfContent);
// Process with Spatie PDF package
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
}
});
Reuse Connections:
$client = Http\Adapter\Guzzle7Adapter::createWithConfig([
'base_uri' => config('gotenberg.url'),
'timeout' => 30,
'connect_timeout' => 5,
'pool' => [
'max_persistent' => 10,
],
]);
Gotenberg::setClient($client);
Concurrent Processing:
$urls = ['url1', 'url2', 'url3'];
$promises = collect($urls)->map(function ($url) {
return Gotenberg::send(
Gotenberg::chromium(config('gotenberg.url'))
->pdf()
How can I help you explore Laravel packages today?