Office 轉 PDF 指南
先決條件
composer require nextpdf/gotenberg
服務需求
| 元件 | 版本需求 | 說明 |
| Gotenberg | ^8.0 | 微服務,需獨立部署 |
| LibreOffice | 內建於 Gotenberg | 辦公室文件轉換引擎 |
基本用法
use NextPDF\Gotenberg\GotenbergClient;
use NextPDF\Gotenberg\ValueObjects\ConversionOptions;
$client = GotenbergClient::create(
baseUrl: 'http://gotenberg:3000',
httpClient: $psrHttpClient, // PSR-18 相容客戶端
factory: $psrRequestFactory,
);
$pdf = $client->convertFile(
path: '/uploads/report.docx',
options: ConversionOptions::default(),
);
$pdf->save('/output/report.pdf');
支援的文件格式
| 格式 | 副檔名 | 支援程度 |
| Microsoft Word | .docx, .doc | 完整 |
| Microsoft Excel | .xlsx, .xls | 完整(無巨集) |
| Microsoft PowerPoint | .pptx, .ppt | 完整 |
| OpenDocument Text | .odt | 完整 |
| OpenDocument Spreadsheet | .ods | 完整 |
| Rich Text Format | .rtf | 部分 |
| CSV | .csv | 基本 |
轉換選項
use NextPDF\Gotenberg\ValueObjects\PaperSize;
$options = ConversionOptions::create()
->withPaperSize(PaperSize::A4)
->withMargin(top: 15, right: 15, bottom: 15, left: 15)
->withLandscape(false)
->withPrintBackground(true)
->withNativePageRanges('1-5');
批次轉換
$files = ['/uploads/doc1.docx', '/uploads/doc2.xlsx'];
$results = $client->convertBatch(
files: $files,
options: ConversionOptions::default(),
);
foreach ($results as $path => $pdf) {
$pdf->save("/output/{$path}.pdf");
}
PDF 後處理
// 轉換後,可用 NextPDF Core 進行後處理
$converted = $client->convertFile(path: '/uploads/report.docx');
// 使用 Core 加水印
$processor = $converted->loadIntoDocument();
$processor->drawing()->watermark(text: 'CONFIDENTIAL', opacity: 0.3);
$processor->save('/output/watermarked.pdf');
與 Laravel 整合
與 Symfony 整合
健康檢查與監控
延伸閱讀