gotenberg-php

repository·main·Indexed 18 days ago

https://github.com/gotenberg/gotenberg-php

A PHP client for Gotenberg, a developer-friendly API for converting various document formats (HTML, Office, etc.) into PDFs using Chromium and LibreOffice. The library provides modules for Chromium, LibreOffice, and PDF engines, supporting features such as PDF/A generation, FacturX electronic invoicing, and custom page layouts. It requires a PSR-18 compatible HTTP client and provides helpers for sending requests and saving resulting files.

Tokens
9K
Snippets
39
Records
44
Agent score
63%

What's inside gotenberg-php

  1. How Gotenberg PHP modules and requests work

    main

    The library is organized into modules corresponding to Gotenberg API capabilities: chromium(), libreOffice(), and pdfEngines().

    To build a request, you initialize a module with the $apiUrl, chain methods to populate the multipart/form-data request (such as setting files, URLs, or options), and finally call the method representing the specific endpoint (e.g., pdf(), screenshot(), or convert()).

    use Gotenberg//
    
    // Example of building a Chromium PDF request
    $request = Gotenberg::chromium($apiUrl)
        ->pdf()
        ->singlePage()
        ->url('https://my.url');
  2. Install Gotenberg PHP via Composer

    main

    Install the client using Composer. This package requires a PSR-18 compatible HTTP client. If you do not have one configured, it is recommended to use the Guzzle 7 adapter.

    composer require gotenberg/gotenberg-php
    
    # Recommended adapter for PSR-18 support
    composer require php-http/guzzle7-adapter
  3. Configure LibreOffice conversion options

    main

    The LibreOffice class provides a fluent interface to configure various parameters for converting LibreOffice documents to PDF via the Gotenberg API. You can control document properties, PDF export settings, security, and metadata.

    Common Configuration Tasks

    • Document Properties: Set passwords, page ranges, or orientation.
    • PDF Export Settings: Control bookmarks, form field exporting, notes, and image compression.
    • Security: Encrypt the resulting PDF with user and owner passwords, and restrict permissions like printing or copying.
    • Metadata: Set document metadata or embed Factur-X / ZUGFeRD invoice XML.
    • Output Control: Merge multiple files into one PDF or split them into multiple PDFs using SplitMode.
  4. Handle GotenbergApiErrored exceptions and Correlation IDs

    main

    When Gotenberg::send() or Gotenberg::save() fails due to a non-2xx response, a GotenbergApiErrored exception is thrown. You can retrieve the correlation ID from the exception to trace the error in Gotenberg logs.

    use Gotenberg\Exceptions\GotenbergApiErrored;
    use Gotenberg\Gotenberg;
    
    try {
        $response = Gotenberg::send($request);
    } catch (GotenbergApiErrored $e) {
        // Get default correlation ID
        $correlationId = $e->getCorrelationId();
        
        // Or get it using a custom header name if you provided one
        $correlationId = $e->getCorrelationId('Request-Id');
    }
  5. Use DownloadFrom to let Gotenberg fetch files

    main

    Instead of uploading files from your local server, you can instruct Gotenberg to download them directly from a URL using the downloadFrom method with an array of DownloadFrom objects.

    use Gotenberg\DownloadFrom;
    use Gotenberg\Gotenberg;
    
    Gotenberg::libreOffice($apiUrl)
        ->downloadFrom([
            new DownloadFrom('https://url.to.document.docx', ['MyHeader' => 'MyValue'])
        ])
        ->convert();
  6. Save a resulting file to a directory

    main

    Use Gotenberg::save() to execute a request and automatically write the resulting file to a specified directory. This method returns the filename generated by Gotenberg (usually a UUID with a .pdf, .zip, or image extension).

    use Gotenberg\Gotenberg;
    
    $request = Gotenberg::chromium($apiUrl)->pdf()->url('https://my.url');
    $filename = Gotenberg::save($request, '/path/to/saving/directory');
  7. Configure output filename and Correlation ID

    main

    You can customize the request behavior using these methods:

    • outputFilename('name'): Sets the base name for the output file (extension is added automatically).
    • correlationId('value', 'Header-Name'): Sets a custom correlation ID to identify the request in Gotenberg logs. This sets the Gotenberg-Trace header by default. Ensure the header name matches the Gotenberg --api-correlation-id-header property.
    // Custom filename
    $request = Gotenberg::chromium($apiUrl)
        ->pdf()
        ->outputFilename('my_file')
        ->url('https://my.url');
    
    // Custom correlation ID and header name
    $request = Gotenberg::chromium($apiUrl)
        ->pdf()
        ->correlationId('debug', 'Request-Id')
        ->url('https://my.url');
  8. Use the Stream class to provide files and content

    main

    When a Gotenberg endpoint requires files (like Office documents or HTML assets), use the Gotenberg\Stream class to wrap your data. You can create streams from:

    • A file path: Stream::path($path)
    • A string (name and content): Stream::string('filename', 'content')
    • A raw stream object: new Stream('filename', $stream)
    use Gotenberg\Gotenberg;
    use Gotenberg\Stream;
    
    // Using file paths
    Gotenberg::libreOffice($apiUrl)->convert(Stream::path($pathToDocx));
    
    // Using string content for assets and HTML
    Gotenberg::chromium($apiUrl)
        ->pdf()
        ->assets(Stream::string('style.css', 'body{font-family: Arial;}'))
        ->html(Stream::string('index.html', '<html>...</html>'));
  9. Send a request and get a PSR-7 response

    main

    If you are using a client that implements RequestInterface, you can manually send the request. If you have a PSR-18 client, you can use the Gotenberg::send() helper, which automatically throws a GotenbergApiErrored exception if the response status is not 2xx.

    use Gotenberg\Gotenberg;
    
    $request = Gotenberg::chromium($apiUrl)->pdf()->url('https://my.url');
    
    // Option 1: Using a PSR-7 compatible client
    $response = $client->sendRequest($request);
    
    // Option 2: Using the Gotenberg::send helper (requires PSR-18 client)
    try {
        $response = Gotenberg::send($request);
    } catch (GotenbergApiErrored $e) {
        // Handle error
    }
  10. Perform PDF engine operations with PdfEngines

    main

    The PdfEngines class provides a fluent interface to interact with Gotenberg's PDF engine endpoints. You can use it to perform various operations on PDF files such as merging, splitting, rotating, watermarking, and more. Most operations return a RequestInterface which you can then send to the API.

    // Example: Merging multiple PDFs into one
    $request = $pdfEngines->merge($pdfStream1, $pdfStream2);
  11. Send a request to the Gotenberg API

    main

    Use Gotenberg::send() to dispatch a PSR-7 RequestInterface to the Gotenberg server.

    • If no $client is provided, it uses Psr18ClientDiscovery to find an available PSR-18 HTTP client in your environment.
    • The method will throw a GotenbergApiErrored exception if the response status code is outside the 200-299 range.
    use Gotenberg\Gotenberg;
    use Psr\Http\Message\RequestInterface;
    use Psr\Http\Client\ClientInterface;
    
    // $request is a pre-configured PSR-7 RequestInterface
    // $client is an optional PSR-18 ClientInterface
    $response = Gotenberg::send($request, $client);
  12. Apply watermarks or stamps to PDFs

    main

    Use watermark() or stamp() to apply visual overlays to your PDFs. Both methods require a source string (the path or identifier for the watermark/stamp) and the PDF streams to be processed.

    // Apply a watermark
    $request = $pdfEngines->watermark('path/to/watermark.png', $pdfStream);