Wednesday, May 16, 2018

Run LibreOffice in PHP scipts

It is often desirable to have PHP convert Word documents into PDF documents. LibreOffice can do that very well and of course it can do much more. There are three tricky points to consider if you want to run LibreOffice with PHP:

  1. You need to run it using the --headless option as it will probably be running on a server that probably has no GUI capabilities.
  2. You need to make sure that the output dir (which if not explicitly specified is the same as that of the php script that runs LibreOffice) is writable by the user php runs as (in my case apache). Obviously, the directory where the document that will be read in resides (as well as the document itself) need to be readable by the user php runs as (in my case I just did a chown apache:apahe <dirpath> on both these dirs)
  3. (Trickiest) soffice (one of LibreOffice's executables) will still not run correctly as apache (or whatever your php user is) although it will run fine if you execute it as root. This is because it requires special permissions for a directory that it considers its environment dir. there is a number of ways to fix this but easiest is to use the -env:UserInstallation option. In my case I created a subdir under /tmp (specifically: /tmp/soffice) and gave it apache:apache ownership.
In conclusion here is how I successfully call soffice from my php script (where $target_file is the Word file to be read in):

$cmd2 = "/opt/libreoffice6.0/program/soffice -env:UserInstallation=file:///tmp/soffice
        --headless --convert-to pdf " . $target_file;


In the my case, the resulting pdf file is saved in the same directory as the php file that runs sofficewhich is fine for my purposes.

No comments:

Post a Comment