How to download PDF File Generated from TCPDF (PHP) using AJAX (jQuery)?

怎甘沉沦 提交于 2019-12-01 17:05:10

问题


I am using Yii Framework, TCPDF and jQuery to generate a pdf.

The pdf is generated by inputing in a form and submitting it using ajax.

The pdf is created but here is the problem when it returns to the client, it down not download.

here is the php code $pdf->Output('Folder Label.pdf','D');

the jQuery on success function has success: function(data) { window.open(data); }

Which i got from this site.

Can you please help


回答1:


If the problem is that you are not getting the browser's download dialog for the PDF, then the solution is to do it this way:

First, redirect the browser (using window.location as the other answers say) to navigate to a special controller action in your application, e.g. with this url: http://your.application.com/download/pdf/filename.pdf.

Implement the action referenced in the URL like this:

public function actionPdf() {
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="filename.pdf";');
    header('Content-Length: '.filesize('path/to/pdf'));
    readfile('path/to/pdf');
    Yii::app()->end();
}

This will cause the browser to download the file.




回答2:


You need to save the PDF to somewhere on your server and then issue window.location = '/url/to/pdf-you-just-saved.pdf'; from your javascript. The users browser will then prompt them to download the PDF file.




回答3:


Not quite, that will cause errors on some browsers, this is the correct way to set the window location.

window.location.assign( downloadUrlToPdf );

So

  1. Send a request to make the pdf via Ajax to the server
  2. Process and generate the pdf on the server
  3. Return in the Ajax call the url to the file you just made
  4. Use the above code fragment to open a download of said file



回答4:


in tcpdf , just pass this argument the Output method:

$pdf->Output('yourfilename.pdf', 'D'); 

that's all



来源:https://stackoverflow.com/questions/5500485/how-to-download-pdf-file-generated-from-tcpdf-php-using-ajax-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!