Symfony2 PHPWord 响应 [英] Symfony2 PHPWord response
本文介绍了Symfony2 PHPWord 响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 PHPWord 包在 Symfony2 上生成 docx 文档.
I am trying to generate a docx document on Symfony2, using the PHPWord bundle.
在我的控制器中,我成功返回了一个 docx 文件,但它是空的,我认为它来自我的错误响应格式.
In my controller, I succeed in returning a docx file, but it is empty, I think it comes from my faulty response format.
public function indexAction($id)
{
$PHPWord = new PHPWord();
$section = $PHPWord->addSection();
$section->addText(htmlspecialchars(
'"Learn from yesterday, live for today, hope for tomorrow. '
. 'The important thing is not to stop questioning." '
. '(Albert Einstein)'
));
// Saving the document
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($PHPWord, 'Word2007');
return new Response($objWriter->save('helloWorld.docx'), 200, array('Content-Type' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'));
}
推荐答案
非常感谢您的回答.
我使用第二种方法实现,在我看来这是最好的.我只需要返回一个响应,否则文件已生成,但卡在 web 目录中.使用此响应,一切正常,并出现下载提示,其中包含完整"文件.
I achieve using the 2nd method, which is in my opinion the best. I just have to return a response, otherwise the file was generated, but stuck in the web directory. Using this response, everything was fine and a download prompt appeared, with the "full" file.
这是我的代码:
$PHPWord = new PHPWord();
$section = $PHPWord->addSection();
$section->addText(htmlspecialchars(
'"Learn from yesterday, live for today, hope for tomorrow. '
. 'The important thing is not to stop questioning." '
. '(Albert Einstein)'
));
// Saving the document
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($PHPWord, 'Word2007');
$filename="MyAwesomeFile.docx";
$objWriter->save($filename, 'Word2007', true);
$path = $this->get('kernel')->getRootDir(). "/../web/" . $filename;
$content = file_get_contents($path);
$response = new Response();
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
$response->headers->set('Content-Disposition', 'attachment;filename="'.$filename);
$response->setContent($content);
return $response;
这篇关于Symfony2 PHPWord 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文