Laravel

How To Convert Word To PDF In Laravel

How To Convert Word To PDF In Laravel

In this post, we’ll learn the way to convert Word to PDF In Laravel. Sometimes we’d like to implement this feature in web applications. In that, he will upload a word file, and we will convert that word file into a PDF using the Laravel library.

We will use two libraries for the word to PDF conversion. the primary one is PHPWord and the other is LARAVEL-DOMPDF.

PHPWord is a library written in pure PHP that gives a collection of classes to put in writing and browse from different document file formats. The present 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 offers robust performance for PDF conversion in Laravel applications spontaneously.

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

To register the service provider, open the config/app.php file. And add the following line in the ‘providers‘ array at the end and also add aliases array at the end.

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

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

Step 3: Create Route in web.php.

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

use App\Http\Controllers\ConvertController;

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

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

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use PDF;

class ConvertController extends Controller
{
    public function convertDocToPDF(){
         $domPdfPath = base_path('vendor/dompdf/dompdf');
         \PhpOffice\PhpWord\Settings::setPdfRendererPath($domPdfPath);
         \PhpOffice\PhpWord\Settings::setPdfRendererName('DomPDF'); 
         $Content = \PhpOffice\PhpWord\IOFactory::load(public_path('sample.docx')); 
         $PDFWriter = \PhpOffice\PhpWord\IOFactory::createWriter($Content,'PDF');
         $PDFWriter->save(public_path('doc-pdf.pdf')); 
         echo 'File has been successfully converted';
    }
}

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

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

Event Calendar Example In Laravel.                       Laravel Autocomplete Search Using Typeahead JS.

Related Articles

Leave a Reply

Back to top button