Gotenberg API 參考
Gotenberg 套件對外只公開一個服務橋接 GotenbergBridge,負責把 Office 文件(docx、xlsx、pptx、odt、ods、odp)透過 POST 送往外部 Gotenberg 服務,轉換成 PDF。圍繞這個橋接的,是你會讀取或傳入的幾個輔助值物件:GotenbergConfig(不可變的服務描述子與限制)、OfficeFormat(支援格式的列舉)、GotenbergConvertPayload(multipart 請求主體),以及 GotenbergConvertResult(剖析後的 PDF 回應)。第二層──GotenbergSecurityPolicy、GotenbergResponseParser,以及 PinnedCurlTransport──則是橋接在內部驅動的驗證、剖析與釘選傳輸機制。只有在你撰寫自訂傳輸或測試程式碼時,才會用到這一層。
**從這裡開始:**用你的 HTTPS 服務 URL 建構一個 GotenbergConfig,再把它連同你的 PSR-18 用戶端與 PSR-17 工廠接進一個 GotenbergBridge。接著呼叫 convertFile() 或 convertString(),並從回傳的 GotenbergConvertResult 讀取 pdfData。
常見任務
標題為「常見任務」的區段以下列出這個套件最常見的實作任務,每一項都附上經過驗證、可直接執行的程式碼片段。
把磁碟上的檔案轉成 PDF
標題為「把磁碟上的檔案轉成 PDF」的區段把橋接指向一個路徑;格式會由副檔名偵測。
<?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 位元組寫入磁碟。
把記憶體中的位元組轉成 PDF
標題為「把記憶體中的位元組轉成 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,接著送出一個 HEAD 到 /health。
<?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。 | 未提供政策時使用 DefaultHtmlSecurityPolicy。 | GotenbergBridge | 容器(container)接線錯誤。 | 需要釘選時,response factory 會啟用釘選的 cURL 傳輸。 |
GotenbergBridge::convertFile(string $filePath) | 指向 Office 文件的檔案系統路徑。 | 以副檔名進行格式偵測。 | GotenbergConvertResult | GotenbergConvertException、RuntimeException,格式不支援時為 ValueError。 | resolve(解析)檔案路徑,並檢查可讀性、大小與檔名。 |
GotenbergBridge::convertString(string $content, string $fileName) | 原始位元組與原始檔名。 | 以檔名副檔名進行格式偵測。 | GotenbergConvertResult | 與 convertFile 相同。 | 當應用程式已有檔案位元組時使用。 |
GotenbergBridge::isAvailable() | 無。 | 組態有效時,對 /health 發出 HEAD 請求。 | bool | 發生錯誤時回傳 false。 | 僅作為就緒訊號。 |
GotenbergBridge::getHtmlSecurityPolicy() | 無。 | 回傳已設定的剖析層政策。 | HtmlSecurityPolicyInterface | 預期無。 | 與傳輸層安全政策互補。 |
組態與 payload
標題為「組態與 payload」的區段這張表涵蓋你會手動建構的值物件──當你需要比兩個轉換進入點更細緻的控制時,可以使用 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_url、timeout、max_file_size、api_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-data。 | string | 預期無。 | 作為請求的 Content-Type 附加。 |
new GotenbergConvertResult(string $pdfData, OfficeFormat $sourceFormat, float $renderTimeMs = 0.0) | 轉換後的 PDF 位元組、來源格式,以及選用的渲染時長。 | 未測量時,渲染時長為 0.0。 | GotenbergConvertResult | 預期無。 | 由 GotenbergResponseParser::parse() 回傳。 |
GotenbergConvertResult::isValid() | 無。 | 當轉換後的 PDF 位元組非空白且看起來像 PDF 資料時即為有效。 | bool | 預期無。 | 在保存或串流(stream)結果之前先行檢查。 |
GotenbergConvertResult::size() | 無。 | 計算轉換後的 PDF 位元組數。 | int | 預期無。 | 可用於配額、遙測(telemetry)與回應大小限制。 |
Office 格式
標題為「Office 格式」的區段這張表針對 OfficeFormat 列舉。當你需要把副檔名對映到格式、讀取它的上傳 MIME 類型,或檢查支援哪六種格式時,就會用到它。
| 符號 | 參數 | 預設行為 | 回傳 | 丟出或失敗於 | 備註 |
|---|---|---|---|---|---|
OfficeFormat::fromExtension(string $ext) | 帶或不帶開頭句點的副檔名。 | 不分大小寫比對。 | OfficeFormat | ValueError,用於不支援的副檔名。 | 支援的值:docx、xlsx、pptx、odt、ods,以及 odp。 |
OfficeFormat::mimeType() | 無。 | 把列舉案例對映到上傳 MIME 類型。 | string | 預期無。 | 用於 multipart 檔案區段。 |
OfficeFormat::extension() | 無。 | 回傳列舉的後端值。 | string | 預期無。 | 適用於診斷與檔名。 |
安全性、剖析與傳輸
標題為「安全性、剖析與傳輸」的區段這張表說明橋接替你驅動的內部機制。只有在你撰寫自訂傳輸、撰寫仍想沿用套件剖析的客製化 HTTP 呼叫,或進行低階安全性與釘選診斷時,才會用到這些項目。
| 符號 | 參數 | 預設行為 | 回傳 | 丟出或失敗於 | 備註 |
|---|---|---|---|---|---|
GotenbergSecurityPolicy::validateApiUrl(string $url) | API 基底 URL。 | 在網路 I/O 之前剖析並驗證目的端。 | array | RuntimeException,用於不安全或無效的 URL。 | 防止 SSRF 型的端點(endpoint)錯誤進入轉換程式碼。 |
GotenbergSecurityPolicy::assertPinsStillValid(string $host, array $pinnedIps) | 主機與釘選的 IP 清單。 | 驗證 DNS 釘選預期值。 | void | RuntimeException,當釘選過期或無效時。 | 用於釘選部署與維運診斷。 |
GotenbergSecurityPolicy::validateFileSize(int $size, int $maxSize) | 實際大小與已設定的上限。 | 接受等於或低於已設定上限的檔案。 | void | RuntimeException,當檔案過大時。 | 在建構請求之前先強制檢查。 |
GotenbergSecurityPolicy::validateFileName(string $name) | 原始檔名。 | 拒絕不安全或不支援的檔名形式。 | void | RuntimeException,用於無效的名稱。 | 避免格式不正確的 multipart 檔名。 |
GotenbergResponseParser::parse(ResponseInterface $response, OfficeFormat $format) | PSR-7 回應與預期的 Office 格式。 | 從成功的回應中擷取轉換後的 PDF 位元組。 | GotenbergConvertResult | GotenbergConvertException,用於失敗的回應或無效的 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 以已設定的逾時與釘選控制送出。 | ResponseInterface | GotenbergConvertException,當 cURL/傳輸失敗時。 | 當釘選無法委派給另一個 HTTP 用戶端時使用。 |
PinnedCurlTransport::buildCurlOptions(RequestInterface $request, string $host, int $port) | 請求、主機與連接埠。 | 建構 sendRequest() 所使用的 cURL 選項陣列。 | array | 請求無效或釘選組態錯誤。 | 低階診斷與測試掛勾。 |
開發備註
標題為「開發備註」的區段- 把 Gotenberg 視為外部服務邊界。請審慎設定逾時、大小、URL 與釘選政策。
convertFile()會在建構請求之前,把整個檔案讀入記憶體。- 記錄檔名與內容長度之類的中繼資料,而非檔案內容本身。