Download pdf file from a string using Jquery

2019-07-23 21:13发布

问题:

All,

I have a PHP5 application written with Zend Framework and MVC. On my home page, I want to incorporate the functionality to download a dynamically generated pdf file. The way this is done is:

  1. User clicks "download file" link.
  2. On Click, an AJAX call occurs to a PHP controller, which takes the form data, generates the pdf and returns it as a string.
  3. My javascript function now has the pdf string.
  4. How can I display the user an "Open/Save" dialog to download the pdf file from javascript?

I have the following code:

<script type="text/Javascript">
   $('#dlcontent').click(function(e) {
      $.ajax({
                type: 'POST',
                url: "/downloads/dlpolicies",
                data:  $("#frmMyContent").serialize(),
                cache: false,
                dataType: "html",
                success: function(html_input){
                    alert(html_input);  // This has the pdf file in a string.
                    //ToDo: Open/Save pdf file dialog using this string..
                }
            });
});
</script>

Thanks

回答1:

I would try to keep this simple. Just sumbit the form with a target="_blank" and then have PHP force the file download.

HTML CODE

<script type="text/Javascript">
$('#dlcontent').click(function(e) {
  e.preventDefault();
  $("#frmMyContent").submit();
});
</script>

<form id="formMyContent" action="/downloads/dlpolicies" target="_blank" ... >
...
</form>

Then on your server side, you need to tell PHP to send the response as a "download".

PHP Code

$this->getResponse()
  ->setHeader('Content-Disposition', 'attachment; filename=result.pdf')
  ->setHeader('Content-type', 'application/pdf');

Got this from here: Zend Framework how to set headers



回答2:

The simplest way of doing it is open a new window with URL to pdf string.



回答3:

Add an element to your page where you want the link to go. It can be a span or a div or a cell in a table or whatever you want. Give it a unique ID. Then use jQuery to set the html of that element. I refer to it as somepageelement here.

$('#dlcontent').click(function(e) {
      $.ajax({
                type: 'POST',
                url: "/downloads/dlpolicies",
                data:  $("#frmMyContent").serialize(),
                cache: false,
                dataType: "html",
                success: function(html_input){
                    $('#somepageelement').html('<a href="' + html_input + '">Click here to download the pdf</a>');
                }
            });
});