PHP - Laravel - Convert .docx to PDF format

How can I convert a document (docx) to PDF format using PHP Laravel? Before converting this, I'm using PHPWord for set variables, and after that, I want to save it or convert it to PDF.

42.6k 16 16 gold badges 121 121 silver badges 164 164 bronze badges asked Dec 28, 2016 at 8:41 127 1 1 silver badge 3 3 bronze badges

As far as I know, LibreOffice is the only option, since it has great support for word files; I've done that in one of my side projects and maybe I'll open source it soon.

Commented Aug 25, 2021 at 9:27

4 Answers 4

Detailed Summary:

Step 1: Install Required Packages

First, make sure you have PHPWord installed. If not, you can install it via Composer:

composer require phpoffice/phpword 

For PDF conversion, you can use Dompdf . Install it as well:

composer require dompdf/dompdf 

Step 2: Create a DOCX File using PHPWord

Assuming you are already using PHPWord for .docx manipulation, you can create or load an existing .docx file like this:

use PhpOffice\PhpWord\PhpWord; $phpWord = new PhpWord(); $section = $phpWord->addSection(); $section->addText('Hello, world!'); // Save DOCX file $writer = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007'); $writer->save('helloWorld.docx'); 

Step 3: Convert DOCX to PDF

Convert the .docx file to .pdf using Dompdf :

use Dompdf\Dompdf; // Load .docx file content $phpWord = \PhpOffice\PhpWord\IOFactory::load('helloWorld.docx'); // Save the document as HTML $writer = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'HTML'); $writer->save('helloWorld.html'); // Convert HTML to PDF using Dompdf $dompdf = new Dompdf(); $dompdf->loadHtml(file_get_contents('helloWorld.html')); $dompdf->setPaper('A4', 'portrait'); $dompdf->render(); // Save the PDF $output = $dompdf->output(); file_put_contents('helloWorld.pdf', $output); 

Step 4: Integrate into Laravel

Wrap the above code inside a Laravel controller method:

public function convertDocxToPdf() < // Your PHPWord and Dompdf code here >

Then route a URL to this controller method.

Critique and Suggestions for Improvement

Note: This solution is not fully tested and is provided as a guideline. Please test thoroughly before implementing in a production environment.