php – Generate Word File in Laravel PHPWord – problem with add blade-ThrowExceptions

Exception or error:

I am beginner in Laravel. I use in my project Laravel 5.8.

I have this code for generate Word file:

$phpWord = new \PhpOffice\PhpWord\PhpWord();
        $month = $request->input('month');
        if ($month == null) {
            $now = Carbon::now();
            $month = $now->month;
        $events = $this->frontendGateway->getEventCalendarDownload($request, $month);
        $logo = public_path('assets/images/logo3.jpg');
        $view_content = View::make('', ['events' => $events, 'logo' => $logo])->render();
        $section = $phpWord->addSection();
        $text = $section->addText('aaaaaaaa');
        $text = $section->addText('bbbbbbbbbb');
        $text = $section->addText('ccccccccccc');
        $text = $section->addText($view_content);

        $fileName = 'Event_calendar' . '-' . now()->toDateString() . '.doc';
        $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');

        header('Content-Type: application/octet-stream');
        header("Cache-Control: no-cache, must-revalidate");
        header("Pragma: no-cache");
        header("Content-Disposition: attachment; filename=$fileName");

and this is my Blade file:

<div id="header" class="fontSize14">
    <table width="100%">
            <td align="left" style="width: 20%;">
                <img src="{{ $logo }}" class="logo" />
            <td align="left" style="width: 80%;">
                <span class="fontSize19"><b>my name</b></span><br />
                street<br />

<div id="content" class="fontSize11">
    <b class="fontSize19">Kalendarz wydarzeń</b><br /><br />

    <table width="100%">
        <thead style="background-color: lightgray;">
                <th>Nazwa imprezy</th>
            @foreach($events as $event)
                $hourFromX = explode(":", $event->hour_from);
                $hourToX = explode(":", $event->hour_to);
                $hourFrom = $hourFromX['0'].":".$hourFromX['1'];
                $hourTo = $hourToX['0'].":".$hourToX['1'];
                <th scope="row">{{ $loop->iteration }}</th>
            <td>{{ $event->date_from }}</td>
            <td align="left">{{ $hourFrom }}-{{ $hourTo }}</td>
            <td align="left">{{ $event->title }}</td>
            <td align="left">@if(isset($event->localization)) {{ $event->localization->name }},
                {{ $event->localization->city }}
                {{ $event->localization->street }} @endif</td>


When I run this code, I have error: Word file is corrupted.

When I comment this line:

$text = $section->addText($view_content);

Word file is okey. Generated file was open in Word without any problems.

How can I repair it?

How to solve:

Can you try adding addHtml instead of addText

\PhpOffice\PhpWord\Shared\Html::addHtml($section, $view_content , false, false);

Leave a Reply

Your email address will not be published. Required fields are marked *