In this post, we going to see how to generate word document using phpWord package in Laravel. Nowadays some user needs to export data into a word file for offline usages. Some of the client to give their relevant data like Terms and conditions, Private policy and Copyrights details into pdf or word document format. For this kind of purpose, it will help us to generate word file in laravel using phpoffice/phpword package.
Step 1: Download and Install package
In this step, I’m going to download and install phpoffice/phpword package using composer and define a basic class in controller.
1 2 3 4 5 |
"require": { ..... ..... "phpoffice/phpword": "v0.13.*" } |
Using composer we can able to add required package details into our Laravel application. The below command will help us to download and install a package in Laravel.
1 |
composer update |
Step 2: Define a controller
Here we need to define a controller with required method details. Add a phpoffice class name to generate word file.
1 |
$wordTest = new \PhpOffice\PhpWord\PhpWord(); |
using this object we can create a Word document. Create a new section help us to add required number of sections or pages into a word document.
1 |
$newSection = $wordTest->addSection(); |
adding text to word document with a help of addText() method. This function will use to add content and text details into new word documents.
1 |
$newSection->addText("TEXT_TO_DOCUMENT_DETAILS"); |
Complete function to generate a Word document using phpoffice package in Laravel. Just add the below details into a controller.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public function createWordDocx() { $wordTest = new \PhpOffice\PhpWord\PhpWord(); $newSection = $wordTest->addSection(); $desc1 = "The Portfolio details is a very useful feature of the web page. You can establish your archived details and the works to the entire web community. It was outlined to bring in extra clients, get you selected based on this details."; $newSection->addText($desc1, array('name' => 'Tahoma', 'size' => 15, 'color' => 'red')); $objectWriter = \PhpOffice\PhpWord\IOFactory::createWriter($wordTest, 'Word2007'); try { $objectWriter->save(storage_path('TestWordFile.docx')); } catch (Exception $e) { } return response()->download(storage_path('TestWordFile.docx')); } |
Step 3: Define a route
Define a route to call the particular controller method for generating a word file.
1 |
Route::get('/createWord', ['as'=>'createWord','uses'=>'WordTestController@createWordDocx']); |