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.
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.
You need to install unoconv on server. Also, permission to run exec() is required on the server.
sudo apt-get install unoconv
exec("doc2pdf sample-file.docx sample-file.pdf");
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');
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'));
}