天天看點

PHP 實作Word,excel等轉換pdf

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

下面是操作步驟:

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

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

3、        安裝完openOffice後,在開始--運作中輸入Dcomcnfg打開元件服務。在元件服務—計算機—我的電腦—DCOMP配置中,選擇

PHP 實作Word,excel等轉換pdf
PHP 實作Word,excel等轉換pdf

在這兩項上分别點選右鍵屬性,打開屬性面闆如下圖:

PHP 實作Word,excel等轉換pdf
PHP 實作Word,excel等轉換pdf

選擇安全頁籤,分别在啟動和激活權限和通路權限兩項上點自定義,添加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 <[email protected]> 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;
		// 打開檔案
		[email protected]($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;
		}
	}

}