Home » How To Convert Word To PDF In Laravel

How To Convert Word To PDF In Laravel

Last updated on December 29, 2020 by

In this article, we will learn how to convert Word to PDF In Laravel. Recently, one of our clients wants to develop functionality in Laravel & Vue based CMS.

In that, he wants to upload a Word document as a template, and then we need to replace some data into the Word file. After that Word file should be converted into a PDF file and make available for the user to download. After googling for some time, We have found very nice libraries for Laravel at GitHub, PHP Word, and DOMPDF Wrapper for Laravel-dompdf.

Here I am going to share how can you easily install that package and convert your Word file To PDF with dynamic data in Laravel.

I can say you, its easy !! We have made it very simple and step by step.

Let’s start. We are preassuming that you already have a Laravel project set up on your machine either it’s a fresh installation or an existing Laravel application.

Laravel: Convert Word To PDF

01 Installing Packages

Most of the Laravel developers know the term “Packages”, if not then read the following definition:

A package is a piece of reusable code that can be dropped into any application and be used without any tinkering to add functionality to that code. You don’t need to know what is happening inside, only what the API for the class(es) are so that you can archive your goal

We don’t need to worry about the packages. It has some files and code inside it but one thing is for sure that it will solve our problem faster than we might think.

We hope you are now clear with the packages. Let’s go ahead.

To install a package you need to first have Composer on your machine. A Composer is a PHP package manager that is used to download and install packages for our projects.

It’s very easy to install the composer. Have a look here and follow the steps and you are good to go https://getcomposer.org/download/

Now, open your command-line tool and navigate it to the directory, our is laravel-demos where your project installed. We are using Git Bash as a command-line tool, you can use your own or you can install Git Bash from here as per your OS: https://git-scm.com/downloads

Install Package In Laravel To Convert Word To Doc

Run the following commands one by one:

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

Now, wait until your installation finishes the process

laravel package install

You are now done with packages installations. Let’s move on next step.

02 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

We shouldn’t worry about the aliases, It’s just a short form of service provider class so that we don’t need to write the whole path while using it in Controllers. Hope you are getting it. Great!

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

03 Register Route In routes/web.php

Open the routes/web.php file to add or register a new route. You can create routes as per your Controller and Method. Here, we have DocumentController, and in that, we have convertWordToPDF() method. So now our route will look like as below:

Route::get('/document/convert-word-to-pdf', 'DocumentController@convertWordToPDF')->name('document.wordtopdf');

Now, add that route to any anchor or button.

<a href="{{ route('document.wordtopdf') }}">Convert Word To PDF</a>

04 Create Controller

Now, we are moving forward to the end of this tutorial so hold tight and let’s move on.

Let’s now create a controller. You can create it by copying any other controller code or run the following command in your command-line tool.

php artisan make:controller DocumentController

After running the above command a new file has been created into your app/Http/Controllers/DocumentController.php

Open the controller file and write down the following code into it.

app/Http/Controllers/DocumentController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use PDF;

class DocumentController extends Controller
{
    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')); 
	    echo 'File has been successfully converted';
    }
}

Now, put the result.docx file into your public folder

Now access the URL /document/convert-word-to-pdf and hit the Convert Word To PDF button. It will save a PDF file into your public directory with a new name new-result.pdf. Hurray! Drum the roll.

Laravel: Dynamically Change The Content In Word File And Convert To PDF

There is some requirement where you need to replace some text in the Doc file prior to converting to the PDF file. In that situation use the setValue() function provided by the PHPWord library.

Let’s say, we have a Word file with following text:

${date}

Dear Sir/Madam,

Re:  ${title} ${firstname} ${lastname} 

I’d be grateful if you could also send me information on the plan detailed above, together with any other plans that I may hold with you.

Please note that all the placeholder should be prefix with $ and wrap with {} braces like ${date}.

Now, we want to replace all the above placeholder with the text. So your Controller should look like below:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use PDF;

class DocumentController extends Controller
{
    /* Laravel Convert Word To PDF Tutorial
     * By ScratchCode.io
     */
    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');
	    
	    /*@ Reading doc file */
        $template = new\PhpOffice\PhpWord\TemplateProcessor(public_path('result.docx'));

        /*@ Replacing variables in doc file */
        $template->setValue('date', date('d-m-Y'));
        $template->setValue('title', 'Mr.');
        $template->setValue('firstname', 'Scratch');
        $template->setValue('lastname', 'Coder');

        /*@ Save Temporary Word File With New Name */
        $saveDocPath = public_path('new-result.docx');
        $template->saveAs($saveDocPath);
        
        // Load temporarily create word file
        $Content = \PhpOffice\PhpWord\IOFactory::load($saveDocPath); 

        //Save it into PDF
        $savePdfPath = public_path('new-result.pdf');

        /*@ If already PDF exists then delete it */
        if ( file_exists($savePdfPath) ) {
            unlink($savePdfPath);
        }

        //Save it into PDF
	    $PDFWriter = \PhpOffice\PhpWord\IOFactory::createWriter($Content,'PDF');
	    $PDFWriter->save($savePdfPath); 
	    echo 'File has been successfully converted';

	    /*@ Remove temporarily created word file */
        if ( file_exists($saveDocPath) ) {
            unlink($saveDocPath);
        }
    }
}

And after the Laravel converting Word To PDF your PDF will look like below:

25-12-2020

Dear Sir/Madam,

Re: Mr. Scratch Coder

I’d be grateful if you could also send me information on the plan detailed above, together with any other plans that I may hold with you.

Tips For Laravel Convert Word To PDF

You might have some formatting issues while converting from Word To PDF. Don’t panic, it happens. If you can’t able to solve it yourself then raise the issue here: https://github.com/PHPOffice/PHPWord/issues

Additionally, read our guide:

  1. Best Way to Remove Public from URL in Laravel
  2. Error After php artisan config:cache In Laravel
  3. Specified Key Was Too Long Error In Laravel
  4. AJAX PHP Post Request With Example
  5. How To Use The Laravel Soft Delete
  6. How To Add Laravel Next Prev Pagination
  7. cURL error 60: SSL certificate problem: unable to get local issuer certificate
  8. Difference Between Factory And Seeders In Laravel
  9. Laravel: Increase Quantity If Product Already Exists In Cart
  10. How To Calculate Age From Birthdate
  11. How to Convert Base64 to Image in PHP
  12. Check If A String Contains A Specific Word In PHP
  13. How To Find Duplicate Records in Database
  14. Laravel Send Mail From Localhost

That’s it for now. We hope this article helped you in Laravel Convert Word To PDF process.

Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you in advance. 🙂 Keep Smiling! Happy Coding!

 
 

8 thoughts on “How To Convert Word To PDF In Laravel”

  1. I had a similar task and formatting was critical for the client, so after long research I have solved the issue by using 3rd party service: https://cloudconvert.com/
    Also there is a way to use LibreOffice CLI to convert the docx to PDF, but the result will not be 100% the same as DOCX design.

    Reply

Leave a Comment