This laravel tutorial help to create a Microsoft word document file. We will use third-party phpoffice/phpword package to create a word file using laravel.
I will let you know step by step process to create a word document. This libs support rich text documents so that you can add images and text with your docs.
The phpword is a library written in pure PHP that provides a set of classes to write to and read 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), Rich Text Format (RTF), HTML, and PDF.
PHPWord is an open-source project licensed under the terms of LGPL version 3.
Install Laravel Project
Let’s create a laravel project using the command line.
composer create-project --prefer-dist laravel/laravel laravel-sample-worddocument
Install phpoffice/phpword Package
We will install phpoffice/phpword package by the composer. Let’s install using the below command –
composer require phpoffice/phpword
Generate Word Document Using laravel
I am assuming you have created data and displaying into an HTML table. We will define the route in routes/web.php
file.
Route::post('msword', EmployeeController@msword');
Go to EmployeeController.php
file and add the below code into msword()
function.
public function msword(Request $request) { $phpWord = new \PhpOffice\PhpWord\PhpWord(); $section = $phpWord->addSection(); $text = $section->addText($request->get('emp_name')); $text = $section->addText($request->get('emp_salary')); $text = $section->addText($request->get('emp_age'),array('name'=>'Arial','size' => 20,'bold' => true)); $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007'); $objWriter->save('Appdividend.docx'); return response()->download(public_path('phpflow.docx')); }
Run Laravel Application
Now, Start Laravel Development server using following command.
php artisan serve
Open to the browser and type this URL:http://localhost:8000/msword
. You can see phpflow.docx
file is downloaded.