PHP Convert Docx to PDF
Here's how you can do it:
-
Install LibreOffice:
Ensure you have LibreOffice installed on your server. You can install it using the following command:sudo apt-get install libreoffice
-
Use PHP to call LibreOffice for conversion:
Use PHP to execute a command that converts the DOCX file to PDF using LibreOffice.
Here is the PHP script:
<?php function convertDocxToPdf($docxFilePath, $outputDir) { // Ensure the output directory exists if (!is_dir($outputDir)) { mkdir($outputDir, 0777, true); } // Define the output file path $pdfFilePath = $outputDir . '/' . pathinfo($docxFilePath, PATHINFO_FILENAME) . '.pdf'; // Command to convert DOCX to PDF using LibreOffice $command = 'libreoffice --headless --convert-to pdf --outdir ' . escapeshellarg($outputDir) . ' ' . escapeshellarg($docxFilePath); // Execute the command exec($command, $output, $returnVar); // Check if the conversion was successful if ($returnVar == 0) { return $pdfFilePath; } else { return false; } } // Usage example $docxFilePath = 'path/to/your/document.docx'; $outputDir = 'path/to/output/directory'; $pdfFilePath = convertDocxToPdf($docxFilePath, $outputDir); if ($pdfFilePath) { echo 'PDF created successfully: ' . $pdfFilePath; } else { echo 'Failed to create PDF.'; } ?>
No Comments