跳到內容

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. 有一個 Gotenberg 服務可透過 HTTPS 連線。純 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,接著將一個 HEAD 送至 <apiUrl>/health

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 算繪管線。