PHP - Laravel - Convert .docx to PDF format

7k views Asked by At

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.

4

There are 4 answers

1
Boris D. Teoharov On

Detailed Summary:

  • Initial Setup: Begin by installing the required packages—PHPWord for DOCX manipulation and Dompdf for PDF conversion—using Composer.

  • DOCX Creation or Manipulation: Utilize the PHPWord library to either create a new DOCX file or manipulate an existing one. Save this intermediate DOCX file.

  • DOCX to HTML Conversion: Use PHPWord to convert the DOCX file into an HTML file, which will serve as an intermediate step before the PDF conversion.

  • HTML to PDF Conversion: Utilize the Dompdf library to convert the intermediate HTML file to a PDF file. Save this PDF file.

  • Laravel Integration: Integrate the entire process within a Laravel application by wrapping the code into a controller method and linking it to a route.

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

  • The conversion from .docx to .html might not be perfect for complex documents. For better accuracy, consider using wkhtmltopdf.
  • This is a basic example; consider adding exception handling and validation for a more robust solution.
  • Be cautious with confidential data and where you're saving the temporary .html and .pdf files. Secure the temporary location and delete files after use.

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

0
Milad Nouri On

You can use the PHPWord library to read the contents of a .docx file, and then use another library such as Dompdf or mPDF to convert the contents to a .pdf file. Here is an example:

use PhpOffice\PhpWord\IOFactory;
use Dompdf\Dompdf;

$phpWord = IOFactory::load('path/to/file.docx');

$dompdf = new Dompdf();
$dompdf->loadHtml($phpWord->saveHTML());
$dompdf->render();
$dompdf->stream();

You can also use the package like "phpoffice/phpword" and "barryvdh/laravel-dompdf"

composer require phpoffice/phpword
composer require barryvdh/laravel-dompdf

and then use them in the controller to convert docx to pdf

use PhpOffice\PhpWord\PhpWord;
use Barryvdh\DomPDF\Facade as PDF;

$phpWord = new PhpWord();
$phpWord->loadTemplate('path/to/file.docx');

$pdf = PDF::loadView('view', compact('phpWord'))->save('path/to/file.pdf');
0
Anurag Prashant On

You need to install unoconv on server. Also, permission to run exec() is required on the server.

  1. Install unoconv

sudo apt-get install unoconv

  1. add below line to convert desired docx file to pdf.

exec("doc2pdf sample-file.docx sample-file.pdf");

0
Nitiz Sharma On

You can also use the package like "phpoffice/phpword" and "barryvdh/laravel-dompdf"

  composer require barryvdh/laravel-dompdf  
  composer require phpoffice/phpword

Register Service Provider In config/app.php
To register the service provider, open the config/app.php file. And add the following line in 'providers' array at the end:

'providers' => [
 .....
 Barryvdh\DomPDF\ServiceProvider::class,
]

Also, add the following line to the 'aliases' array at the end. You can use any aliases as you want like we have used ‘PDF’ but you can also use aliases like ‘DoPDF’, ‘myPDF’, ‘PF’, etc

'aliases' => [
 .....
 'PDF' => Barryvdh\DomPDF\Facade::class,
]

and then use them in the controller to convert docx to pdf

use PDF;
public function convertWordToPDF()
    {
            /* Set the PDF Engine Renderer Path */
        $domPdfPath = base_path('vendor/dompdf/dompdf');
        \PhpOffice\PhpWord\Settings::setPdfRendererPath($domPdfPath);
        \PhpOffice\PhpWord\Settings::setPdfRendererName('DomPDF');
         
        //Load word file
        $Content = \PhpOffice\PhpWord\IOFactory::load(public_path('result.docx')); 
 
        //Save it into PDF
        $PDFWriter = \PhpOffice\PhpWord\IOFactory::createWriter($Content,'PDF');
        $PDFWriter->save(public_path('new-result.pdf')); 
    }