Current Location: Home> Latest Articles> How to Convert Word Documents to PDF Using PHP on Linux

How to Convert Word Documents to PDF Using PHP on Linux

gitbox 2025-06-13

1. Introduction

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.

2. Installing Dependencies

2.1. LibreOffice

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:

sudo apt-get install libreoffice

After installation, use the command "libreoffice" to verify that it was installed successfully.

3. Conversion Process

3.1. Preparation

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.

3.2. PHP Code Implementation

Here is an example of PHP code that converts a Word document to a PDF:

$wordFilePath = '/var/www/html/uploads/word.docx';
$pdfFilePath = '/var/www/html/uploads/pdf.pdf';
// Use LibreOffice command to convert Word document to PDF
$command = "libreoffice --headless --convert-to pdf {$wordFilePath} --outdir {$pdfFilePath}";
// Execute conversion command
exec($command);
// Check if conversion was successful
if (file_exists($pdfFilePath)) {
    echo 'Conversion Successful!';
} else {
    echo 'Conversion Failed!';
}

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.

3.3. Running the Code

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.

4. Conclusion

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.