问题
I am having issues converting Word documents to PDF using soffice.exe in LibreOffice 5.4.6 - running on Windows Server 2012 R2 via IIS.
After changing directory into the relevant LibreOffice program directory in PHP (chdir), the command I am calling in PHP is:
$cmd = "soffice.exe --headless -convert-to pdf -outdir ".sys_get_temp_dir()." ".$workingdoc;
exec($cmd);
Where $workingdoc is the full path to the .docx Word file.
sys_get_temp_dir() on my system translates to C:\Windows\Temp
If I echo out the $cmd variable to a browser, then copy-paste that output into a cmd.exe Command Prompt interactively on the server, a PDF gets produced without issue.
For example, an echoed out $cmd that I copy-paste into a cmd.exe prompt might be:
soffice.exe --headless -convert-to pdf -outdir C:\Windows\TEMP C:\Windows\Temp\pdD125.docx
However, running this $cmd variable from PHP via exec() in the same user context as what I interactively initiated the cmd.exe from just hangs. I can see soffice.exe in Task Manager with RAM usage hovering between 10-20MB. Additionally, in my C:\Windows\Temp folder, I get multiple empty folders continuously created every second whilst soffice.exe remains running, all with a name in the format of lu*.tmp
For example, one of the many folders that get produced are lu1124fq1pud.tmp
The PDF does not get created, and the only way to allow the PHP script to finish and stop the lu folders being created (besides PHP timeouts) is to force end the soffice.exe task in Task Manager.
So, why does the soffice.exe command work when called from cmd.exe, but not via PHP, even though through both methods they are launched in the same user context?
回答1:
It turns out this is a known issue as reported here. In short, it appears to be a user permissions issue.
I solved my issue by first creating a temporary LibreOffice user profile folder in the system's temp directory (don't make the directory, allow the soffice.exe to initialise it):
$tempLibreOfficeProfile = sys_get_temp_dir()."\\LibreOfficeProfile".rand(100000, 999999);
Then add an env parameter to the soffice.exe command:
$cmd = 'soffice "-env:UserInstallation=file:///'.str_replace("\\", "/", $tempLibreOfficeProfile).'" --headless --convert-to pdf -outdir "'.sys_get_temp_dir().'" '.$workingDoc;
exec($cmd);
Make sure to clean up your temporary profile folder once finished to not clog up your temp, for example:
exec('rmdir /S /Q "'.$tempLibreOfficeProfile.'"');
来源:https://stackoverflow.com/questions/50250739/running-libreoffice-soffice-exe-on-windows-from-php-exec-stuck