Search code examples
phpsymfonyphpword

How PHPWord return a word response object


My php symfony document download code content, I am downloading PDF and docx, I can get PDF response object as return but can not return a docx response object. here my code for docx download,

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');
    $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("&nbsp", " ", $content);

    header('Content-Type: application/vnd.ms-word');
    header('Content-Disposition: attachment;filename="test.docx"');
    header('Cache-Control: max-age=0');
    $objWriter = PHPWord_IOFactory::createWriter($this->docxBuilder, 'Word2007');
    $objWriter->save('php://output');
}

Word download functionality working but, I want to return a word response object for my REST API, for my above code is being returned null. I searched much about this but could not find How return a php/word response object.


Solution

  • If I understand your question correctly, you want to return a Symfony Response with the file. A Streamed response is best suited for that.

    /**
     * @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("&nbsp", " ", $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;
    }