简体   繁体   中英

Download PDF resource from PHP to Javascript via Ajax

So I will explain the problem:

Steps:

1) client (browser javascript) sends an Ajax request to the server that hits a controller method called download.

2) the controller's method creates a PDF resource(without saving on the filesystem), and returns a response with the PDF binary stream back to the client.

3) the client receives the PDF binary stream and download it on the client's computer. Is that possible?

Code: Things I have already tried -

Client-side:

<script>
    (function($) {

        var button; // some random DOM button

        button.on('click', function(e) {
            e.preventDefault();

            $.ajax({
                url: "/download/:userId"
                method: "POST",
                dataType: "json"
                success: function(response) {
                    var reader = new FileReader;
                    var file = new Blob([response.pdf_stream], 'application/pdf');

                    // create a generic download link
                    var a = $('<a/>', {
                        href: file,
                        download: response.filename
                    });

                    // trigger click event on that generic link.
                    a.get(0).click(); 
                }
            });
        }

    })(jQuery);


</script>

On the server-side:

class Controller
{
     public function download($userId)
     {
         // fetching the user from the database
         $user = User::find($userId);

         // creating a pdf file using barry pdfdom package
         // this will actually parse an HTML view and give us the PDF blob.
         $pdf = PDF::loadView('pdf.view')->output();

         // using Laravel helper function
         return response()->json([
             'pdf_stream' => utf8_encode($pdf),
             'filename' => 'blahblah.pdf"
         ]);

        // Or if you will in native PHP, just in case you don't use laravel.
        echo json_encode([
             'pdf_stream' => utf8_encode($pdf),
             'filename' => 'blahblah.pdf"
        ]);
     }
}

Any Idea what am I doing wrong here? How could I download that PDF file without saving it to the system (security and space concerns).

Any help would be appreciated.

Eden

If you want download pdf on client side, just open this pdf in new window. Use GET request for that things, like in RESTfull application (eg download/user/:id or somehow like that).

Could be useful: Download and open pdf file using Ajax

The main problem is the returned response from controller. Try this:

public function download($userId)
     {
      // fetching the user from the database
      $user = User::find($userId);

      // creating a pdf file using barry pdfdom package
      // this will actually parse an HTML view and give us the PDF blob.
      $pdf = PDF::loadView('pdf.view')->output();
      return response($pdf, 200,
        [
          'Content-Type'   => 'application/pdf',
          'Content-Length' =>  strlen($pdf),
          'Cache-Control'  => 'private, max-age=0, must-revalidate',
          'Pragma'         => 'public'
        ]
      );

About calling the route which executes download($userid) method:

You do not have to use Ajax. Easy way:

<a href="/path/to/download/1" target="_blank">Click view PDF</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM