Skip to content

Gotenberg API reference

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.

Use these verified, runnable snippets for the package tasks you are most likely to perform.

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.

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.

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.

This table covers the bridge surface. Use it when you construct GotenbergBridge or call its conversion and readiness methods.

SymbolParametersDefault behaviorReturnsThrows or fails withNotes
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.GotenbergBridgeContainer 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.GotenbergConvertResultGotenbergConvertException, 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.GotenbergConvertResultSame as convertFile.Use when your application already has file bytes.
GotenbergBridge::isAvailable()none.Sends HEAD to /health when config is valid.boolReturns false on errors.Readiness signal only.
GotenbergBridge::getHtmlSecurityPolicy()none.Returns the configured parse-layer policy.HtmlSecurityPolicyInterfacenone expected.Complements transport-level security policy.

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.

SymbolParametersDefault behaviorReturnsThrows or fails withNotes
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.GotenbergConfignone 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.GotenbergConfignone expected.String lists ignore non-string values.
GotenbergConfig::isValid()none.Valid when the API URL is non-empty.boolnone 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.GotenbergConvertPayloadnone 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.stringnone expected.The bridge generates the boundary.
GotenbergConvertPayload::contentType(string $boundary)Multipart boundary.Uses multipart/form-data.stringnone 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.GotenbergConvertResultnone expected.Returned by GotenbergResponseParser::parse().
GotenbergConvertResult::isValid()none.Valid when converted PDF bytes are non-empty and look like PDF data.boolnone expected.Check before persisting or streaming the result.
GotenbergConvertResult::size()none.Counts the converted PDF bytes.intnone expected.Use it for quotas, telemetry, and response limits.

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.

SymbolParametersDefault behaviorReturnsThrows or fails withNotes
OfficeFormat::fromExtension(string $ext)File extension with or without leading dot.Matches case-insensitively.OfficeFormatValueError for unsupported extension.Supported values: docx, xlsx, pptx, odt, ods, odp.
OfficeFormat::mimeType()none.Maps the enum case to the upload MIME type.stringnone expected.Used in the multipart file part.
OfficeFormat::extension()none.Returns the backed value.stringnone expected.Useful in diagnostics and filenames.

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.

SymbolParametersDefault behaviorReturnsThrows or fails withNotes
GotenbergSecurityPolicy::validateApiUrl(string $url)API base URL.Parses and validates the destination before any network operation.arrayRuntimeException 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.voidRuntimeException 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.voidRuntimeException when the file is too large.Enforce before request construction.
GotenbergSecurityPolicy::validateFileName(string $name)Original filename.Rejects unsafe or unsupported filename forms.voidRuntimeException 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.GotenbergConvertResultGotenbergConvertException 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.PinnedCurlTransportnone 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.ResponseInterfaceGotenbergConvertException 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.arrayInvalid request or pin configuration errors.Low-level diagnostics and test hook.
  • 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.