php使用libreoffice将office文件转换为pdf文件

1970-01-01 08:00:00 php

下载

官网下载libreoffice安装包或者使用下面的国内镜像地址下载

  1. // 历史版本地址
  2. downloadarchive.documentfoundation.org/libreoffice/old/
  3. // 最新版本地址
  4. zh-cn.libreoffice.org/download/libreoffice/
  5. // 国内镜像地址
  6. mirrors.cloud.tencent.com/libreoffice/libreoffice/stable/
  7. // 建议使用最新版

安装安装

  1. windows系统下安装
    1. windows比较简单,一路默认安装即可,如果使用自定目录一定要保证目录名都是英文的
    2. 安装成功后,可以配置环境变量,方便程序调用
  2. inux下安装

    1. #将安装包上传到/usr/src/LibreOffice目录然后进入目录
    2. cd /usr/src/LibreOffice/
    3. # 验证之前有没有安装过
    4. libreoffice --version
    5. # 有安装进行卸载,没有直接下一步
    6. yum remove libreoffice-*
    7. # 解压
    8. tar -zxvf LibreOffice_7.6.6_Linux_x86-64_rpm.tar.gz
    9. #进入目录
    10. cd LibreOffice_7.6.6_Linux_x86-64_rpm/RPMS
    11. # 安装*.rpm
    12. yum -y localinstall *.rpm
    13. # 安装libreoffice-headless
    14. yum install -y libreoffice-headless
    15. # 检验是否安装完成
    16. libreoffice7.6 --version
    17. # 测试Word转PDF并安装libreoffice-writer
    18. libreoffice --headless --convert-to pdf test.docx
    19. Error: source file could not be loaded
    20. # 报这个错表示说明缺少writer,安装一下,没报错会输出转换成功的保存路径
    21. yum install libreoffice-writer
    22. # 转换格式说明
    23. libreoffice --headless --convert-to pdf {文档路径} --outdir {导出目录路径}

    使用php进行调用

    1. $docxFile = '/www/wwwroot/public/docx.docx';
    2. $xlsxFile ='/www/wwwroot/public/xlsx.xlsx';
    3. $saveDir = '/www/wwwroot/public/';
    4. var_dump(office_to_pdf($docxFile,$saveDir));
    5. /**
    6. * 使用libreoffice将office文件转换为pdf文件[ppt、pptx、doc、docx、xls、xlsx、txt等]
    7. * @param string $wordFile office文件路径
    8. * @param string $pdfSaveFile pdf文件保存路径
    9. * @return array|string|void
    10. */
    11. function office_to_pdf($wordFile,$pdfSaveFile='',$libreofficeVersion='7.6'){
    12. if (empty($wordFile) || !file_exists($wordFile)){
    13. return false;
    14. }
    15. try {
    16. if(empty($pdfSaveFile)){
    17. $dir = './';
    18. }else{
    19. $dir = dirname($pdfSaveFile);
    20. if(!is_dir($dir)){
    21. mkdir($dir,0777,true);
    22. }
    23. }
    24. //判断php是否禁用了exec函数
    25. if (function_exists('exec')){
    26. //最好加上版本号,防止多个版本的libreoffice冲突引用了默认的版本
    27. $command = "libreoffice{$libreofficeVersion} --headless --convert-to pdf {$wordFile} --outdir {$dir}";
    28. exec($command,$output,$return_var);
    29. return $output;
    30. }
    31. }catch (Exception $e){
    32. return $e->getMessage();
    33. }
    34. }