Search code examples
phplaraveldownloadcpu-wordphpword

Laravel PhpWord force download whithout error


I use Laravel 5.3 and phpWord 0.14

I create my word document.

$phpWord = new \PhpOffice\PhpWord\PhpWord();
$section = $phpWord->addSection();
$section->addText( 'Ikerkuntza taldea' , array('name' => 'Tahoma', 'size' => 13, 'bold' => true) );
$phpWord->save('GIE.docx');

It work's and created GIE.docx in public/ folder

But... I want to force the download

I found 2 different form to do it but both of then give me and error when I open the word file from my computer.

$phpWord->save('GIE.docx', 'Word2007', true);

$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save('GIE.docx');

$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
header("Content-Disposition: attachment; filename='GIE.docx'");
$objWriter->save("php://output");

All of them give me a error document corrupted


Solution

  • I found a solution.

    $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
    $objWriter->save("GIE.docx");
    header('Pragma: no-cache');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
    header('Content-Disposition: attachment; filename=GIE.docx;');
    header('Content-Transfer-Encoding: binary');
    header('Content-Length: '.filesize('GIE.docx'));
    readfile('GIE.docx');
    unlink('GIE.docx');