摘要:最近在做文件管理系統(tǒng)的時候张足,需要將office文檔轉(zhuǎn)成PDF文件骤星,于是想到調(diào)用OpenOffice軟件的com組件去處理
1.首先是下載OpenOffice安裝包(官網(wǎng)下載需要翻墻流强,推薦云墻脑慧,購買流量下載還是蠻快的)
? ? ? ? 云盤:https://pan.baidu.com/s/1i43GzPV
2.配置組件服務(wù)
? ? ? ? A.OpenOffice 安裝完成之后抡驼,按 win+R 快捷鍵進入運行菜單阳藻,輸入 Dcomcnfg 打開組件服務(wù)
????????B.
????????C.右鍵點擊屬性選擇安全晰奖,下面都選擇自定義
????????D.確定后選擇標識腥泥,并將用戶賬號選擇為 交互式用戶.
3.使用命令后臺啟動服務(wù)(只需要執(zhí)行一次匾南,就可以使軟件一直在后臺運行,即使重啟服務(wù)器也不受影響)
? ? 首先需要找到你的安裝位置(在C盤搜索soffice.exe文件蛔外,發(fā)現(xiàn)在C:\Program Files\OpenOffice 4\program)
? ? 所以先進入項目位置c:
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? cd?Program Files\OpenOffice 4\program
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 輸入命令:soffice -headless-accept="socket,host=127.0.0.1,port=8100;urp;"-nofirststartwizard啟動
4.在php.ini中開啟com_dotnet擴展(我用的PHP7)蛆楞,添加extension=php_com_dotnet.dll,重啟服務(wù)器后
5.代碼如下:
classPDFConverter
{
private$com;
/**
* 需要安裝openoffice并在后臺運行
* soffice -headless-accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
*/
public function__construct()
{
try{
$this->com=newCOM('com.sun.star.ServiceManager');
}catch(Exception$e) {
die('Please be sure that OpenOffice.org is installed.');
}
}
/**
* 執(zhí)行PDF文件(絕對路徑)轉(zhuǎn)換
*@param$source [source file]
*@param$export [export file]
*/
public functionexecute($source,$export)
{
$source='file:///'.str_replace('\\','/',$source);
$export='file:///'.str_replace('\\','/',$export);
$this->convertProcess($source,$export);
}
/**
* 獲取PDF頁面
*@param$pdf_path [absolute path]
*@returnint
*/
public functiongetPages($pdf_path)
{
if(!file_exists($pdf_path))return0;
if(!is_readable($pdf_path))return0;
if($fp=fopen($pdf_path,'r')) {
$page=0;
while(!feof($fp)) {
$line=fgets($fp,255);
if(preg_match('/\/Count [0-9]+/',$line,$matches)) {
preg_match('/[0-9]+/',$matches[0],$matches2);
$page= ($page<$matches2[0]) ?$matches2[0] :$page;
}
}
fclose($fp);
return$page;
}
return0;
}
private functionsetProperty($name,$value)
{
$struct=$this->com->Bridge_GetStruct('com.sun.star.beans.PropertyValue');
$struct->Name=$name;
$struct->Value=$value;
return$struct;
}
private functionconvertProcess($source,$export)
{
$desktop_args=array($this->setProperty('Hidden',true));
$desktop=$this->com->createInstance('com.sun.star.frame.Desktop');
$export_args=array($this->setProperty('FilterName','writer_pdf_Export'));
$program=$desktop->loadComponentFromURL($source,'_blank',0,$desktop_args);
$program->storeToURL($export,$export_args);
$program->close(true);
}
}
//$arr = array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx');
$converter=newPDFConverter();
$source=__DIR__.'/office/test.'.'pptx';//轉(zhuǎn)換前文件(絕對路徑)
$export=__DIR__.'/pdf/test.'.'pptx'.'.pdf';//轉(zhuǎn)換后文件(絕對路徑)
$converter->execute($source,$export);