How to Convert Word to PDF in Laravel

Posted on

In this article, we will learn how to convert Word to PDF in Laravel. Sometimes we would like to implement this functionality in web applications. In this it will upload a Word file and we will convert this Word file to PDF using Laravel library.

We will use two libraries for converting Word to PDF. the primary is PHP Word and the other is LARAVEL-DOMPDF.

PHP Word is a library written in pure PHP that gives a collection of classes to write to and browse from different document file formats. The current version of PHPWord supports Microsoft Office Open XML (OOXML or OpenXML), OASIS Open Document Format for Office Applications (OpenDocument or ODF) and Rich Text Format (RTF), HTML and PDF.

DOMPDF is a wrapper for Laravel, and it provides robust performance for PDF conversion in Laravel applications spontaneously.

Step 1: Create a Laravel project.
composer create-project laravel/laravel doc-to-pdf --prefer-dist
Step 2: Install the library below one by one.
composer require barryvdh/laravel-dompdf
composer require phpoffice/phpword
Step 3: Register the service provider in config/app.php.

To register the service provider, open the config/app.php case. And add the following line in the ‘suppliers‘ array at the end and also add pseudonyms table at the end.

'providers' => [

'aliases' => [
 'PDF' => BarryvdhDomPDFFacade::class,

Step 3: Create a route in web.php.

Open routes/web.php file and create the route below.

use AppHttpControllersConvertController;

Route::get('/doc-to-pdf', [ConvertController::class, 'convertDocToPDF']);
Step 4: Create a controller.
php artisan make:controller ConvertController

After creating the controller, open it and below the line of code.


namespace AppHttpControllers;
use IlluminateHttpRequest;
use PDF;

class ConvertController extends Controller
    public function convertDocToPDF(){
         $domPdfPath = base_path('vendor/dompdf/dompdf');
         $Content = PhpOfficePhpWordIOFactory::load(public_path('sample.docx')); 
         $PDFWriter = PhpOfficePhpWordIOFactory::createWriter($Content,'PDF');
         echo 'File has been successfully converted';

Now put the example.docx file in your public folder.

Step 5: Add the link below to the view file.
 <a href="{{ url("convert-word-to-pdf') }}">Convert Word To PDF</a>

Example of an event calendar in Laravel. Semi-automatic Laravel search using Typeahead JS.

Leave a Reply

Your email address will not be published.