php 將office文件(word/excel/ppt)轉化為pdf(windows和linux只要安裝對應組件應該就行)


 

 

一、配置環境

(1)配置php.ini

添加:extension=php_com_dotnet.dll

com.allow_dcom = true  // 去掉號,改為true

重啟環境

 

(2) 安裝:WPS 專業版,或者 microsoft  office 2010

(microsoft office 2007 需要安裝加載項:Microsoft Save as PDF) 

(3)配置office組件服務

        按 win+R 快捷鍵進入運行菜單,輸入 Dcomcnfg 

        找到:     [組件服務] —— [計算機]—— [我的電腦] —— [DCOM配置] ——【wps……】或[Microsoft Wrord 97-2003文檔]

        如果沒找到【wps……】或(Microsoft Wrord 97-2003文檔):

        按 win+R 快捷鍵進入運行菜單

        輸入:mmc -32

        [文件]——[添加或刪除管理單元]——[組件服務](從可用管理單元,添加到所選管理單元,點擊:確定)

        添加完以后,在控制台根節點下,找到【wps……】或[Microsoft Wrord 97-2003文檔],右鍵設置屬性,設置“標識”為:交互式用戶(還有安全里面的設置 可以看其他文章的設置)

 

 

注:我開始 選擇交互式用戶  : 會出現 我登錄遠程服務器一切正常,如果退出遠程服務器實例化組件就報錯,最后選擇了 下列用戶,填寫了管理員用戶和密碼才正常可用.

 

二、編寫程序

<?php

word2pdf();
 function word2pdf()
{
    $filenamedoc = dirname(__FILE__)."/index.docx";
    $filenamepdf = dirname(__FILE__)."/index.pdf";

    $dd = $word = new COM("KWPS.Application") or die ("Could not initialise Object.");
    // 或者 $dd = $word = new COM("Word.Application") or die ("Could not initialise Object.");
    // set it to 1 to see the MS Word window (the actual opening of the document)
    $word->Visible = 0;
    // recommend to set to 0, disables alerts like "Do you want MS Word to be the default .. etc"
    $word->DisplayAlerts = 0;
    // open the word 2007-2013 document

    $word->Documents->Open($filenamedoc);
    // save it as word 2003
    // convert word 2007-2013 to PDF

    //判斷要生成的文件名是否存在
    if(file_exists($filenamepdf)) {
        //存在就刪除
        unlink ($filenamepdf);
    }
    $word->ActiveDocument->ExportAsFixedFormat($filenamepdf, 17, false, 0, 0, 0, 0, 7, true, true, 2, true, true, false);
    // quit the Word process
    $word->Quit(false);
    // clean up
    unset($word);
    if(!function_exists('read_pdf')) {
        header('Content-type: application/pdf');
        header('filename='.$filenamepdf);
        readfile($filenamepdf);
        read_pdf('Python_study.pdf');
    }
    echo 'ok';
}

?>

 

if(!function_exists('read_pdf')) {
  function read_pdf($file) {
    if(strtolower(substr(strrchr($file,'.'),1)) != 'pdf') {
      echo '文件格式不對.';
      return;
    }
    if(!file_exists($file)) {
      echo '文件不存在';
      return;
    }
    header('Content-type: application/pdf');
    header('filename='.$file);
    readfile($file);
  }
}

 

 

 

 

 

轉: https://my.oschina.net/u/3567851/blog/2909656

https://blog.csdn.net/sangjinchao/article/details/78053545

https://blog.csdn.net/ken2999/article/details/82353747  (組件的權限)

https://www.cnblogs.com/zhuchenglin/p/7586170.html

https://stackoverflow.com/questions/5538584/convert-word-doc-docx-and-excel-xls-xlsx-to-pdf-with-php

https://blog.csdn.net/baidu_27474941/article/details/83268468

 


免責聲明!

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



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