Gotenberg — Office 轉換橋接套件¶
NextPDF Gotenberg
nextpdf/gotenberg 橋接 Gotenberg 服務與 NextPDF Core,讓 Office 文件(Word、Excel、PowerPoint、LibreOffice 格式)可以無縫轉換為 PDF,並透過 PageImport 機制嵌入 NextPDF 文件工作流程。
PHP Compatibility
This example uses PHP 8.5 syntax. If your environment runs PHP 8.1 or 7.4, use NextPDF Backport for a backward-compatible build.
核心能力¶
| 功能 | 說明 |
|---|---|
| Office 格式轉換 | DOCX、XLSX、PPTX、ODT、ODS、ODP → PDF |
| HTML 渲染 | Chromium-backed HTML → PDF(Gotenberg 內建) |
| 頁面合併 | 轉換結果透過 PageImport 嵌入 Core 文件 |
| 健康檢查 | Gotenberg 服務健康狀態監控 |
| 重試策略 | 網路失敗的指數退避重試 |
架構概覽¶
PHP 應用程式
└─▶ GotenbergClient::convert(OfficeFile)
│ (multipart/form-data HTTP POST)
└─▶ Gotenberg Service (Docker)
└─▶ LibreOffice / Chromium
└─▶ PDF bytes
└─▶ PdfParser → PageImport → Core Document
安裝¶
需要執行中的 Gotenberg 服務實例。參見 Docker 設定。
快速開始¶
<?php
declare(strict_types=1);
use NextPDF\Gotenberg\GotenbergClient;
use NextPDF\Gotenberg\Config\GotenbergConfig;
// 建立客戶端
$client = GotenbergClient::create(
config: GotenbergConfig::create(
baseUrl: 'http://localhost:3000', // Gotenberg 服務位址
timeoutSeconds: 30,
apiKey: $_ENV['GOTENBERG_API_KEY'] ?? null, // 可選:API 金鑰認證
),
);
// 轉換 DOCX 為 PDF
$pdfBytes = $client->convertOffice(
file: '/path/to/contract.docx',
options: OfficeConversionOptions::default(),
);
file_put_contents('/tmp/contract.pdf', $pdfBytes);
與 NextPDF Core 整合¶
Gotenberg 轉換結果可直接透過 PageImport 嵌入 NextPDF Core 文件:
use NextPDF\Core\Document;
use NextPDF\Artisan\PdfParser;
use NextPDF\Artisan\PageImport\PageImporter;
use NextPDF\Gotenberg\GotenbergClient;
// 1. 轉換 Office 文件
$client = GotenbergClient::create(/* config */);
$pdfBytes = $client->convertOffice('/path/to/report.docx');
// 2. 解析轉換結果
$parser = PdfParser::fromBytes($pdfBytes);
// 3. 建立 NextPDF 文件並匯入頁面
$document = Document::createStandalone(title: 'Combined Report');
$importer = PageImporter::create(document: $document);
// 加入封面頁(純 NextPDF Core 生成)
$document->addPage();
$document->text('Q1 Report Package', x: 20, y: 30, fontSize: 24);
// 匯入 Office 轉換頁面
$xObjectIds = $importer->importAll($parser->pages());
foreach ($xObjectIds as $xObjectId) {
$document->addPage();
$document->placeXObject(id: $xObjectId, position: Position::create(0, 0));
}
$document->save('/tmp/combined-report.pdf');
健康檢查¶
$health = $client->health();
if (!$health->isHealthy()) {
throw new \RuntimeException("Gotenberg service unavailable: {$health->status()}");
}
echo "Gotenberg version: " . $health->version(); // e.g. "8.x.x"
參見¶
- Office 格式轉換 — 各格式的詳細選項與轉換品質控制
- Docker 設定 — Gotenberg 服務的 Docker 與 docker-compose 設定