Laravel PhpWord强制下载没有错误

时间:2018-02-14 08:27:30

标签: php laravel download word phpword

我使用Laravel 5.3和phpWord 0.14

我创建了word文档。

export class SomeComponent2 {
    public data = {};

    public constructor(private myService: MyService) {
        this.myService.myMethod$.subscribe((data) => {
                this.data = data; // And he have data here too!
            }
        );
    }
}

它工作并在公共/文件夹

中创建了GIE.docx

但是......我想强制下载

我找到了两种不同的形式,但是当我从计算机上打开word文件时,两者都给了我错误。

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

所有这些都给我一个错误文件已损坏

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。

$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');