PHP將word文件轉為pdf



 

 修改php.ini

  1. 添加:extension=php_com_dotnet.dll 
  2. 去除注釋:com.allow_dcom = true
  3. 重啟環境

 配置office支持

  1. 安裝微軟office套件。(office 2007 需要手動安裝 `Microsoft Save as PDF and XPS`)
  2. 配置office組件服務
    1. win+R打開運行菜單,輸入dcomcnfg 
    2. 找到 [組件服務] —— [計算機]—— [我的電腦] —— [DCOM配置] —— [Microsoft Wrord 97-2003文檔]
    3. 右鍵 [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內容如下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM