跳转到内容

NextPDF Gotenberg 快速入门

本教程会逐步演示如何将一个 .docx 文件转换为 PDF。完成后,你会得到三样东西:一个可运行的桥接器实例、一个已验证的服务连接,以及一份保存在磁盘上的 PDF。完整程序位于仓库的 examples/convert-office-to-pdf.php。下面的代码片段均摘自该程序。

本页面是教程,因此会先演示顺利路径。生产环境中的考量——密钥来源、重试、超时与可观测性——请参见 /integrations/gotenberg/production-usage/。

请确认以下三件事:

  1. 已运行 composer require nextpdf/gotenberg,并已安装 PSR-18 client 与 PSR-17 factory。参见 /integrations/gotenberg/install/。
  2. 有一个可通过 HTTPS 连接的 Gotenberg 服务。纯 http:// 会在任何请求离开进程前就被桥接器拒绝。
  3. 你有一份示例文件,格式为下列任一种:.docx.xlsx.pptx.odt.ods,或 .odp。其他扩展名会触发 ValueError 并被拒绝。

GotenbergConfig 是不可变值对象。它至少需要你的 Gotenberg 服务的 HTTPS 基础 URL:

use NextPDF\Gotenberg\GotenbergConfig;
$config = new GotenbergConfig(
apiUrl: 'https://gotenberg.example.com',
timeout: 60,
apiKey: $apiKey,
);

timeout 是以秒为单位的传输超时时间,由基于 cURL 的传输层应用。apiKey 非空时,会以 Authorization: Bearer <token> 发送。如果你的 Gotenberg 部署不需要 token,就将 apiKey 留空。

桥接器会接收配置及其 PSR 协作组件。这里还注入了 responseFactory,以启用具备 DNS 钉选与 TLS 钉选的 cURL 传输层:

use NextPDF\Gotenberg\GotenbergBridge;
$bridge = new GotenbergBridge(
config: $config,
httpClient: $httpClient,
requestFactory: $requestFactory,
streamFactory: $streamFactory,
responseFactory: $responseFactory,
);

桥接器本身绝不会自行构造 HTTP client。请使用你已安装的任意 PSR-18 client 与 PSR-17 factory。示例文件在注释中演示了 Guzzle 的接线方式。

在转换任何内容之前,先探测服务。这个探测会先在不产生任何网络流量的情况下验证 URL,然后向 <apiUrl>/health 发送一个 HEAD

if (! $bridge->isAvailable()) {
throw new \RuntimeException('Gotenberg is not reachable.');
}

对于空白、非 HTTPS 或私有地址的 URL,以及任何网络错误,isAvailable() 都会返回 false(绝不抛出异常)。当 /health 返回低于 500 的状态码时,即代表服务可用。

convertFile() 接收磁盘上的路径。该路径会经过规范化处理,以阻止目录穿越。扩展名会映射到受支持的格式。大小和文件名也会经过筛查。随后会向 <apiUrl>/forms/libreoffice/convert 发送一个 multipart 请求:

use NextPDF\Gotenberg\GotenbergConvertException;
try {
$result = $bridge->convertFile('/path/to/report.docx');
} catch (GotenbergConvertException $e) {
// Bad config, HTTP failure, non-200, wrong Content-Type, or non-PDF body.
throw $e;
} catch (\RuntimeException $e) {
// Non-HTTPS URL, private address, oversized input, or unsafe filename.
throw $e;
} catch (\ValueError $e) {
// Extension is not one of the six recognised Office formats.
throw $e;
}

若要转换已经保存在内存中的字节,请使用 convertString()。传入原始文件名,以便桥接器检测扩展名:

$pdf = $bridge->convertString($docxBytes, 'report.docx');

结果包含三样东西:PDF 字节、来源格式,以及一项有效性检查:

if (! $result->isValid()) {
throw new \RuntimeException('Result is not a valid PDF.');
}
\file_put_contents('/path/to/report.pdf', $result->pdfData);
\printf(
"Converted %s (%d bytes)\n",
$result->sourceFormat->value,
$result->size(),
);

isValid() 在主体非空且以 %PDF 开头时返回 true。size() 是字节长度。从这里开始,这份 PDF 就是普通流,你可以交给 NextPDF 进行后处理。

完整、可运行的程序位于软件包仓库的 examples/convert-office-to-pdf.php。它涵盖参数解析、由环境变量驱动的配置、健康探测、详尽的错误处理,以及写入流程。按以下方式运行:

Terminal window
GOTENBERG_URL=https://gotenberg.example.com \
php examples/convert-office-to-pdf.php report.docx report.pdf
  • /integrations/gotenberg/configuration/ — 所有选项,以及传输层选择规则。
  • /integrations/gotenberg/production-usage/ — 密钥、重试、超时、日志和并发。
  • /integrations/gotenberg/troubleshooting/ — 这段代码可能抛出的所有异常及其含义。
  • /integrations/gotenberg/integration/ — 通过该服务驱动 NextPDF 渲染管线。