PHPWord generate file from template and send it to ajax

61 Views Asked by At

I work with PHP 7 and PHP Word. I generate a file using a Word template and save it to my app's main folder. The PHP file that is generating the word file is triggered by an ajax call like this:

 $.ajax({
    type: 'POST',
    url: 'generatefile.php',
    data: {
            
            ...:...
        }, 
    dataType: 'json',
    beforeSend: function () {
       $('.loading-overlay').show();
    },
    success: function (html) {
       
    }
}).done(function(data){
    var a = data.file;
    $( ".clickbutton").attr('href',a).css('visibility', 'visible');
    $( ".clickbutton").attr('download','GSO Housing report.docx');
    }
});

What I've used for PHPExcel and it was working is this (in the PHP file):

$writer = PHPExcel_IOFactory::createWriter($spreadsheet, 'Excel5');  
       ob_start();
       $writer->save('php://output');
       $xlsData = ob_get_contents();
       ob_end_clean();
       $response =  array(
            'op' => 'ok',
            'file' => "data:application/vnd.ms-excel;base64,".base64_encode($xlsData)
        );
        die(json_encode($response));

And this is working like a charm. In PHPWord (for .docx documents), I am trying this:

$writer = new \PhpOffice\PhpWord\TemplateProcessor("./myfile.docx");
     ob_start();
     $writer->save('php://output');
     $docData = ob_get_contents();
     ob_end_clean();
      $response =  array(
            'op' => 'ok',
            'file' => "data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,".base64_encode($docData)
        );
        die(json_encode($response));

but in the front-end I get a blank Word file. Any ideas?

Thank you in advance

0

There are 0 best solutions below