一、背景
在centos环境下,需要将word文档转换成pdf文档,由于未能查找到相关php扩展,因此借助linux的libreoffice实现转换。
二、具体实现
1、centos下安装libreoffice
yum install libreoffice
2、命令行执行word转pdf
将 /home/file/word/test.docx转成pdf存放到 /home/file/pdf/ 目录下:
libreoffice --headless --convert-to pdf:writer_pdf_Export /home/file/word/test.docx --outdir /home/file/pdf/
3、在php中执行的代码
<?php
$docfile = '/home/file/word/test.docx'; // word文件
$pdfdir = '/home/file/pdf/'; // pdf文件
$cmd = "export HOME=/tmp && libreoffice --headless -convert-to pdf {$docfile} -outdir {$pdfdir}";
$res = system($cmd); // exec($cmd);
三、可能碰到的问题
1、在centos执行"libreoffice --headless --convert-to pdf:writer_pdf_Export /home/file/word/test.docx --outdir /home/file/pdf/"命令时,可能遇到:
root@snake:~/bin $ soffice --headless --convert-to txt:text blah.doc /usr/lib64/libreoffice/program/soffice.bin X11 error: Can't open display: Set DISPLAY environment variable, use -display option or check permissions of your X-Server (See "man X" resp. "man xhost" for details)
此时需要安装libreoffice-headless,执行:
yum install libreoffice-headless
2、若转换出来的文件有乱码,则需添加中文字体,传送门>>