修改php.ini
- 添加:extension=php_com_dotnet.dll
- 去除注釋:com.allow_dcom = true
- 重啟環境
配置office支持
- 安裝微軟office套件。(office 2007 需要手動安裝 `Microsoft Save as PDF and XPS`)
- 配置office組件服務
-
- win+R打開運行菜單,輸入dcomcnfg
- 找到 [組件服務] —— [計算機]—— [我的電腦] —— [DCOM配置] —— [Microsoft Wrord 97-2003文檔]
- 右鍵 [Microsoft Wrord 97-2003文檔] 設置屬性 [標識] 為 [交互式用戶]
代碼如下:
/** * @desc xmsb_wordToPdf 將word轉換為pdf * @param string $wordPath word原文件路徑 * @param string $outPath pdf輸出路徑 * @return string */ function xmsb_wordToPdf($wordPath, $outPath) { // 原文件不存在則返回錯誤 if(!file_exists($wordPath)) { return 'word原文件不存在'; } // 輸出目錄不存在則創建目錄 if(!file_exists($tmpPath = rtrim($outPath, basename($outPath)))) { mkdir($tmpPath, 0777, true); } $filenamedoc = dirname(__FILE__)."/".$wordPath; $filenamepdf = dirname(__FILE__)."/".$outPath; // 刪除已有同名文件 if(file_exists($filenamepdf)) { unlink($filenamepdf); } // 執行轉換操作 $word = new COM("word.Application") or die("Could not initialise Object"); $word->Documents->Open($filenamedoc); $word->ActiveDocument->ExportAsFixedFormat($filenamepdf, 17, false, 0, 0, 0, 0, 7, true, true, 2, true, true, false); $word->Quit(false); unset($word); // 在頁面中顯示生成的pdf // header('Content-type: application/pdf'); // header('filename='.$filenamepdf); // readfile($filenamepdf); return '轉換成功'; } // 測試運行 echo xmsb_wordToPdf('./word/word1.docx', './pdf/output1.pdf');
測試結果:
word文件內容如下:
轉換后pdf內容如下: