On Linux platforms, converting Word documents to PDF using PHP is a common requirement. This article explains how to implement this functionality on a Linux system using PHP.
LibreOffice is an open-source office suite that supports multiple document formats, including Word and PDF files. On Linux, you can install LibreOffice using the following command:
After installation, use the command "libreoffice" to verify that it was installed successfully.
Before starting the conversion, make sure PHP is installed on the server and has the appropriate read/write permissions. Additionally, the Word document to be converted should be uploaded to a specified directory on the server, for example, /var/www/html/uploads.
Here is an example of PHP code that converts a Word document to a PDF:
In the code above, $wordFilePath and $pdfFilePath refer to the paths of the Word document to be converted and the generated PDF file. The exec() function is used to execute the LibreOffice command to perform the conversion, where --headless runs LibreOffice in headless mode, --convert-to pdf specifies conversion to PDF format, and --outdir specifies the output directory.
After execution, check if the generated PDF file exists to confirm whether the conversion was successful.
Save the above code as convert.php and upload it to the web root directory of your server. Then, access http://localhost/convert.php in your browser to execute the conversion task.
Once the conversion is successful, the generated PDF file will be stored in the specified directory, and you can either provide a download link or display it to users directly.
This article explained how to convert Word documents to PDF on a Linux platform using PHP. By leveraging the LibreOffice command along with PHP code, you can easily implement document format conversion.
For scenarios requiring large-scale document conversions, you can wrap this code in a function and combine it with other features for batch processing or scheduling. For example, you can use a scheduling tool to automatically convert uploaded Word files every day.