Tuesday, 23 July 2019

linux - Convert file to PDF using LibreOffice under user apache (i.e. when using PHP)


I installed libreoffice-headless and can convert documents when logged on into the shell as a normal user.


[root@desktop ~]# yum install libreoffice-headless
[root@desktop ~]# yum install libreoffice-writer
[root@desktop ~]# su NotionCommotion
sh-4.1$ /usr/bin/libreoffice --headless -convert-to pdf --outdir /tmp/ayb /tmp/ayb/document_34.doc
convert /tmp/ayb/document_34.doc -> /tmp/ayb/document_34.pdf using writer_pdf_Export

I now wish to do the same thing, but using PHP and therefore as user apache, however, the following will not convert the file.


  shell_exec('/usr/bin/libreoffice --headless -convert-to pdf --outdir /tmp/ayb /tmp/ayb/document_34.doc');
?>

In an attempt to troubleshoot, I ran the same command through the shell as user apache, but still it will not convert the file:


[root@desktop ~]# su -s /bin/sh apache -c "/usr/bin/libreoffice --headless -convert-to pdf --outdir /tmp/ayb /tmp/ayb/document_34.doc"

Apache unlike normal users doesn't have a home, and I recall hearing I might need to specify a home using HOME=/tmp/ayb before attempting to convert, but it doesn't help (I think when using CentOS 5.8 and probably a different version of LibreOffice, it did, but am not certain).


How do I convert a file to PDF using libreoffice when running it as user apache?


Installed System:


CentOS 6.4
httpd.x86_64 2.2.15-28.el6.centos @updates
libreoffice-headless.x86_64 1:3.4.5.2-16.1.el6_3 @base

Answer



There are two problems here. The first is that www-data (the apache user) does not have a $HOME so libreoffice cannot run if there is no $HOME defined. The second problem is, unless you specifically set it up this way (and you really really really shouldn't), apache does not have access to the system /tmp directory. A web server normally runs in a restricted environment and does not have full access to the file system for very valid security reasons.


So, you need to i) give apache's user a home and ii) give it a directory it has access to to write in. So, create a tmp directory in the same folder where you store your webpage and then run the following php code:


  shell_exec('export HOME=/tmp && libreoffice --headless -convert-to pdf --outdir ./tmp /tmp/ayb/document_34.doc');
?>

I just tested and it works perfectly on my machine. Make sure your ./tmp has its permissions set to 777. Also, you may need to restart apache if you play aroud with it too much. It stopped working for me after a while when I made changes and I needed to restart it.


No comments:

Post a Comment

How can I VLOOKUP in multiple Excel documents?

I am trying to VLOOKUP reference data with around 400 seperate Excel files. Is it possible to do this in a quick way rather than doing it m...