跳转到内容

Gotenberg API 参考文档

Gotenberg 包对外只暴露一个服务桥接 GotenbergBridge,负责把 Office 文档(docxxlsxpptxodtodsodp)通过 POST 发送到外部 Gotenberg 服务并转换为 PDF。围绕这个桥接层,你会读取或传入几个辅助值对象:GotenbergConfig(不可变的服务描述对象和限制)、OfficeFormat(支持格式的枚举)、GotenbergConvertPayload(multipart 请求主体),以及 GotenbergConvertResult(解析后的 PDF 响应)。第二层包括 GotenbergSecurityPolicyGotenbergResponseParser,以及 PinnedCurlTransport,它们是桥接层内部驱动的验证、解析与固定传输机制。只有在编写自定义传输或测试代码时才会用到它们。

**从这里开始:**使用你的 HTTPS 服务 URL 构造一个 GotenbergConfig,再把它连同你的 PSR-18 客户端和 PSR-17 工厂接入一个 GotenbergBridge。接着调用 convertFile()convertString(),读取返回的 GotenbergConvertResult 上的 pdfData

下面列出这个包最常见的实际任务,每项都附有经过验证、可直接运行的代码片段。

把桥接层指向一个路径;格式会根据扩展名检测出来。

<?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);

它会:验证 URL、路径、大小和文件名,发出一个 multipart 请求,并把返回的 PDF 字节写入磁盘。

当你已经持有字节数据时,使用 convertString();格式检测由文件名决定。

<?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.');
}

它会:根据文件名检测出 xlsx,转换字节,并在你使用结果前确认它以 %PDF 签名开头。

isAvailable() 用作作业 gate;它会在不发起转换流量的情况下验证 URL,接着向 /health 发送一个 HEAD

<?php
declare(strict_types=1);
use NextPDF\Gotenberg\GotenbergBridge;
/** @var GotenbergBridge $bridge */
if (! $bridge->isAvailable()) {
throw new \RuntimeException('Gotenberg is not reachable.');
}

它会:对于空白、非 HTTPS 或私有地址的 URL,以及任何网络错误,都返回 false(绝不抛出异常),让你能在派发转换之前快速失败。

这张表列出桥接层的接口,供你在构造 GotenbergBridge 或调用其转换与就绪检查方法时使用。

符号参数默认行为返回抛出或失败条件备注
new GotenbergBridge(GotenbergConfig $config, ClientInterface $httpClient, RequestFactoryInterface $requestFactory, StreamFactoryInterface $streamFactory, ?LoggerInterface $logger = null, ?HtmlSecurityPolicyInterface $htmlSecurityPolicy = null, ?ResponseFactoryInterface $responseFactory = null)Config、PSR-18 客户端、PSR-17 工厂、可选的 logger、可选的 HTML 策略、可选的 response factory。未提供策略时使用 DefaultHtmlSecurityPolicyGotenbergBridge容器(container)装配错误。需要固定时,response factory 会启用固定的 cURL 传输。
GotenbergBridge::convertFile(string $filePath)指向 Office 文档的文件系统路径。根据扩展名检测格式。GotenbergConvertResultGotenbergConvertExceptionRuntimeException;格式不支持时为 ValueError解析文件路径,并检查可读性、大小和文件名。
GotenbergBridge::convertString(string $content, string $fileName)原始字节和源文件名。根据文件名扩展名检测格式。GotenbergConvertResultconvertFile 相同。当应用程序已经持有文件字节时使用。
GotenbergBridge::isAvailable()无。配置有效时,对 /health 发出 HEAD 请求。bool发生错误时返回 false仅用作就绪信号。
GotenbergBridge::getHtmlSecurityPolicy()无。返回已配置的解析层策略。HtmlSecurityPolicyInterface不应抛出。与传输层安全策略互补。

这张表涵盖你手动构造的值对象。需要比两个转换入口更细粒度的控制时,可使用 GotenbergConfig 服务描述对象,以及 GotenbergConvertPayload/GotenbergConvertResult 这组请求与响应载体。

符号参数默认行为返回抛出或失败条件备注
new GotenbergConfig(string $apiUrl = '', int $timeout = 30, int $maxFileSize = 52428800, string $apiKey = '', array $pinnedPublicKeys = [], array $backupPublicKeys = [])API URL、超时、文件大小上限、bearer token、固定集合。空白 URL 无效;默认大小上限为 50 MiB。GotenbergConfig不应抛出。请妥善保密 API 密钥。
GotenbergConfig::fromArray(array $config)api_urltimeoutmax_file_sizeapi_key,以及固定数组。缺少的可选值会采用构造函数默认值。GotenbergConfig不应抛出。字符串列表会忽略非字符串值。
GotenbergConfig::isValid()无。API URL 非空时即为有效。bool不应抛出。URL 安全性会在网络 I/O 之前完成验证。
GotenbergConfig::allPublicKeyPins()无。合并主固定项和备用固定项。list<string>不应抛出。空列表会停用固定。
new GotenbergConvertPayload(string $fileName, string $fileContent, OfficeFormat $format, bool $landscape = false, string $nativePageRanges = '')文件名、字节、格式、方向标志、页面范围。纵向;所有页面。GotenbergConvertPayload不应抛出。payload 会转换为 multipart 表单数据。
GotenbergConvertPayload::toMultipartBody(string $boundary)multipart 边界。只有页面范围字段非空时才会纳入。string不应抛出。边界由桥接层生成。
GotenbergConvertPayload::contentType(string $boundary)multipart 边界。使用 multipart/form-datastring不应抛出。作为请求的 Content-Type 附加。
new GotenbergConvertResult(string $pdfData, OfficeFormat $sourceFormat, float $renderTimeMs = 0.0)转换后的 PDF 字节、源格式,以及可选的渲染时长。未经测量时,渲染时长为 0.0GotenbergConvertResult不应抛出。GotenbergResponseParser::parse() 返回。
GotenbergConvertResult::isValid()无。转换后的 PDF 字节非空且看起来像 PDF 数据时即为有效。bool不应抛出。在保存或流式传输(stream)结果之前先检查。
GotenbergConvertResult::size()无。计算转换后的 PDF 字节数。int不应抛出。可用于配额、遥测(telemetry)和响应大小限制。

这张表针对 OfficeFormat 枚举。需要将扩展名映射到格式、读取其上传 MIME 类型,或检查支持的六种格式时使用。

符号参数默认行为返回抛出或失败条件备注
OfficeFormat::fromExtension(string $ext)带或不带前导句点的扩展名。不区分大小写匹配。OfficeFormatValueError,表示扩展名不受支持。支持的值:docxxlsxpptxodtods,以及 odp
OfficeFormat::mimeType()无。将枚举项映射到上传 MIME 类型。string不应抛出。用于 multipart 文件区段。
OfficeFormat::extension()无。返回枚举的 backing value。string不应抛出。对诊断和文件名很有用。

这张表列出桥接层代为驱动的内部机制。只有在编写自定义传输、编写仍想沿用包内解析逻辑的自定义 HTTP 调用,或进行底层安全性与固定诊断时,才会用到它们。

符号参数默认行为返回抛出或失败条件备注
GotenbergSecurityPolicy::validateApiUrl(string $url)API 基础 URL。在网络 I/O 之前解析并验证目标端。arrayRuntimeException,表示 URL 不安全或无效。阻止 SSRF 类型的端点(endpoint)错误进入转换代码。
GotenbergSecurityPolicy::assertPinsStillValid(string $host, array $pinnedIps)主机和固定的 IP 列表。验证 DNS 固定是否符合预期。voidRuntimeException,当固定过期或无效时。用于固定部署和运维诊断。
GotenbergSecurityPolicy::validateFileSize(int $size, int $maxSize)实际大小和已配置的上限。接受等于或低于已配置上限的文件。voidRuntimeException,当文件过大时。在构造请求之前强制检查。
GotenbergSecurityPolicy::validateFileName(string $name)源文件名。拒绝不安全或不受支持的文件名形式。voidRuntimeException,表示名称无效。避免格式不正确的 multipart 文件名。
GotenbergResponseParser::parse(ResponseInterface $response, OfficeFormat $format)PSR-7 响应和预期的 Office 格式。从成功响应中提取转换后的 PDF 字节。GotenbergConvertResultGotenbergConvertException,当响应失败或 PDF 输出无效时。文件和字符串转换共用的核心解析器。
new PinnedCurlTransport(ResponseFactoryInterface $responseFactory, StreamFactoryInterface $streamFactory, array $pinnedIps = [], array $pinnedPublicKeys = [], int $timeoutSeconds = 30)PSR-17 工厂、固定的 IP、固定的公钥,以及超时。无固定,超时为 30 秒。PinnedCurlTransport不应抛出。仅在需要 cURL 层级固定时才使用。
PinnedCurlTransport::sendRequest(RequestInterface $request)PSR-7 请求。通过 cURL 以已配置的超时和固定控制发送。ResponseInterfaceGotenbergConvertException,当 cURL/传输失败时。当固定无法委托给另一个 HTTP 客户端时使用。
PinnedCurlTransport::buildCurlOptions(RequestInterface $request, string $host, int $port)请求、主机和连接端口。构造 sendRequest() 使用的 cURL 选项数组。array请求无效或固定配置错误。底层诊断和测试挂钩。
  • 将 Gotenberg 视为外部服务边界。请谨慎配置超时、大小、URL 和固定策略。
  • convertFile() 会在构造请求之前将整个文件读入内存。
  • 记录文件名和内容长度这类元数据,而不是文件内容本身。