在 Windows 環境下,PHP 可透過 COM 元件呼叫 `HTML2RTF.Converter` 將 HTML 檔案轉換為 RTF 格式。需安裝對應 COM 元件並啟用 PHP `php_com_dotnet.dll` 擴充。
<?php
$html2RTFCom = new COM("HTML2RTF.Converter");
$html2RTFCom->PreserveImages = true; // 保留圖片
$html2RTFCom->PageNumbers = 1; // 頁碼
$html2RTFCom->PageNumbersAlignH = 1; // 水平對齊
$html2RTFCom->PageNumbersAlignV = 5; // 垂直對齊
$htmlFile = "a.html";
$rtfFile = "a.rtf";
$result = $html2RTFCom->ConvertFile($htmlFile, $rtfFile, "head", "foot");
print($result);
unset($html2RTFCom);
echo "done";
?>
[PHP_COM_DOTNET]
extension=php_com_dotnet.dll
將 `php_com_dotnet.dll` 複製至 `ext/` 目錄(若不存在)。| 錯誤 | 原因 | 解決 |
|---|---|---|
| Class 'COM' not found | 未載入 php_com_dotnet.dll | php.ini 啟用擴充、重啟 PHP |
| Failed to create COM object | 元件未註冊/ProgID 錯誤 | 確認 HTML2RTF 安裝、註冊表檢查 CLSID |
| Permission denied | COM 安全性設定、DCOM 權限 | `dcomcnfg` 設定啟動/存取權限 |
| 轉換失敗/輸出空白 | HTML 語法錯誤、CSS 不支援 | 簡化 HTML、移除複雜 CSS、檢查元件文檔 |
COM 方案僅限 Windows + 特定元件安裝環境,跨平台專案請優先考慮 Pandoc 或 LibreOffice 方案。