Using template in PHPWord

In this tutorial we’ll use template capability of PHPWord library. Sometimes you just want to generate a document by changing few fields in it. In this case, using template is suitable than generating whole document programmatically. Let’s build a Laravel 8 app which outputs docx file using template.

You can start by creating a fresh Laravel app by entering following command:

composer create-project laravel/laravel app 8.*

Now install PHPWord by executing the following command inside project directory:

composer require phpoffice/phpword

In Laravel, there is a convenient way of handling a complex controller action – by creating a Single Action Controller. This type of controller contains single method __invoke() and can be called by controller name only without mentioning the method name. So, let’s create a Single Action Controller for generating document:

php artisan make:controller Document --invokable

Now, open the newly created file Document.php in app/Http/Controllers/ folder and enter the following code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use PhpOffice\PhpWord\TemplateProcessor;

class Document extends Controller
{
    public function __invoke(Request $request)
    {
        $templateProcessor = new TemplateProcessor('template.docx');
        $templateProcessor->setValue('firstname', 'Sohail');
        $templateProcessor->setValue('lastname', 'Saleem');
        $templateProcessor->saveAs('Result.docx');
    }
}

Now, create a template file by creating new blank file in MSWord. Insert following line in this document file and save it as template.docx in public/ folder of the app.

Hello ${firstname} ${lastname}

Finally, open routes/web.php and put the following line at the top of it:

use App\Http\Controllers\Document;

And then insert following route into this web.php:

Route::get('/document', Document::class)->name('document');

Run Laravel development server by executing:

php artisan serve

Enter the following URL in your browser:

localhost:8000/document

Result.docx” file has been generated and saved in public folder of the project.

Leave a Comment