一、介紹
1.目前前端只能實現在線預覽pdf格式的文件,可以用pdf.js或者jquery.media.js來實現。
2.要實現其他格式的文件預覽,需要在後端進行格式轉換。
二、具體步驟
1.目前我瞭解到的後端對office文檔格式的轉換方法有:
a、先轉換成swf格式->在轉換成pdf格式
b、借用第三方工具,如openoffice,通過其給的接口,用php後者java或者c#來實現.
2.我用的的是上面提到的第二種方法,下面進行詳細介紹。
a、首先下載openoffice軟件,下載鏈接
b、oppenoffice權限設置
1、cmd 運行Dcomcnfg.exe->組件服務->計算機->我的電腦->DCOM配置->OpenOffice Service Manager
2、右鍵選擇屬性
3、設置步驟圖示
c、php環境及配置(開啓php中com組件服務)
php環境我用的是xampp集成環境,php版本爲5.6.21
具體配置:到php.ini中打開com選項 com.allow_dcom = true
PS:PHP 5.4.5後,com/dotnet 模塊已經成了單獨的擴展,所以需要在PHP.ini中配置extension=php_com_dotnet.dll ,如果PHP VERSION<5.4.5 則不需要。
三、格式轉換代碼實現
<?php
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;
}
}
}
$con=new office2pdf();
$con->run("D:/xampp/htdocs/design/yuanwenjian/ax.xlsx","D:/xampp/htdocs/design/xinwenjian/ax.pdf");
echo $con->getPdfPages("D:/xampp/htdocs/design/xinwenjian/ax.pdf");
?>
四、pdf格式文件預覽代碼實現
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="../js/jquery-3.1.0.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../js/jquery.media.js" type="text/javascript" charset="utf-8"></script>
<script src="../js/jquery.metadata.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<a class="media {type: 'html'}" href="../output/ad.pdf"></a>
</body>
<script type="text/javascript">
$('a.media').media({width:1200, height:900});
</script>
</html>
五、參考博客
參考博客