Search code examples
phplaravellaravel-livewirephpword

Download PHPWord File with laravel livewire without save file


i'm trying to download a file generated with PHP Word, but i'll generate around of 10 000 files daily, i need to download file with laravel livewire without save the file in storage, someone could help me?

This is my code:

public function downloadDoc()
    {
        $phpWord = new \PhpOffice\PhpWord\PhpWord();
        
        $section = $phpWord->addSection();
        $html = \PhpOffice\PhpWord\Shared\Html::addHtml($section, nl2br(strip_tags($this->result, '<strong>')));
        $text = $section->addText("Que onda chavo");

        $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
        $name = time().rand();
        try {
            $objWriter->save(storage_path('document'.$name.'.docx'));
        } catch (Exception $e) {

        }
        return response()->download(storage_path('document'.$name.'.docx'));
    }

Solution

  • The key solution here is you should use

    $objWriter->save("php://output");
    

    To echo data to php output and then use Response::stream to output as file

    public function downloadDoc()
    {
        $callback = function()
        {
            $phpWord = new \PhpOffice\PhpWord\PhpWord();
        
            $section = $phpWord->addSection();
            $html = \PhpOffice\PhpWord\Shared\Html::addHtml($section, nl2br(strip_tags($this->result, '<strong>')));
            $text = $section->addText("Que onda chavo");
    
            $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
            
            try {
                $objWriter->save("php://output");
            } catch (Exception $e) {
    
            }
        };
        
        $name = time().rand();
        
        $file = 'document'.$name.'.docx';
        $headers = array(
            "Content-type" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
            "Content-Disposition" => "attachment; filename=".$file,
            "Pragma" => "no-cache",
            "Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
            "Expires" => "0"
        );
        
        
        return Response::stream($callback, 200, $headers)->send();
    }