PHP 實現Word,excel等轉換pdf

來源:互聯網
上載者:User
最近做一個項目,需要將使用者上傳的word,excel文檔轉成PDF文檔儲存並列印,在網上找了很多資料,並不全面,所以自己寫了一份比較全面的教程來分享。

下面是操作步驟:

1、 安裝免費的openOffice軟體,請至openoffice.org下載最新版本。

2、 JDK支援,請自行搜尋下載最新版本JDK。

3、 安裝完openOffice後,在開始--運行中輸入Dcomcnfg開啟元件服務。在元件服務?電腦?我的電腦?DCOMP配置中,選擇

在這兩項上分別點擊右鍵屬性,開啟屬性面板如:

選擇安全選項卡,分別在啟動和啟用許可權和存取權限兩項上點自訂,添加Everyone的許可權。

選擇標識選項卡,選擇互動式使用者。

4、 安裝完openOffice後,請先開啟一次確認可以正常運行軟體,然後退出後用命令列運行以下命令。

先到安裝目錄下,例如:C:\Program Files\OpenOffice 4\program\

執行命令:

soffice -headless-accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard

成功後即在後台運行了該軟體。

5、 如果是php5.4.5以前版本,需要在php.ini裡把com.allow_dcom = true開啟,即去掉前面的分號。如果是以後版本,需要在php.ini 裡增加一行擴充extension=php_com_dotnet.dll,然後檢查php的ext目錄中是否存在該dll檔案,如果沒有請自行下載對應版本的dll。然後重啟apache或IIS伺服器。

6、 代碼實現

/** * office文檔轉換為PDF類 * @author jinzhonghao <954299193@qq.com> created 2015-04-23 */class office2pdf{private $osm;public function __construct(){$this->osm = new COM("com.sun.star.ServiceManager")or die ("Please be sure that OpenOffice.org is installed.n"); }public function MakePropertyValue($name,$value){$oStruct = $this->osm->Bridge_GetStruct("com.sun.star.beans.PropertyValue");$oStruct->Name = $name;$oStruct->Value = $value;return $oStruct;}public function transform($input_url, $output_url){$args = array($this->MakePropertyValue("Hidden",true));$oDesktop = $this->osm->createInstance("com.sun.star.frame.Desktop");$oWriterDoc = $oDesktop->loadComponentFromURL($input_url,"_blank", 0, $args);$export_args = array($this->MakePropertyValue("FilterName","writer_pdf_Export"));$oWriterDoc->storeToURL($output_url,$export_args);$oWriterDoc->close(true);return $this->getPdfPages($output_url);}public function run($input,$output){$input = "file:///" . str_replace("\\","/",$input);$output = "file:///" . str_replace("\\","/",$output);return $this->transform($input, $output);}/** * 擷取PDF檔案頁數的函數擷取 * 檔案應當對目前使用者可讀(linux下) * @param  [string] $path [檔案路徑] * @return int */public function getPdfPages($path){if(!file_exists($path)) return 0;if(!is_readable($path)) return 0;// 開啟檔案$fp=@fopen($path,"r");if (!$fp) {return 0;}else {$max=0;while(!feof($fp)) {$line = fgets($fp,255);if (preg_match('/\/Count [0-9]+/', $line, $matches)){preg_match('/[0-9]+/',$matches[0], $matches2);if ($max<$matches2[0]) $max=$matches2[0];}}fclose($fp);// 返回頁數return $max;}}}
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.