How to Create Word Document File in Laravel

5
3606
How to Create Word Document File in Laravel

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. You can also apply some basic styles to that document. As usual, we start our tutorial by installing Laravel first.

How to Create a Word Document File in Laravel

To create a word document file in Laravel, use the phpoffice/phpword package. PHPWord is a library written in pure PHP that provides classes to write to and read from different document file formats.

In this example, I will show you how you can generate a word document, and in that document, you can add text and images.

First, we install the new Laravel Project.

Step 1: Install Laravel Project

Download the laravel project by typing the following command in the terminal.

composer create-project --prefer-dist laravel/laravel laravelworddocument

Step 2: Install phpoffice/phpword Package

We will install the phpoffice/phpword package by hitting the following command in cmd.

composer require phpoffice/phpword

Step 3: Build a view file to add the data

Create a file in the resources  >>  views  >>   createdocument.blade.php and put the following code.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Create Word File in Laravel</title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">  
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>  
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
  </head>
  <body>
    <div class="container">
      <h2>Create Word File in Laravel</h2><br/>
      <form method="post" action="{{url('store')}}">
        @csrf
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <label for="Name">Name:</label>
            <input type="text" class="form-control" name="name">
          </div>
        </div>
        <div class="row">
          <div class="col-md-4"></div>
            <div class="form-group col-md-4">
              <label for="Email">Email:</label>
              <input type="text" class="form-control" name="email">
            </div>
          </div>
        <div class="row">
          <div class="col-md-4"></div>
            <div class="form-group col-md-4">
              <label for="Number">Phone Number:</label>
              <input type="text" class="form-control" name="number">
            </div>
          </div>
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <button type="submit" class="btn btn-success">Submit</button>
          </div>
        </div>
      </form>
   </div>
  </body>
</html>

Step 4: Create one controller and route

Generate the controller using the following command.

php artisan make:controller DocumentController --resource

It will create one controller file called DocumentController.php.

We define a route in routes  >>  web.php file. So let us do it.

Route::get('create','DocumentController@create');
Route::post('store','DocumentController@store');

The next step would be to go to the DocumentController.php file and add some into creating () function code.

//DocumentController.php

/**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('createdocument');
    }

After that, we need to start the Laravel Development server. So in the terminal, follow the following command.

php artisan serve

Move to the browser and type this URL:http://localhost:8000/create

Step 5: Create Word Document File

Next, we can save data in a word file and download the word file.

Go to the DocumentController.php file and add some code into the store() function.

public function store(Request $request)
    {
        $phpWord = new \PhpOffice\PhpWord\PhpWord();
        $section = $phpWord->addSection();
        $text = $section->addText($request->get('name'));
        $text = $section->addText($request->get('email'));
        $text = $section->addText($request->get('number'),array('name'=>'Arial','size' => 20,'bold' => true));
        $section->addImage("./images/Krunal.jpg");  
        $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
        $objWriter->save('Appdividend.docx');
        return response()->download(public_path('Appdividend.docx'));
    }

If you are saving a document as an ODF file, then add the following code to save.

public function store(Request $request)
    {
        $phpWord = new \PhpOffice\PhpWord\PhpWord();
        $section = $phpWord->addSection();
        $text = $section->addText($request->get('name'));
        $text = $section->addText($request->get('email'));
        $text = $section->addText($request->get('number'),array('name'=>'Arial','size' => 20,'bold' => true));
        $section->addImage("./images/Krunal.jpg");  
        $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'ODText');
        $objWriter->save('Appdividend.odt');
        return response()->download(public_path('Appdividend.odt'));
    }

If you are saving a document as an HTML file, then add the following code to save.

public function store(Request $request)
    {
        $phpWord = new \PhpOffice\PhpWord\PhpWord();
        $section = $phpWord->addSection();
        $text = $section->addText($request->get('name'));
        $text = $section->addText($request->get('email'));
        $text = $section->addText($request->get('number'),array('name'=>'Arial','size' => 20,'bold' => true));
        $section->addImage("./images/Krunal.jpg");  
        $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'HTML');
        $objWriter->save('Appdividend.html');
        return response()->download(public_path('Appdividend.html'));
    }

In the above screenshot, you can see that we have exported three different formats of the file. That’s it for this tutorial. Thanks for taking it.

5 Comments

  1. I can use a view (like the example “createdocument”) to create my word Document?
    You only use de view to show in PC, but no to create de docx file.

  2. Thanks from Chile!!!,
    It is the only excellent example, which does not put the folder in C: \ Xampp and download a vendor folder where it generates the html of that word, and complicates for those of us who work with github version control, because at least I do not work in C: / Xampp / htdocs, and when moving the project folder I had to create a whole new repository to upload the project, and it was not the idea, very much thanks, God bless you.

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.