Problem with called an action via ajax and use mpdf

Hello,

I have a somewhat complicated problem. I called an action in yii2 with an ajax function. This works fine. Put there is no output from mdpf. If i called the action directly it works fine. The reason is that I don’t want the action function to be able to be run directly from a url. I only want to allow this via ajax function. Is there maybe another way?

My Ajax-Function is

function generatePTA(site) {
    $.ajax({
        url: site+'downloadpdf',
        dataType: 'JSON',  
        data: "",
        type: 'post',
        success: function(){                      
        },
        complete: function() {
        },
    });                
}

And my action is

    public function actionDownloadpdf() {
        if (Yii::$app->request->getIsAjax()) {
        $content = "Test";
        $pdf = Yii::$app->pdf;
        $pdf->content = $content;
        $pdf->filename='test.pdf';
        $pdf->output($pdf->content,$pdf->filename,'D');

        return;
    }
    }

Not sure about the AJAX part, but for the PDF output I would use sendContentAsFile.

Yii::$app->response->sendContentAsFile($pdf->content,$pdf->filename, $options = [] )

For options, you can specify inline, if that is what you require and the required MIME type. Not sure if that is what $pdf->output does that anyway!

For testing I would remove the getIsAjax check.

This is the same. Yii always open a new window with the PDF-Document. It seems a problem from yii.

First of all:
You cannot send / download files to the browser via Ajax requests. Those will never be able to receive / download file content directly - their accepted content type is json, not a file.

There are only 2 ways to achieve that

  1. you return the url to that file to the browser, create a link and open that
  2. you encode your content and decode it via js in your frontend but that will make the file many times larger and the request takes longer.

So I would suggest method 1.
You should place the content of your PDF somewhere and create a 2nd controller action with your send File function.

Another thing: your browser decides what to do with downloaded content. You can’t force it to download it directly. If your browser settings are to display the content there is no way for yii or any server script to download it instead.

1 Like

Thank you so much for your information. Now I have solved it by saving the PDF in the database. The customer can now open and download their PDF document via a link in their dashboard. The Document can only downloaded when the User is logged in, and he can only download his own Document. Not Documents from others. This solution has been the best for me.