PHPackages                             tobento/app-pdf - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [PDF &amp; Document Generation](/categories/documents)
4. /
5. tobento/app-pdf

ActiveLibrary[PDF &amp; Document Generation](/categories/documents)

tobento/app-pdf
===============

PDF generation and rendering support for Tobento applications.

2.0(5mo ago)031MITPHPPHP &gt;=8.4

Since Jan 21Pushed 5mo agoCompare

[ Source](https://github.com/tobento-ch/app-pdf)[ Packagist](https://packagist.org/packages/tobento/app-pdf)[ Docs](https://www.tobento.ch)[ RSS](/packages/tobento-app-pdf/feed)WikiDiscussions 2.x Synced today

READMEChangelog (1)Dependencies (14)Versions (2)Used By (1)

App PDF
=======

[](#app-pdf)

PDF support for the application, built on top of the [PDF Service](https://github.com/tobento-ch/service-pdf).

Table of Contents
-----------------

[](#table-of-contents)

- [Getting Started](#getting-started)
    - [Requirements](#requirements)
- [Documentation](#documentation)
    - [App](#app)
    - [PDF Boot](#pdf-boot)
        - [PDF Config](#pdf-config)
        - [Basic Usage](#basic-usage)
        - [Using PDF Handler](#using-pdf-handler)
            - [Storing](#storing)
            - [Downloading](#downloading)
            - [Webhook](#webhook)
            - [Queueing](#queueing)
- [Credits](#credits)

---

Getting Started
===============

[](#getting-started)

Add the latest version of the app pdf project running this command.

```
composer require tobento/app-pdf

```

Requirements
------------

[](#requirements)

- PHP 8.4 or greater

Documentation
=============

[](#documentation)

App
---

[](#app)

Check out the [**App Skeleton**](https://github.com/tobento-ch/app-skeleton) if you are using the skeleton.

You may also check out the [**App**](https://github.com/tobento-ch/app) to learn more about the app in general.

PDF Boot
--------

[](#pdf-boot)

The Pdf boot integrates the Tobento [PDF Service](https://github.com/tobento-ch/service-pdf) into your application and registers all PDF-related handlers. It provides:

- loading of the `pdf.php` configuration
- binding of all App-PDF interfaces
- binding of all Service-PDF interfaces
- automatic setup of PDF generators, renderers, and handlers

```
use Tobento\App\AppFactory;
use Tobento\App\Pdf\Download\DownloadHandlerInterface;
use Tobento\App\Pdf\FileStorage\FileStorageHandlerInterface;
use Tobento\App\Pdf\PdfHandlerInterface;
use Tobento\App\Pdf\Queue\QueueHandlerInterface;
use Tobento\App\Pdf\Webhook\WebhookHandlerInterface;
use Tobento\Service\Pdf\ParametersFactoryInterface;
use Tobento\Service\Pdf\PdfGeneratorFactoryInterface;
use Tobento\Service\Pdf\PdfGeneratorInterface;
use Tobento\Service\Pdf\PdfGeneratorsInterface;
use Tobento\Service\Pdf\PdfResponseFactoryInterface;
use Tobento\Service\Pdf\RendererInterface;

// Create the app
$app = new AppFactory()->createApp();

// Add directories:
$app->dirs()
    ->dir(realpath(__DIR__.'/../'), 'root')
    ->dir(realpath(__DIR__.'/../app/'), 'app')
    ->dir($app->dir('app').'config', 'config', group: 'config')
    ->dir($app->dir('root').'public', 'public')
    ->dir($app->dir('root').'vendor', 'vendor');

// Boot the PDF module
$app->boot(\Tobento\App\Pdf\Boot\Pdf::class);
$app->booting();

// App-PDF interfaces
$pdfHandler = $app->get(PdfHandlerInterface::class);
$downloadHandler = $app->get(DownloadHandlerInterface::class);
$fileStorageHandler = $app->get(FileStorageHandlerInterface::class);
$queueHandler = $app->get(QueueHandlerInterface::class);
$webhookHandler = $app->get(WebhookHandlerInterface::class);

// Service-PDF interfaces
$parametersFactory = $app->get(ParametersFactoryInterface::class);
$pdfGeneratorFactory = $app->get(PdfGeneratorFactoryInterface::class);
$pdfGenerator = $app->get(PdfGeneratorInterface::class);
$pdfGenerators = $app->get(PdfGeneratorsInterface::class);
$pdfResponseFactory = $app->get(PdfResponseFactoryInterface::class);
$renderer = $app->get(RendererInterface::class);

// Run the app
$app->run();
```

### PDF Config

[](#pdf-config)

The configuration for the pdf is located in the `app/config/pdf.php` file at the default [**App Skeleton**](https://github.com/tobento-ch/app-skeleton) config location where you can specify the [pdf generators](https://github.com/tobento-ch/service-pdf#pdf-generator) for your application.

### Basic Usage

[](#basic-usage)

If you're new to working with PDFs in Tobento, start with the
[Basic Usage section of the PDF Service](https://github.com/tobento-ch/service-pdf#basic-usage).
It explains how to create PDF definitions using views, HTML, or raw content, and provides the foundation for how App-PDF builds on top of the underlying service.

### Using PDF Handler

[](#using-pdf-handler)

The PDF handler coordinates everything that happens after you define a PDF.
By attaching parameters to the `Pdf` object, you can instruct the handler to:

- store the rendered PDF
- trigger a file download
- send the PDF to a webhook
- queue the PDF for asynchronous processing

These parameters can be used **individually or combined**.
When queueing is enabled, the handler prepares a queue job and then executes only the **immediate actions** (such as download).
All deferred actions - like storing the PDF or sending it to a webhook - are performed later inside the queue job.
The PDF is rendered only once, even when multiple actions are defined.

The `Pdf` object offers a fluent API, allowing you to define content and attach parameters in a clean and expressive way.

**Example**

The example below shows how to define a PDF, attach multiple parameters, and let the handler orchestrate the workflow:

```
use Tobento\App\Pdf\Pdf;
use Tobento\App\Pdf\PdfHandlerInterface;

class SomeService
{
    public function store(PdfHandlerInterface $pdfHandler): void
    {
        $pdf = new Pdf()
            ->html('Lorem Ipsum')

            // Use a specific PDF generator (optional, must be defined in pdf.php config)
            ->generator(
                name: 'name',
            )

            // Store the generated PDF using the specified storage and path
            ->store(
                storage: 'uploads',
                path: 'folder/document.pdf',
            )

            // Send the PDF to a webhook endpoint
            ->webhook(
                url: 'https://example.com/pdf',

                // Additional payload data for the webhook request (optional)
                payload: [],

                // Whether the PDF should be attached to the webhook request (default: true)
                attachPdf: true,
            )

            // Queue the PDF for asynchronous processing (all parameters optional)
            ->queue(
                name: 'default',
                delay: 0,
                retry: 3,
                priority: 0,
                encrypt: false,
                renderTemplates: true,
            )

            // Immediate actions (executed after queue evaluation)
            ->download(
                filename: 'document.pdf',
                headers: [],   // optional
                inline: true,  // optional, default is false
            );

        // Process the PDF according to the defined parameters
        $pdfHandler->handle($pdf);
    }
}
```

#### Storing

[](#storing)

The `store()` parameter instructs the handler to save the rendered PDF to a specific storage and path.
If queueing is enabled, storing is **not** performed during the request. Instead, it is executed later inside the queue job.

This feature is powered by the application's [app-file-storage](https://github.com/tobento-ch/app-file-storage) system, which provides unified storage handling, directory creation, and driver-based file operations.

```
use Tobento\App\Pdf\Pdf;

$pdf = new Pdf()
    ->html('Invoice')
    ->store(
        storage: 'uploads',
        path: 'invoices/invoice.pdf',
    );
```

The storage name must refer to a configured storage in your application
(for example via your file storage configuration).
The path may include folders and will be created automatically if supported by the storage driver.

**Events**

When storing is used, the following events may be dispatched:

```
use Tobento\App\Pdf\Event;
```

- **PdfGenerated**
    Fired before the PDF is written to storage. Useful for logging, validation, or modifying metadata.
- **PdfStored**
    Fired after the PDF has been successfully written to storage. Useful for notifications, indexing, or triggering follow‑up processes.
- **PdfQueued**
    Fired when the PDF has been queued for later processing. Useful for monitoring background jobs or triggering follow-up actions.

These events allow you to hook into the storage lifecycle and extend the behavior as needed.

#### Downloading

[](#downloading)

The `download()` parameter instructs the handler to emit the rendered PDF as an HTTP response.
Downloading is always an **immediate action** and is executed during the request, even when queueing is enabled.

```
use Tobento\App\Pdf\Pdf;

$pdf = new Pdf()
    ->html('Report')
    ->download(
        filename: 'report.pdf',
        headers: [],   // optional
        inline: false, // optional, default is false
    );
```

When a download parameter is present, the download handler:

- creates a PDF stream from the generated content
- builds a PSR-7 response with `Content-Type: application/pdf`
- sets the `Content-Disposition` header as either `attachment` or `inline` based on the `inline` flag
- applies any custom headers defined on the parameter
- emits the response using the configured `SimpleResponseEmitterInterface`
- throws a `PdfException` if the response cannot be emitted

If `inline` is set to `true`, the PDF is displayed in the browser (if supported); otherwise, the browser will treat it as a file download.

**Events**

When downloading is used, the following events may be dispatched:

```
use Tobento\App\Pdf\Event;
```

- **PdfGenerated**
    Fired after the PDF has been rendered and before it is emitted as an HTTP response. Useful for logging or modifying metadata.
- **PdfDownloaded**
    Fired after the PDF has been successfully emitted as a response. Useful for auditing, monitoring, or triggering follow-up processes.

These events allow you to hook into the download lifecycle and extend the behavior as needed.

#### Webhook

[](#webhook)

The `webhook()` parameter instructs the handler to send the generated PDF to a remote endpoint.
Webhook delivery is always an **immediate action** and is executed during the request, even when queueing is enabled.

```
use Tobento\App\Pdf\Pdf;

$pdf = new Pdf()
    ->html('Invoice')
    ->webhook(
        url: 'https://example.com/pdf-endpoint',

        // Additional payload data for the webhook request (optional)
        payload: [],

        // Whether the PDF should be attached to the webhook request (default: true)
        attachPdf: true,
    );
```

When a webhook parameter is present, the webhook handler:

- sends a POST request to the configured endpoint
- builds a JSON payload from the provided data
- attaches the generated PDF as a Base64‑encoded string if attachPdf is enabled
- applies any custom headers
- throws a PdfException if the endpoint responds with an error

If the remote endpoint responds with an error or cannot be reached, a PdfException may be thrown depending on your configuration.

**Example Webhook Payload**

When a webhook is configured, the handler sends a JSON payload to the specified endpoint.

If `attachPdf` is **true** (default), the generated PDF is included as a Base64‑encoded string:

```
POST https://example.com/webhook-endpoint
Content-Type: application/json
X-Custom: Foo

{
    "order_id": 12345,
    "customer": "John Doe",
    "pdf": "JVBERi0xLjQKJcTl8uXrp......"
}

```

**Notes**

- The PDF is always Base64‑encoded when attached.
- Any array passed as $payload is merged directly into the JSON body.
- If the endpoint returns an HTTP status ≥ 400, a PdfException is thrown.

**Events**

When a webhook is used, the following events may be dispatched:

```
use Tobento\App\Pdf\Event;
```

- **PdfGenerated**
    Fired after the PDF has been rendered and before the webhook request is sent. Useful for logging, validation, or modifying metadata.
- **PdfWebhookSent**
    Fired after the webhook has been successfully delivered. Useful for auditing, monitoring, or triggering follow-up processes.

These events allow you to hook into the webhook lifecycle and extend the behavior as needed.

#### Queueing

[](#queueing)

Queueing allows PDF generation and its associated actions (such as storing or sending a webhook)
to be executed **asynchronously** in a background worker instead of during the HTTP request.

This is useful when generating large PDFs or when performing slow operations such as storage or webhook delivery.

This feature is powered by the application's [app-queue](https://github.com/tobento-ch/app-queue) system, which handles job dispatching, retry logic, delays, and worker execution.

```
use Tobento\App\Pdf\Pdf;

$pdf = new Pdf()
    ->html('Invoice')
    ->queue(
        // The queue name or channel where the job should be pushed
        name: 'default',

        // Delay (in seconds) before the job becomes available for processing
        delay: 0,

        // Number of retry attempts if the job fails
        retry: 3,

        // Job priority (lower = processed earlier, depending on queue system)
        priority: 0,

        // Encrypt the PDF content before sending it to the queue worker
        encrypt: false,

        // Render templates before queueing (if using templated PDFs)
        renderTemplates: true,
    );
```

When queueing is enabled:

- the PDF is not generated during the request
- the job is pushed onto the configured queue
- a worker later generates the PDF in the background
- any additional actions (store, webhook, etc.) are executed inside the queued job
- the HTTP response remains fast and unaffected by PDF processing time

Queueing does not change the behavior of the individual handlers - it only defers their execution.

**Example Workflow**

If you combine queueing with storing and a webhook:

```
use Tobento\App\Pdf\Pdf;

$pdf = new Pdf()
    ->html('Invoice')
    ->store('uploads', 'invoices/invoice.pdf')
    ->webhook('https://example.com/endpoint')
    ->queue();
```

The worker will:

- generate the PDF
- store it
- send the webhook
- dispatch the corresponding events

All outside the original HTTP request.

**Events**

When queueing is used, the following events may be dispatched:

```
use Tobento\App\Pdf\Event;
```

- **PdfQueued**
    Fired when the PDF job has been successfully pushed onto the queue. Useful for monitoring background processing or triggering follow-up actions.
- **PdfGenerated**
    Fired inside the queue worker after the PDF has been rendered. Useful for logging, validation, or modifying metadata before any actions are executed.
- **PdfStored**
    Fired after the PDF has been successfully written to storage by the queue worker. Useful for notifications, indexing, or triggering follow-up processes.
- **PdfWebhookSent**
    Fired after the webhook has been successfully delivered by the queue worker. Useful for auditing, monitoring, or chaining external processes.

These events allow you to hook into the queue lifecycle and extend the behavior as needed.

Credits
=======

[](#credits)

- [Tobias Strub](https://www.tobento.ch)
- [All Contributors](../../contributors)

###  Health Score

35

—

LowBetter than 77% of packages

Maintenance71

Regular maintenance activity

Popularity2

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

2

Last Release

163d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/055d6a1b5c2384bb179c75ab0b55914231d898fdc4dffeb30770f81200e52206?d=identicon)[TOBENTOch](/maintainers/TOBENTOch)

---

Top Contributors

[![tobento-ch](https://avatars.githubusercontent.com/u/16684832?v=4)](https://github.com/tobento-ch "tobento-ch (1 commits)")

---

Tags

pdfpackageapptobento

###  Code Quality

TestsPHPUnit

Static AnalysisPsalm

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tobento-app-pdf/health.svg)

```
[![Health](https://phpackages.com/badges/tobento-app-pdf/health.svg)](https://phpackages.com/packages/tobento-app-pdf)
```

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
