dimanche 11 juillet 2021

corrupted docx file when reading and replacing contents of docx file using PHPWord

I am using "phpoffice/phpword": "^0.18.2" with "php": "^7.3|^8.0" to replace particular contents of docx file. I have tried the following code to replace and download the contents of docx file.

        $file = public_path('assets/dist/sample.docx');

        $phpword = new \PhpOffice\PhpWord\TemplateProcessor($file);
        $phpword->setValue('firstname', 'John Doe');
        $phpword->setValue('shareholderNumber', '5');
        $phpword->setValue('address', 'Newyork');
        header("Content-Description: File Transfer");
        header('Content-Disposition: attachment; filename=test.docx');
        header('Content-Type: application/docx');
        header('Content-Transfer-Encoding: binary');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Expires: 0');
        $phpword->saveAs(public_path('assets/dist/test.docx'));
        return response()->download(public_path('assets/dist/test.docx'));

The above code downloads the doc file but when opened it just displays we can't open test.docx because we found a problem with its contents. Anyone help me to replace contents of docx file and download the docx file with replaced contents in laravel. My sample docx file contains the following contents:

कम्पीको नाम अंग्रेजीमा: ${name}
शेयरधनीको संख्या: ${shareholderNumber}
अख्तीयार वालाको ठेगाना: ${address}


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire