php文库计划-libreoffice和pdf2svg使用

磊落不羁 by:磊落不羁 分类:常用函数 时间:5个月前 阅读:46 评论:0

一.libreoffice的使用 (目的 文档转换为PDF)

//通过libreoffice将文档转换为pdf文件的函数
//$officePath 是绝对路径  $outDir为本文件的相对路径
function officeToPdf($officePath,$outDir)
{
    /**本函数主要将office文件转换为pdf 主要涉及的文件类型包括
     *  doc  docx  xls xlsx ppt  pptx txt几个个类型 (类型的来源主要依据libreoffice的支持情况进行判断)
     * 思路:  首先判断是否安装软件 获得libreoffice的路径(加入系统Path路径则无需cmd_one)( 和本系统所在的根目录 以避免在使用过程中出现路径错误
     * 其次获取文件名称文件名称用来标注生成的文件名称
     * 最后生成文件
     * $fileName 文件名称
     * $libreOfficePath libreoffice中 soffice.exe软件地址 用于运行cmd
     */
    //判断文件是否存在
    if (!file_exists($officePath)){
        return '输入文件不存在';
    }
    $outFilePath=__DIR__.'/'.$outDir;

    //获取libreoffice安装目录 依据版本号为7.4 这里最好后台填写
    $libreOfficePath="C:\Program Files\LibreOffice\program";
    if (!file_exists($libreOfficePath)){
        return '请正确配置LibreOffice,soffice.exe所在地址';
    }
    $fileName=explode('.',basename($officePath))[0];
    $outFile=$outFilePath.'/'.$fileName.'.pdf';


    $cmd_one='cd '.$libreOfficePath;
    $cmd_two='soffice '
        .'--headless --invisible '
        .'--convert-to pdf '.$officePath.' --outdir '
        .$outFilePath;

    $retval=1;
    if (function_exists('exec')){
        exec($cmd_one .' && ' .$cmd_two,$output,$retval);

    }
    if ($retval>0){
        exit('process_failed');
    }else{
        return ['state'=>$retval,'path'=>$outFile,'dir'=>$outFilePath,'name'=>$fileName];
    }
}




二、获取PDF页码

/**
 * 获取PDF的页数
 */
function getPageTotal($path)
{
    // 打开文件
    if (!$fp = @fopen($path, "r")) {
        $error = "打开文件{$path}失败";
        return false;
    } 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;
    }
}


三、pdf转svg 图片

$totalpage=getPageTotal($path);
$targetPageNumber=10;
$cmd_three='cd '.$rs['dir'].' && ';
if ($totalpage>$targetPageNumber){
    for ($i=1;$i<=$targetPageNumber;$i++){
        $newcmd='start C:\pdf2svg\pdf2svg.exe '.$rs['name'].'.pdf '.$rs['name']."$i.svg".' '.$i;
        exec($cmd_three.$newcmd);
    }
}else{
    $newcmd='pdf2svg '.$rs['name'].'.pdf '.$rs['name'].'.svg all';
    exec($cmd_three.' && '.$newcmd,$output2,$state);
}


非特殊说明,本文版权归原作者所有,转载请注明出处

本文地址:http://php.liulei.com.cn/?type=acticle&id=83

评论列表

发表评论

  • 昵称(必填)
  • 邮箱
  • 网址

TOP