跳转到内容

NextPDF Cloudflare 集成

本页完整覆盖整个流程:安装软件包、完成配置、渲染一份 PDF,并且——如果你愿意——归档结果。每个步骤都通过 Cloudflare Worker 与 R2 驱动 NextPDF 渲染。这是一份操作指南,可与概念说明 /integrations/cloudflare/overview/ 和参考文档 /integrations/cloudflare/configuration/. 配合阅读。

Terminal window
composer require nextpdf/cloudflare:^0.1

接着,添加一个 PSR-18 客户端和若干 PSR-17 工厂,例如 Guzzle 7。这个软件包只声明 PSR 契约,本身不内置任何具体客户端,因此需要你自行提供。完整细节请参阅 /integrations/cloudflare/install/.

这个桥接器没有 service provider,也没有 bundle。它会直接由 PSR 协作对象和一个 CloudflareRendererConfig 构造而成。宿主框架会复用应用程序既有的 PSR-18 绑定,并将其绑定到自身容器中。完整的启动序列与容器绑定示例,请参阅 /integrations/cloudflare/boot-and-discovery/.

CloudflareHtmlRenderer 绑定为单例(singleton)。提供 PSR-18 客户端、PSR-17 请求与流工厂,以及一个可选的 PSR-3 日志记录器。如果要使用固定的 cURL 传输层,还需要额外提供一个 PSR-17 响应工厂。绑定示例请见 /integrations/cloudflare/boot-and-discovery/.

这个软件包会从 CloudflareRendererConfig 读取配置。机密信息应来自环境变量,绝不可来自已提交的文件:

<?php
declare(strict_types=1);
use NextPDF\Cloudflare\CloudflareRendererConfig;
$config = CloudflareRendererConfig::fromArray([
'worker_url' => getenv('CF_WORKER_URL') ?: '',
'api_token' => getenv('CF_PDF_TOKEN') ?: '',
'render_timeout' => 60,
'r2_font_bucket' => getenv('CF_R2_FONT_BUCKET') ?: null,
]);

workerUrl 必须是 HTTPS。apiToken 标注为 #[SensitiveParameter]。完整的字段参考请参阅 /integrations/cloudflare/configuration/,其中涵盖 SPKI 固定字段以及所有默认值。R2 归档配置与 API 保护层则在 /integrations/cloudflare/production-usage/ 中说明。

这里没有 service provider 可供冒烟测试。对应的启动检查如下:

$config = CloudflareRendererConfig::fromArray($appConfig['cloudflare']);
assert($config->isValid(), 'Cloudflare config incomplete');
// Optional runtime reachability check (authenticated HTTP HEAD):
if (!$renderer->isAvailable()) {
// Worker not reachable — degrade or alert.
}

isValid() 只是完整性检查,不会发出任何网络调用。isAvailable() 会执行一次经过验证的 HEAD 请求。当 Worker 无法正常工作时,它会返回 false,而不是抛出异常。

这个软件包的所有公开接口都位于 NextPDF\Cloudflare\ 之下:

类型角色
CloudflareHtmlRenderer渲染入口点:render()isAvailable()getHtmlSecurityPolicy()
CloudflareRendererConfig渲染器配置(fromArray()isValid()allPublicKeyPins())。
CloudflareRenderResult带类型的渲染结果(isValid()size())。
CloudflareRenderPayloadWorker JSON 负载(toJson())。
CloudflareResponseParserWorker 响应 → 结果解析器。
CloudflareSecurityPolicy输入与 URL 验证。
Transport\PinnedCurlTransportDNS 固定/TLS 固定的 PSR-18 传输层。
Contract\LocalRendererFactoryInterfaceContract\LocalRendererInterface本地回退(fallback)契约。
ApiProtectionApiProtectionConfigApiProtectionResultApiKeyValidator入站 API 保护。
R2ArchiveManagerR2ArchiveConfigR2ObjectKeyR2UploadResultR2 归档。
Exception\CloudflareRenderExceptionException\CloudflareNotAvailableExceptionException\InvalidSpkiPinException异常层次结构。

完整的渲染流程分步教程,请参阅 /integrations/cloudflare/quickstart/. 生产环境接线方式位于 /integrations/cloudflare/production-usage/,其中涵盖回退机制、遥测、归档与保护。

  • /integrations/cloudflare/overview/ —— 信任边界与边缘渲染模型。
  • /integrations/cloudflare/quickstart/ —— 可实际执行的第一次渲染。
  • /integrations/cloudflare/boot-and-discovery/ —— 容器接线细节。
  • /integrations/cloudflare/security-and-operations/ —— SSRF 防御、固定和运维手册。
  • /integrations/cloudflare/troubleshooting/ —— 对应到各异常的失败模式。