Gotenberg API reference
At a glance
Section titled “At a glance”The Gotenberg package exposes one service bridge, GotenbergBridge. It converts an Office document (docx, xlsx, pptx, odt, ods, odp) to Portable Document Format (PDF) by sending a POST request to an external Gotenberg service. The bridge works with the value objects you pass in or read from: GotenbergConfig (the immutable service descriptor and limits), OfficeFormat (the supported-format enum), GotenbergConvertPayload (the multipart request body), and GotenbergConvertResult (the parsed PDF response). A second tier, GotenbergSecurityPolicy, GotenbergResponseParser, and PinnedCurlTransport, provides the validation, parsing, and pinned-transport machinery the bridge drives internally. Use that tier only when you write custom transport or test code.
Start here: Create a GotenbergConfig with your Hypertext Transfer Protocol Secure (HTTPS) service URL, then pass it to a GotenbergBridge with your PSR-18 client and PSR-17 factories. Call convertFile() or convertString(), then read pdfData from the returned GotenbergConvertResult.
Common tasks
Section titled “Common tasks”Use these verified, runnable snippets for the package tasks you are most likely to perform.
Convert a file on disk to PDF
Section titled “Convert a file on disk to PDF”Point the bridge at a path. It detects the format from the extension.
<?php
declare(strict_types=1);
use NextPDF\Gotenberg\GotenbergBridge;use NextPDF\Gotenberg\GotenbergConfig;
$config = new GotenbergConfig( apiUrl: 'https://gotenberg.example.com', timeout: 60, apiKey: $apiKey,);
$bridge = new GotenbergBridge( config: $config, httpClient: $psrHttpClient, requestFactory: $psrRequestFactory, streamFactory: $psrStreamFactory, responseFactory: $psrResponseFactory,);
$result = $bridge->convertFile('/path/to/report.docx');
\file_put_contents('/path/to/report.pdf', $result->pdfData);What it does: validates the URL, path, size, and filename; sends one multipart request; and writes the returned PDF bytes to disk.
Convert in-memory bytes to PDF
Section titled “Convert in-memory bytes to PDF”Use convertString() when you already have the bytes. The filename drives format detection.
<?php
declare(strict_types=1);
use NextPDF\Gotenberg\GotenbergBridge;
/** @var GotenbergBridge $bridge */$result = $bridge->convertString($xlsxBytes, 'spreadsheet.xlsx');
if (! $result->isValid()) { throw new \RuntimeException('Conversion did not return a valid PDF.');}What it does: detects xlsx from the filename, converts the bytes, and confirms that the result begins with the %PDF signature before you use it.
Probe service readiness before converting
Section titled “Probe service readiness before converting”Gate work with isAvailable(). It validates the URL without network traffic, then sends one HEAD request to /health.
<?php
declare(strict_types=1);
use NextPDF\Gotenberg\GotenbergBridge;
/** @var GotenbergBridge $bridge */if (! $bridge->isAvailable()) { throw new \RuntimeException('Gotenberg is not reachable.');}What it does: returns false (never throws) for an empty, non-HTTPS, or private-address URL and for any network error, so you can fail fast before you dispatch a conversion.
Bridge
Section titled “Bridge”This table covers the bridge surface. Use it when you construct GotenbergBridge or call its conversion and readiness methods.
| Symbol | Parameters | Default behavior | Returns | Throws or fails with | Notes |
|---|---|---|---|---|---|
new GotenbergBridge(GotenbergConfig $config, ClientInterface $httpClient, RequestFactoryInterface $requestFactory, StreamFactoryInterface $streamFactory, ?LoggerInterface $logger = null, ?HtmlSecurityPolicyInterface $htmlSecurityPolicy = null, ?ResponseFactoryInterface $responseFactory = null) | Config, PSR-18 client, PSR-17 factories, optional logger, optional HTML policy, optional response factory. | Uses DefaultHtmlSecurityPolicy when you do not supply a policy. | GotenbergBridge | Container wiring errors. | Response factory enables pinned cURL transport when pinning is required. |
GotenbergBridge::convertFile(string $filePath) | Filesystem path to an Office document. | Uses the file extension for format detection. | GotenbergConvertResult | GotenbergConvertException, RuntimeException, ValueError for unsupported format. | Resolves the real path and checks readability, size, and filename. |
GotenbergBridge::convertString(string $content, string $fileName) | Raw bytes and original filename. | Uses the filename extension for format detection. | GotenbergConvertResult | Same as convertFile. | Use when your application already has file bytes. |
GotenbergBridge::isAvailable() | none. | Sends HEAD to /health when config is valid. | bool | Returns false on errors. | Readiness signal only. |
GotenbergBridge::getHtmlSecurityPolicy() | none. | Returns the configured parse-layer policy. | HtmlSecurityPolicyInterface | none expected. | Complements transport-level security policy. |
Configuration and payloads
Section titled “Configuration and payloads”This table covers value objects you build directly: the GotenbergConfig service descriptor and the GotenbergConvertPayload/GotenbergConvertResult request and response carriers. Use them when you need finer control than the two conversion entry points provide.
| Symbol | Parameters | Default behavior | Returns | Throws or fails with | Notes |
|---|---|---|---|---|---|
new GotenbergConfig(string $apiUrl = '', int $timeout = 30, int $maxFileSize = 52428800, string $apiKey = '', array $pinnedPublicKeys = [], array $backupPublicKeys = []) | API URL, timeout, max file size, bearer token, pin sets. | Empty URL is invalid; the default max size is 50 MiB. | GotenbergConfig | none expected. | Keep API key secret. |
GotenbergConfig::fromArray(array $config) | api_url, timeout, max_file_size, api_key, pin arrays. | Missing optional values use constructor defaults. | GotenbergConfig | none expected. | String lists ignore non-string values. |
GotenbergConfig::isValid() | none. | Valid when the API URL is non-empty. | bool | none expected. | URL safety is validated before any network operation. |
GotenbergConfig::allPublicKeyPins() | none. | Combines primary and backup pins. | list<string> | none expected. | An empty list disables pinning. |
new GotenbergConvertPayload(string $fileName, string $fileContent, OfficeFormat $format, bool $landscape = false, string $nativePageRanges = '') | Filename, bytes, format, orientation flag, page ranges. | Portrait; all pages. | GotenbergConvertPayload | none expected. | The payload is converted to multipart form data. |
GotenbergConvertPayload::toMultipartBody(string $boundary) | Multipart boundary. | Includes the page-range field only when it is non-empty. | string | none expected. | The bridge generates the boundary. |
GotenbergConvertPayload::contentType(string $boundary) | Multipart boundary. | Uses multipart/form-data. | string | none expected. | Attach as the request Content-Type. |
new GotenbergConvertResult(string $pdfData, OfficeFormat $sourceFormat, float $renderTimeMs = 0.0) | Converted PDF bytes, source format, optional render duration. | Render duration is 0.0 when it is not measured. | GotenbergConvertResult | none expected. | Returned by GotenbergResponseParser::parse(). |
GotenbergConvertResult::isValid() | none. | Valid when converted PDF bytes are non-empty and look like PDF data. | bool | none expected. | Check before persisting or streaming the result. |
GotenbergConvertResult::size() | none. | Counts the converted PDF bytes. | int | none expected. | Use it for quotas, telemetry, and response limits. |
Office formats
Section titled “Office formats”This table covers the OfficeFormat enum. Use it to map an extension to a format, read its upload MIME type, or check which six formats are supported.
| Symbol | Parameters | Default behavior | Returns | Throws or fails with | Notes |
|---|---|---|---|---|---|
OfficeFormat::fromExtension(string $ext) | File extension with or without leading dot. | Matches case-insensitively. | OfficeFormat | ValueError for unsupported extension. | Supported values: docx, xlsx, pptx, odt, ods, odp. |
OfficeFormat::mimeType() | none. | Maps the enum case to the upload MIME type. | string | none expected. | Used in the multipart file part. |
OfficeFormat::extension() | none. | Returns the backed value. | string | none expected. | Useful in diagnostics and filenames. |
Security, parsing, and transport
Section titled “Security, parsing, and transport”This table covers the internal machinery the bridge drives for you. Use it only when you write custom transport, make a custom Hypertext Transfer Protocol (HTTP) call that still needs package parsing, or inspect low-level security and pinning behavior.
| Symbol | Parameters | Default behavior | Returns | Throws or fails with | Notes |
|---|---|---|---|---|---|
GotenbergSecurityPolicy::validateApiUrl(string $url) | API base URL. | Parses and validates the destination before any network operation. | array | RuntimeException for unsafe or invalid URLs. | Keeps server-side request forgery (SSRF)-style endpoint mistakes out of conversion code. |
GotenbergSecurityPolicy::assertPinsStillValid(string $host, array $pinnedIps) | Host and pinned Internet Protocol (IP) list. | Verifies Domain Name System (DNS) pin expectations. | void | RuntimeException when pins are stale or invalid. | Use it in pinned deployments and operational diagnostics. |
GotenbergSecurityPolicy::validateFileSize(int $size, int $maxSize) | Actual size and configured maximum. | Accepts files at or below the configured limit. | void | RuntimeException when the file is too large. | Enforce before request construction. |
GotenbergSecurityPolicy::validateFileName(string $name) | Original filename. | Rejects unsafe or unsupported filename forms. | void | RuntimeException for invalid names. | Prevents malformed multipart filenames. |
GotenbergResponseParser::parse(ResponseInterface $response, OfficeFormat $format) | PSR-7 response and expected Office format. | Extracts converted PDF bytes from a successful response. | GotenbergConvertResult | GotenbergConvertException for failed responses or invalid PDF output. | Central parser for file and string conversion. |
new PinnedCurlTransport(ResponseFactoryInterface $responseFactory, StreamFactoryInterface $streamFactory, array $pinnedIps = [], array $pinnedPublicKeys = [], int $timeoutSeconds = 30) | PSR-17 factories, pinned IPs, pinned public keys, timeout. | No pins and 30 second timeout. | PinnedCurlTransport | none expected. | Use only when cURL-level pinning is required. |
PinnedCurlTransport::sendRequest(RequestInterface $request) | PSR-7 request. | Sends through cURL with the configured timeout and pinning controls. | ResponseInterface | GotenbergConvertException on cURL/transport failure. | Use it when pinning cannot be delegated to another HTTP client. |
PinnedCurlTransport::buildCurlOptions(RequestInterface $request, string $host, int $port) | Request, host, and port. | Builds the cURL option array that sendRequest() uses. | array | Invalid request or pin configuration errors. | Low-level diagnostics and test hook. |
Development notes
Section titled “Development notes”- Treat Gotenberg as an external service boundary. Set timeout, size, URL, and pin policy deliberately.
convertFile()reads the whole file into memory before request construction.- Log metadata such as filename and content length, not file contents.