GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — GitHub - gotenberg/gotenberg-php: 🐘 A PHP client for interacting with Gotenberg.

BranchesTags
Open more actions menu

Latest commit

 

History

145 Commits
145 Commits

Folders and files

NameName
Last commit message
Last commit date
.github
.github
 
 
src
src
 
 
tests
tests
 
 
.gitattributes
.gitattributes
 
 
.gitignore
.gitignore
 
 
AGENTS.md
AGENTS.md
 
 
CLAUDE.md
CLAUDE.md
 
 
CONTRIBUTING.md
CONTRIBUTING.md
 
 
GEMINI.md
GEMINI.md
 
 
LICENSE
LICENSE
 
 
Makefile
Makefile
 
 
README.md
README.md
 
 
composer.json
composer.json
 
 
phpcs.xml.dist
phpcs.xml.dist
 
 
phpstan.neon
phpstan.neon
 
 
phpunit.xml
phpunit.xml
 
 

Repository files navigation

Gotenberg PHP Logo

Gotenberg PHP

A PHP client for interacting with Gotenberg

Latest Version Total Downloads Monthly Downloads Continuous Integration https://codecov.io/gh/gotenberg/gotenberg


This package is a PHP client for Gotenberg, a developer-friendly API to interact with powerful tools like Chromium and LibreOffice for converting numerous document formats (HTML, Markdown, Word, Excel, etc.) into PDF files, and more!

Gotenberg version Client
9.x (current) v3.x (current)
8.x v2.x
7.x v1.x
6.x thecodingmachine/gotenberg-php-client

Tip

A Symfony Bundle is also available!

Quick Examples

You may convert a target URL to PDF and save it to a given directory:

use Gotenberg\Gotenberg;

// Converts a target URL to PDF and saves it to a given directory.
$filename = Gotenberg::save(
    Gotenberg::chromium($apiUrl)->pdf()->url('https://my.url'), 
    $pathToSavingDirectory
);

You may also convert Office documents:

use Gotenberg\Gotenberg;
use Gotenberg\Stream;

// Converts Office documents to PDF.
$response = Gotenberg::send(
    Gotenberg::libreOffice($apiUrl)
        ->convert(
            Stream::path($pathToDocx),
            Stream::path($pathToXlsx)
        )
);

Requirement

This package requires PHP 8.3 or later, and Gotenberg 9, a containerized API for seamless PDF conversion.

See the installation guide for more information.

Installation

This package can be installed with Composer:

composer require gotenberg/gotenberg-php

We use PSR-7 HTTP message interfaces (i.e., RequestInterface and ResponseInterface) and the PSR-18 HTTP client interface (i.e., ClientInterface).

For the latter, you may need an adapter in order to use your favorite client library. Check the available adapters:

  • https://docs.php-http.org/en/latest/clients.html

If you're not sure which adapter you should use, consider using the php-http/guzzle7-adapter:

composer require php-http/guzzle7-adapter

Build a request

This package is organized around modules, namely:

use Gotenberg\Gotenberg;

Gotenberg::chromium($apiUrl);
Gotenberg::libreOffice($apiUrl);
Gotenberg::pdf($apiUrl);

Each of these modules offers a variety of methods to populate a multipart/form-data request.

After setting all optional form fields and files, you can create a request by calling the method that represents the endpoint. For example, to call the /forms/chromium/convert/url route:

use Gotenberg\Gotenberg;

Gotenberg::chromium($apiUrl)
    ->pdf()                  // Or screenshot().
    ->singlePage()           // Optional.
    ->url('https://my.url');

Tip

Head to the documentation to learn about all possibilities.

If the route requires form files, use the Stream class to create them:

use Gotenberg\DownloadFrom;
use Gotenberg\Gotenberg;
use Gotenberg\Stream;

Gotenberg::libreOffice($apiUrl)
    ->convert(Stream::path($pathToDocument));

// Alternatively, you may also set the content directly.
Gotenberg::chromium($apiUrl)
    ->pdf()
    ->assets(Stream::string('style.css', 'body{font-family: Arial, Helvetica, sans-serif;}'))
    ->html(Stream::string('index.html', '<html><head><link rel="stylesheet" type="text/css" href="style.css"></head><body><p>Hello, world!</p></body></html>'));

// Or create your stream from scratch.
Gotenberg::libreOffice($apiUrl)
    ->convert(new Stream('document.docx', $stream));

// Or upload a ZIP archive that Gotenberg unpacks.
Gotenberg::chromium($apiUrl)
    ->pdf()
    ->archives(Stream::path($pathToSiteZip))
    ->html(null);

// Or even tell Gotenberg to download the files for you.
Gotenberg::libreOffice($apiUrl)
    ->downloadFrom(
        new DownloadFrom('https://url.to.document.docx', ['MyHeader' => 'MyValue']),
        // Name the file when neither the server nor the URL path does.
        new DownloadFrom('https://url.to/download?id=42', filename: 'appendix.docx'),
    )
    ->convert();

A stage is one operation on a PDF: merge, stamp, sign, make PDF/A, and so on. Gotenberg runs the stages you give, in that order, on the PDFs a conversion makes:

use Gotenberg\Gotenberg;
use Gotenberg\Profile;
use Gotenberg\Stage;
use Gotenberg\StampPosition;
use Gotenberg\Stream;

// Merges the documents, stamps a text across the center of each page and makes the output PDF/A-2b.
Gotenberg::libreOffice($apiUrl)
    ->stages(
        Stage::merge(),
        Stage::stampText('DRAFT', fontSize: 96, opacity: 0.2, rotation: 45, position: StampPosition::Center),
        Stage::remediate(Profile::PdfA2b),
    )
    ->convert(
        Stream::path($pathToDocx),
        Stream::path($pathToXlsx)
    );

// The pdf module runs stages on the PDFs you upload, through /forms/pdf/pipe...
Gotenberg::pdf($apiUrl)
    ->stages(
        Stage::select('1-2'),
        Stage::optimize(),
    )
    ->pipe(Stream::path($pathToPdf));

// ...or one stage through its own route, such as /forms/pdf/sign.
Gotenberg::pdf($apiUrl)
    ->run(Stage::sign(Stream::path($pathToP12), certificatePassword: 'secret'), Stream::path($pathToPdf));

// It also reads and validates PDFs; Gotenberg answers JSON.
Gotenberg::pdf($apiUrl)->metadata(Stream::path($pathToPdf));
Gotenberg::pdf($apiUrl)->validate([Profile::PdfA2b, Profile::PdfUa1], Stream::path($pathToPdf));

A stage that reads a file, such as an image to stamp or a certificate, takes a Stream: the client uploads it for you. See Run stages for every stage and its order rules.

Send a request to the API

After having created the HTTP request, you have two options:

  1. Get the response from the API and handle it according to your need.
  2. Save the resulting file to a given directory.

Get a response

You may use any HTTP client that is able to handle a PSR-7 RequestInterface to call the API:

use Gotenberg\Gotenberg;

$request = Gotenberg::chromium($apiUrl)
    ->pdf()
    ->url('https://my.url');

$response = $client->sendRequest($request);

If you have a PSR-18 compatible HTTP client (see Installation), you may also use Gotenberg::send:

use Gotenberg\Gotenberg;

$request = Gotenberg::chromium($apiUrl)
    ->pdf()
    ->url('https://my.url');

try {
    $response = Gotenberg::send($request);
    return $response;
} catch (GotenbergApiErrored $e) {
    // $e->getResponse();
}

This helper will parse the response and if it is not 2xx, it will throw an exception. That's especially useful if you wish to return the response directly to the browser.

You may also explicitly set the HTTP client:

use Gotenberg\Gotenberg;

$response = Gotenberg::send($request, $client);

Save the resulting file

If you have a PSR-18 compatible HTTP client (see Installation), you may use Gotenberg::save:

use Gotenberg\Gotenberg;

$request = Gotenberg::chromium($apiUrl)
    ->pdf()
    ->url('https://my.url');
    
$filename = Gotenberg::save($request, '/path/to/saving/directory');

It returns the filename of the resulting file, as the Content-Disposition header names it. Without outputFilename(), Gotenberg names the result after its source (report.docx gives report.docx.pdf), or picks a UUID for a web page or a ZIP archive.

You may also explicitly set the HTTP client:

use Gotenberg\Gotenberg;

$response = Gotenberg::save($request, $pathToSavingDirectory, $client);

Filename

You may override the output filename with:

use Gotenberg\Gotenberg;

$request = Gotenberg::chromium($apiUrl)
    ->pdf()
    ->outputFilename('my_file')
    ->url('https://my.url');

Gotenberg will automatically add the correct file extension.

Correlation ID

By default, Gotenberg creates a UUID correlation ID that identifies a request in its logs. You may override its value thanks to:

use Gotenberg\Gotenberg;

$request = Gotenberg::chromium($apiUrl)
    ->pdf()
    ->correlationId('debug')
    ->url('https://my.url');

It will set the header Gotenberg-Trace with your value. You may also override the default header name:

use Gotenberg\Gotenberg;

$request = Gotenberg::chromium($apiUrl)
    ->pdf()
    ->correlationId('debug', 'Request-Id')
    ->url('https://my.url');

Please note that it should be the same value as defined by the --api-correlation-id-header Gotenberg's property.

The response from Gotenberg will also contain the correlation ID header. In case of error, both the Gotenberg::send and Gotenberg::save methods throw a GotenbergApiErrored exception that provides the following method for retrieving it:

use Gotenberg\Exceptions\GotenbergApiErrored;
use Gotenberg\Gotenberg;

try {
    $response = Gotenberg::send(
        Gotenberg::chromium($apiUrl)
            ->screenshot()
            ->url('https://my.url')
    );
} catch (GotenbergApiErrored $e) {
    $correlationId = $e->getCorrelationId();
    // Or if you override the header name:
    $correlationId = $e->getCorrelationId('Request-Id');
}

Webhook

You may tell Gotenberg to upload the result to a webhook instead of answering with it. Gotenberg then sends a webhook.success or webhook.error event to the events URL:

use Gotenberg\Gotenberg;
use Gotenberg\WebhookMethod;

$request = Gotenberg::chromium($apiUrl)
    ->pdf()
    ->webhook('https://my.webhook.url', 'https://my.webhook.url/events')
    ->webhookMethod(WebhookMethod::Put) // Optional, default POST.
    ->webhookExtraHttpHeaders(['Authorization' => 'Bearer …']) // Optional.
    ->url('https://my.url');

About

🐘 A PHP client for interacting with Gotenberg.

gotenberg.dev

Topics

chromiumconversioncsvdocxexcelgoogle-chromegotenberghtmllibreofficemarkdownpdfpdftkphppptxpuppeteerunoconvwkhtmltopdfwordxlsx

Resources

Readme
MIT license

Contributing

Contributing
Activity
Custom properties

Stars

407 stars

Watchers

4 watching

Forks

22 forks
Report repository

Releases

Sponsor this project

Used by

Contributors

Languages

You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.