[PHP] office文件转为PDF--兼容WINDOWS与LINUX

407 阅读1分钟
1. 下载并安装LibreOffice

下载地址:zh-cn.libreoffice.org/download/li…

安装完毕后,右键开始-->运行-->输入Dcomcnfg,打开组件服务。

微信截图_20220208153051.png

在组件服务中的如下路径找到LibreOffice Service Manager并右键-->属性-->标识,选择交互式用户。

微信截图_20220208153223.png

随后在安全-->启动和激活权限-->自定义处添加Everyone并赋予所有权限,访问权限同理。

微信截图_20220208153952.png

2. 配置php.ini文件

微信截图_20220208152709.png

可在phpinfo()处查看是否开启成功

微信截图_20220208154242.png

3. 代码
<?php
class PdfConverter
{
    /**
     * 执行文件转化
     * @param $officeName
     * @param $pdfName
     */
    public static function run($officeName, $pdfName){
        //最终生成的文件路径如下
        //$officeName = 'file:///D:/phpstudy_pro/WWW/www.nilin.ceshi.com/test.docx';
        //$pdfname = 'file:///D:/phpstudy_pro/WWW/www.nilin.ceshi.com/test.pdf';
        return self::converter($officeName, $pdfName);
    }

    public static function converter($input_url, $output_url){
        $osm = new \COM("com.sun.star.ServiceManager") or die ("调用组件接口失败");
        $args = array(self::MakePropertyValue($osm,"Hidden",true));
        $oDesktop = $osm->createInstance("com.sun.star.frame.Desktop");
        if(!$oDesktop) {
            return false;
        }
        $oWriterDoc = $oDesktop->loadComponentFromURL($input_url,"_blank", 0, $args);
        if(!$oWriterDoc) {
            return false;
        }
        $export_args = array(self::MakePropertyValue($osm,"FilterName","writer_pdf_Export"));
        $oWriterDoc->storeToURL($output_url,$export_args);
        $oWriterDoc->close(true);
        return self::getPdfPages($output_url);
    }

    public static function MakePropertyValue($osm,$name,$value){
        $oStruct = $osm->Bridge_GetStruct("com.sun.star.beans.PropertyValue");
        $oStruct->Name = $name;
        $oStruct->Value = $value;
        return $oStruct;
    }

    /**
     * 获取PDF文件页数的函数获取
     * 文件应当对当前用户可读(linux下)
     * @param  [string] $path [文件路径]
     * @return int
     */
    public static 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;
        }
    }
}
4. 总结

经测试,可以将word、excel、ppt、txt、rtf、图片转为pdf。

使用微软的office软件和openoffice也可实现此功能。