如果我正确理解你的问题,你想返回一个Symfony响应文件。流式响应最适合这种情况。
/**
* @Route("/", name="default")
*/
public function index(): Response
{
return $this->exportDocument([], 'test');
}
public function getDocxBuilder()
{
if (is_null($this->docxBuilder)) {
$this->docxBuilder = new \PhpOffice\PhpWord\PhpWord();
}
return $this->docxBuilder;
}
public function setMarginArray($parameterArray, $fileType)
{
$this->name = isset($parameterArray['name']) ? $parameterArray['name'] : 'document';
$pageSize = isset($parameterArray['pageSize']) ? $parameterArray['pageSize'] : 'A4';
$marginLeft = isset($parameterArray['margin_left']) ? $parameterArray['margin_left'] : ($fileType == "PDF" ? '10mm' : 600);
$marginRight = isset($parameterArray['margin_right']) ? $parameterArray['margin_right'] : ($fileType == "PDF" ? '10mm' : 600);
$marginTop = isset($parameterArray['margin_top']) ? $parameterArray['margin_top'] : ($fileType == "PDF" ? '10mm' : 600);
$marginBottom = isset($parameterArray['margin_bottom']) ? $parameterArray['margin_bottom'] : ($fileType == "PDF" ? '10mm' : 600);
return [
'pageSize' => $pageSize,
'name' => $this->name,
'marginLeft' => $marginLeft,
'marginRight' => $marginRight,
'marginTop' => $marginTop,
'marginBottom' => $marginBottom
];
}
public function exportDocument($parameterArray, $content)
{
$pageOption = $this->setMarginArray($parameterArray, $fileType = 'docx');
return $this->getDocx($content, $pageOption);
}
protected function getDocx($content, $sectionStyle)
{
$section = $this->getDocxBuilder()->addSection($sectionStyle);
$content = preg_replace("/<table\s(.+?)>(.+?)<\/table>/is",
"<table style=\"border: 6px #000000 solid;\">$2</table>", $content);
$content = str_replace("<p><div style=' page-break-after:always !important;'></div></p>",
"<pagebreak></pagebreak>", $content);
$content = str_replace(" ", " ", $content);
// The latest version of PHPWord is using IOFactory from the PhpOffice\PhpWord namespace
// instead of the PHPWord_IOFactory, you might want to change it back.
$objWriter = IOFactory::createWriter($this->docxBuilder, 'Word2007');
$response = new StreamedResponse();
// Here we are using the $objWriter in a Callback method.
// This way we can use php://output within a Symfony Repsonse (StreamedResponse)
$response->setCallback(function () use ($objWriter) {
$objWriter->save('php://output');
});
$response->headers->set('Content-Type', 'application/vnd.ms-word');
$response->headers->set('Cache-Control', 'max-age=0');
$disposition = HeaderUtils::makeDisposition(
HeaderUtils::DISPOSITION_ATTACHMENT,
'test.docx'
);
$response->headers->set('Content-Disposition', $disposition);
return $response;
}