跳轉到

Office 格式轉換

GotenbergClientconvertOffice() 方法透過 Gotenberg 的 LibreOffice 路由(/forms/libreoffice/convert)處理各種 Office 格式轉換,支援精細的輸出品質控制。


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.

支援格式

輸入格式 MIME Type 說明
.docx application/vnd.openxmlformats-officedocument.wordprocessingml.document Word 2007+
.doc application/msword Word 97-2003(需安裝相容套件)
.xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet Excel 2007+
.xls application/vnd.ms-excel Excel 97-2003
.pptx application/vnd.openxmlformats-officedocument.presentationml.presentation PowerPoint 2007+
.ppt application/vnd.ms-powerpoint PowerPoint 97-2003
.odt application/vnd.oasis.opendocument.text LibreOffice Writer
.ods application/vnd.oasis.opendocument.spreadsheet LibreOffice Calc
.odp application/vnd.oasis.opendocument.presentation LibreOffice Impress
.rtf application/rtf Rich Text Format
.csv text/csv 逗號分隔值(LibreOffice Calc 開啟)

基本轉換

use NextPDF\Gotenberg\GotenbergClient;
use NextPDF\Gotenberg\Office\OfficeConversionOptions;

$client = GotenbergClient::create(/* config */);

// 從檔案路徑轉換
$pdfBytes = $client->convertOffice(
    file: '/path/to/contract.docx',
    options: OfficeConversionOptions::default(),
);

// 從 bytes 轉換(記憶體中的檔案)
$pdfBytes = $client->convertOfficeFromBytes(
    bytes: $fileContent,
    filename: 'contract.docx',   // 副檔名決定 LibreOffice 的解析器
    options: OfficeConversionOptions::default(),
);

// 從 PHP stream resource 轉換(大型檔案)
$pdfBytes = $client->convertOfficeFromStream(
    stream: fopen('/path/to/large.xlsx', 'r'),
    filename: 'report.xlsx',
);

轉換選項

use NextPDF\Gotenberg\Office\OfficeConversionOptions;
use NextPDF\Gotenberg\Office\PaperFormat;
use NextPDF\Gotenberg\Office\PageMargin;

$options = OfficeConversionOptions::create(
    landscape: false,                        // 橫向輸出
    paperFormat: PaperFormat::A4,            // 紙張尺寸覆寫
    margin: PageMargin::create(              // 邊距(inches)
        top: 0.5, right: 0.5,
        bottom: 0.5, left: 0.5,
    ),
    nativePageRanges: '1-5,7,9-',           // 只轉換指定頁碼範圍
    exportFormFields: false,                 // 匯出表單欄位內容(而非表單控制項)
    allowDuplicateFieldNames: false,
    exportBookmarks: true,                   // 匯出書籤為 PDF 書籤
    exportBookmarksToPDFDestination: true,
    exportPlaceholders: false,
    exportNotes: false,                      // 不匯出備註
    exportNotesPages: false,
    exportOnlyNotesPages: false,
    exportNotesInMargin: false,
    convertOOoTargetToPDFTarget: false,
    exportLinksRelativeFsys: false,
    exportHiddenSlides: false,               // PowerPoint:不匯出隱藏投影片
    skipEmptyPages: false,
    addOriginalDocumentAsStream: false,
    pdfa: '',                                // 'PDF/A-1b', 'PDF/A-2b' 等
    pdfua: false,                            // 啟用 PDF/UA 無障礙輸出
    losslessImageCompression: false,
    reduceImageResolution: false,
    maxImageResolution: 300,                 // DPI
    password: null,                          // 開啟受密碼保護的文件
);

$pdfBytes = $client->convertOffice(file: '/path/to/doc.docx', options: $options);

Word 文件(DOCX)轉換

DOCX 轉換的品質取決於文件所使用的字型是否安裝於 Gotenberg 的 LibreOffice 環境中。

// 推薦:指定頁面格式以確保一致輸出
$options = OfficeConversionOptions::create(
    paperFormat: PaperFormat::A4,
    margin: PageMargin::create(top: 1.0, right: 1.0, bottom: 1.0, left: 1.0),
    exportBookmarks: true,
);

$pdfBytes = $client->convertOffice(file: '/path/to/contract.docx', options: $options);

字型注意:若文件使用商業字型(Times New Roman、Calibri 等),必須在 Gotenberg Docker 映像中安裝對應字型,否則 LibreOffice 將使用替代字型,導致排版差異。

Excel 試算表(XLSX)轉換

$options = OfficeConversionOptions::create(
    landscape: true,                        // Excel 通常橫向輸出
    paperFormat: PaperFormat::A3,           // 寬度較大的工作表
    maxImageResolution: 150,                // 降低圖表解析度以減小檔案大小
    skipEmptyPages: true,                   // 跳過空白工作表
);

$pdfBytes = $client->convertOffice(file: '/path/to/report.xlsx', options: $options);

PowerPoint 簡報(PPTX)轉換

$options = OfficeConversionOptions::create(
    landscape: true,                        // 投影片通常橫向
    exportHiddenSlides: false,              // 不匯出隱藏投影片
    nativePageRanges: '1-10',              // 只轉換前 10 張
    losslessImageCompression: true,         // 保持影像品質
);

$pdfBytes = $client->convertOffice(file: '/path/to/deck.pptx', options: $options);

批次轉換

use NextPDF\Gotenberg\Office\BatchConversionRequest;

// 批次轉換多個文件(並行 HTTP 請求)
$requests = [
    new BatchConversionRequest('/docs/contract.docx', OfficeConversionOptions::default()),
    new BatchConversionRequest('/docs/annex.xlsx', OfficeConversionOptions::default()),
    new BatchConversionRequest('/docs/presentation.pptx', OfficeConversionOptions::default()),
];

$results = $client->convertOfficeBatch(
    requests: $requests,
    concurrency: 3,   // 最大並行請求數
);

// $results 為 list<ConversionResult>,順序與 $requests 一致
foreach ($results as $index => $result) {
    if ($result->isSuccess()) {
        file_put_contents("/tmp/output-{$index}.pdf", $result->pdfBytes());
    } else {
        echo "Failed: " . $result->error()->getMessage();
    }
}

例外處理

例外類別 觸發條件
GotenbergConversionException Gotenberg 回傳非 200 狀態碼
GotenbergTimeoutException 轉換超出設定時間
UnsupportedFormatException 提交了不支援的副檔名
PasswordProtectedException 文件有密碼保護但未提供密碼
GotenbergNetworkException 無法連線至 Gotenberg 服務

參見