Gotenberg Bundle for Symfony

repository·1.x·Indexed 42 days ago

https://github.com/sensiolabs/gotenbergbundle

A Symfony bundle providing a high-level PHP interface for the Gotenberg 8.x API. It enables the generation of PDFs and screenshots from URLs, HTML, Markdown, and Office documents, featuring integration with Twig templates, asset management, and support for asynchronous file generation via webhooks.

Tokens
60.2K
Snippets
202
Records
231
Agent score
52%

What's inside Gotenberg Bundle

  1. Configure Webhooks for PDF embedding

    1.x

    Webhooks allow you to receive notifications about the success or failure of the PDF generation process. You can configure them via a single array or by using pre-defined configurations from your YAML settings.

    Using a configuration name

    If you have a webhook configuration defined in your Symfony configuration file, use webhookConfiguration() to apply it.

    Manual Webhook Configuration

    • webhook(array $webhook): Set success, error, and event URLs in one array.
    • webhookUrl(string $url, ?string $method): Set the success URL and optional HTTP method (POST, PUT, or PATCH).
    • webhookErrorUrl(string $url, ?string $method): Set the error URL and optional HTTP method.
    • webhookRoute(string $route, array $parameters, ?string $method): Set a Symfony route for success.
    • webhookErrorRoute(string $route, array $parameters, ?string $method): Set a Symfony route for errors.
    • webhookEventsUrl(string $url): Set a URL to receive structured JSON event callbacks (e.g., webhook.success, webhook.error).
    • webhookEventsRoute(string $route, array $parameters): Set a Symfony route for event callbacks.
    // Using a named configuration from config files
    return $gotenberg
        ->webhookConfiguration('my_webhook_config')
        ->generate()
        ->stream();
    
    // Manual configuration
    return $gotenberg
        ->webhook([
            'config_name' => 'my_config',
            'success' => ['url' => 'https://my.webhook.url/success', 'method' => 'POST'],
            'error' => ['route' => 'my_route_error', 'method' => 'POST'],
            'events' => ['url' => 'https://my.webhook.url/events']
        ])
        ->generate()
        ->stream();
  2. Convert Markdown to screenshots using MarkdownScreenshotBuilder

    1.x

    To convert Markdown files into screenshots, you must wrap the Markdown content within an HTML or Twig template. This template acts as the container for the Markdown content, which is injected using a special directive.

    Important Template Requirement: Every HTML or Twig template passed to Gotenberg (including headers or footers) must follow a valid HTML5 structure:

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <title>My screenshot</title>
      </head>
      <body>
        <!-- Your code goes here -->
      </body>
    </html>
  3. Use Gotenberg webhooks for asynchronous file generation

    1.x

    Gotenberg supports deferring file generation through webhooks. When the generation process is complete, Gotenberg calls back the URL provided in the request headers. To use this feature in the bundle, you must:

    1. Configure the webhook settings (URL, route, or method).
    2. Use the ->generateAsync() method instead of the standard synchronous generation method.

    If only a success URL is provided, the error URL will automatically fallback to the success URL.

  4. Merge named webhook configurations with builder overrides

    1.x

    When using both config_name and a custom configuration on a specific builder, the bundle loads the named configuration and merges it with the builder's specific configuration. The builder's configuration takes precedence for any overlapping keys.

    # This configuration:
    sensiolabs_gotenberg:
        webhook:
            default:
                success:
                    url: 'https://webhook.site/#!/view/{some-success-uuid}'
                error:
                    url: 'https://webhook.site/#!/view/{some-error-uuid}'
        default_options:
            pdf:
                html:
                    webhook:
                        config_name: 'default'
                        success:
                            url: 'https://webhook.site/#!/view/{some-other-uuid}'
    
    # Is equivalent to:
    sensiolabs_gotenberg:
        default_options:
            pdf:
                html:
                    webhook:
                        success:
                            url: 'https://webhook.site/#!/view/{some-other-uuid}'
                        error:
                            url: 'https://webhook.site/#!/view/{some-error-uuid}'
  5. Migrate from 0.4.0 to 1.0.0: Interface and Class Changes

    1.x

    The internal architecture for builders has been unified in version 1.0.0:

    • Removed Traits: CookieAwareTrait, DefaultBuilderTrait, and AsyncBuilderTrait have been removed.
    • Unified Interfaces: AsyncBuilderInterface, PdfBuilderInterface, and ScreenshotBuilderInterface have been replaced by a unified BuilderInterface.
    • New Interfaces:
      • BuilderAsyncInterface (extends BuilderInterface)
      • BuilderFileInterface (extends BuilderInterface)
      • BuilderAssetInterface (for asset management)
    • New Base Class: All builders now extend a new AbstractBuilder class.
  6. How Processors work in GotenbergBundle

    1.x

    Processors are used to handle the output of a generated PDF or Screenshot (e.g., saving to a file, streaming to a browser, or uploading to S3).

    When building a request, you attach a processor using the ->processor() method on the builder. After calling ->generate(), you have two ways to execute the processing:

    1. ->process(): Executes the processor and returns the result defined by that specific processor (e.g., a SplFileInfo, a resource, or an S3 result object).
    2. ->stream(): Streams the file content directly to the browser as a Symfony\Component\HttpFoundation\StreamedResponse. This is memory-efficient as it avoids loading the entire file into memory.

    All processors implement Sensiolabs\GotenbergBundle\Processor\ProcessorInterface and leverage PHP Generators to handle data in chunks.

    /** @var GotenbergFileResult $gotenbergFileResult */
    $gotenbergFileResult = $gotenbergPdf->html()
        ->fileName('my_pdf')
        ->processor(new FileProcessor($filesystem, $storage))
        ->generate();
    
    // To get the processor's specific return value:
    $result = $gotenbergFileResult->process();
    
    // To stream the result to a browser:
    $result = $gotenbergFileResult->stream();
  7. Understand asset path resolution logic

    1.x

    The path resolution for {{ gotenberg_asset() }}, assets(), and addAsset() follows these rules:

    1. Absolute Paths: If an absolute path is provided, it is used directly, ignoring the assets_directory configuration.
    2. Relative Paths (with assets_directory set): If a path is relative, it is treated as relative to the assets_directory path.
    3. Absolute assets_directory: If assets_directory is an absolute path, any path provided to the builder functions will use assets_directory as its base path.
    4. Relative assets_directory: If assets_directory is a relative path, the base path is the project root followed by the assets_directory path, and then the provided asset path.
    // Without sensiolabs_gotenberg.assets_directory:
    $builder->addAsset('/some/absolute/path/img.png'); // (string) '/some/absolute/path/img.png'
    
    // Without sensiolabs_gotenberg.assets_directory:
    $builder->addAsset('some/relative/img.png'); // (string) '%kernel.project_dir%/assets/some/relative/img.png'
    
    // With sensiolabs_gotenberg.assets_directory: '/some/absolute/path'
    $builder->addAsset('./some/relative/img.png'); // (string) '/some/absolute/path/some/relative/img.png'
    
    // With sensiolabs_gotenberg.assets_directory: 'some/relative/path'
    $builder->addAsset('./also/relative/img.png'); // (string) '%kernel.project_dir%/assets/some/relative/path/also/relative/img.png"
  8. Enable or disable the GotenbergFileResult controller listener

    1.x

    The bundle includes a listener for the kernel.view event. When a controller returns a GotenbergFileResult object, this listener automatically calls ->stream() to convert it into a Symfony Response object.

    This feature is enabled by default but can be toggled using the sensiolabs_gotenberg.controller_listener configuration key.

  9. Convert Markdown to PDF using MarkdownPdfBuilder

    1.x

    To convert Markdown files into PDF, you must wrap the Markdown content within an HTML or Twig template. This template acts as a shell for the Markdown content, which is injected using a special directive.

    Important Template Requirement: Every HTML or Twig template (including headers and footers) must follow a valid HTML5 structure:

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <title>My PDF</title>
      </head>
      <body>
        <!-- Your code goes here -->
      </body>
    </html>
  10. Automatic configurator registration for custom builders

    1.x
    In version 1.1.0, if you are implementing a custom builder by implementing BuilderInterface and your Symfony configuration has autoconfigure: true, the configurator will be automatically added to the service container.
  11. Generate a screenshot from a Symfony route

    1.x

    Use the route() method to generate a screenshot of a specific Symfony route. This is useful for internal pages.

    Important: The route must be accessible by the Gotenberg instance. If Gotenberg is running in a separate container (e.g., Docker), you must ensure it can resolve the host. You can configure a base_uri in your bundle configuration to point to your local development server.

    # config/packages/sensiolabs_gotenberg.yaml
    sensiolabs_gotenberg:
      request_context:
        base_uri: 'http://host.docker.internal:3000'
    namespace App\
    Controller;
    
    use Sensiolabs\\GotenbergBundle\\GotenbergScreenshotInterface;
    
    class YourController
    {
        public function yourControllerMethod(GotenbergScreenshotInterface $gotenberg): Response
        {
            return $gotenberg->url()
                ->route('home', [
                    'my_var' => 'value'
                ])
                ->generate()
                ->stream()
            ;
        }
    }
  12. Use custom fonts in static HTML files

    1.x

    If you are providing a raw HTML file instead of a Twig template, you must manually define the @font-face rule. The src: url(...) path must be relative to the root level of the assets provided to the bundle.

    To make the font available, you must explicitly register the font file path using the assets() or addAsset() method in your controller when building the request.

    <!-- content.html -->
    <style>
        @font-face {
            font-family: "my_font";
            src: url("custom-font.ttf");
        }
    </style>
    <p style="font-family: 'my_font';">Custom font text</p>
    // In your Controller
    return $gotenberg->html()
        ->contentFile('content.html')
        ->assets('fonts/my-font.ttf') // Register the font asset
        ->generate()
        ->stream();