How to Generate Word Document (Doc) File in Laravel

In this tutorial you will learn How to Generate Word Document File in Laravel. Many times we need to craete html to doc, docx file from laravel blade.

Here in this example tutorial we have added step by step easy steps for export word file using php function not using any library. We can use the php liabraries like phpword, phpoffice etc to exporting the word document but we can use a simple php code for generating word document file.

Generate Docx File in Laravel PHP

Here is the best step by step guide on how to create/generate docs file in laravel php application.

Step 1: Add Button in Blade File

First we add a button in our laravel blade file for generating the html view page.

<!DOCTYPE html>
<html>
<head>
  <title></title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-10 col-md-offset-1">
            <div class="panel panel-default">
                <div class="panel-heading">Generate Word Document in Laravel</div>
                <div class="panel-body">
                    <a class="btn btn-primary btn-sm pull-right" href="{{ route('export-docx') }}">Download DOC</a>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>

Step 2: Add Route

Now add a routes for exporting data in word document file.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;

Route::get('export-docx', 'UserController@exportDocx')->name('export-docx');

Step 3: Add Code in Controller

Here now we need to add the easiest code in controller for converting html to docx file easily. We have added the static content but you can implement your dynamic data as well for generating data in word document.

    public function exportDocx()
    {
        $filename = 'docfile.doc';
        header("Content-Type: application/force-download");
        header( "Content-Disposition: attachment; filename=".basename($filename));
        header( "Content-Description: File Transfer");
        @readfile($filename);

        $htmlContent = '<html>
                        <head></head>
                        <body>
                        <h1>This is test heading using docx export.</h1>
                        <p>Hello, its a paragraph for testing text docuents</p>
                        </body>
                        </html>';

        // $content = view('users.resume.resume-content', compact('data'))->render();
        echo $htmlContent;
    }

I hope you enjoy with this example, for more follow us on social networks. If you have any questions let me know in comment section.

Leave a Comment