Question

I'm trying to generate a ms-word document with Yii. I'm finding very difficult to do it. I found this example Generating ms-word but I cannot get it to work.

View:
echo CHtml::ajaxLink(
    'Generate Word',
    CController::createUrl('Calculator/generateWord'), array(
        'type'    => 'POST',
    ), array('id'=>'gen_word')
);

Controller:
$var = "hello";
$div = $this->renderPartial('graphs/print', array('var'=>$var), true);
header("Pragma: no-cache"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false); // required for certain browsers
header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment; filename=\"test.doc");
header("Content-Transfer-Encoding: binary");
ob_clean();
flush();
echo $div;

graphs/print:
<table>
    <tr>
        <td>This is just s test</td>
    </tr>
    <tr>
        <td><?php echo $var; ?></td>
    </tr>
</table>

When I click on the link "Generate Word" it doesn't do anything.

Was it helpful?

Solution

Correction. This is the way it must be done. The problem was that I was doing an Ajax call. Instead by using a simple link there are no problems.

View:
echo CHtml::link('Generate Word', array('Calculator/generateWord'));

Controller:
    public function actionGenerateWord() {
    $var = "Hello World!";
    $div = $this->renderPartial('graphs/word', array('var'=>$var), true);
    header("Pragma: no-cache");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private", false);
    header("Content-type: application/vnd.ms-word");
    header("Content-Disposition: attachment; filename=\"test.doc");
    header("Content-Transfer-Encoding: binary");
    ob_clean();
    flush();
    echo $div;
    Yii::app()->end();
}

Rendered view:
<table>
    <tr>
        <td>This is just a test</td>
    </tr>
    <tr>
        <td><?php echo $var; ?></td>
    </tr>
</table>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top