10

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.

miken32
  • 42,008
  • 16
  • 111
  • 154
DandyF
  • 117
  • 1
  • 3
  • 1
    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. – Ahmad Aug 25 '21 at 09:27

3 Answers3

0

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");

Anurag Prashant
  • 995
  • 10
  • 31
-1

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');
Milad Nouri
  • 1,587
  • 1
  • 21
  • 32
-2

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')); 
    }