wkhtmltopdf和apache的tmp目录问题

3月31日。

今天遇到了一个坑。

之前用于html转pdf的工具是wkhtmltopdf,一直用的好好的,今天在重启httpd.service后突然出现问题,无法生成pdf,辗转调试【由于操作系统等因素不同无法在本地和测试环境调试,只能在线上调试,幸好目前用户操作这个功能不多不会造成困扰 = =】,终于发现问题所在,并且同时解决了几个问题。

原始代码如下:

$fileName = 'foo';
$fileHtml = '/tmp/'.$fileName.'.html';
$filePdf = '/tmp/'.$fileName.'.pdf';
file_put_contents($fileHtml, 'bar');
exec('wkhtmltopdf '.$fileHtml.' '.$filePdf);

发现在/tmp目录下根本没有生成html文件,是什么原因呢?
谷歌后发现这篇文章:Centos 7 – Missing php/Apache temporary files in /tmp – Systemd Private Temp

是centos7搞的鬼。于是按照以下步骤解决了此问题:

1、找到httpd.service的位置:systemctl status httpd

2、vim /usr/lib/systemd/system/httpd.service 并修改PrivateTmp为false

3、systemctl daemon-reload

4、systemctl restart httpd

搞定。

之后继续,又报了wkhtmltopdf: Cannot connect to X server的错误。答案在此 wkhtmltopdf: cannot connect to X server,于是安装xvfb:yum install xorg-x11-server-Xvfb,并使用下面这句话:

exec('xvfb-run --server-args="-screen 0, 1024x680x24" wkhtmltopdf --load-error-handling ignore --use-xserver '.$fileHtml.' '.$filePdf.' 2>&1');

搞定~