3

I hava a backbonejs view containing a button saying "download pdf". I also have the url available where the pdf can be found. I want that when user clicks on the button, the pdf file gets downloaded. Is it possible?

EDIT: My view code in backbone.js

savendownload: function () {
  this.$("#saveanddownload").button('loading');

  var that = this;
  var formData = this.fetchData();
  if (formData) window.invoices.create({
    buyer: formData.buyer,
    items: formData.items,
    company: formData.company,
    action: "savendownload"
  }, {
    wait: true,
    success: function (model) {
      var data = model.toJSON();

      var filename = data.filename;
      //download code here
    }
  });
}
jevakallio
  • 35,324
  • 3
  • 105
  • 112
beNerd
  • 3,314
  • 6
  • 54
  • 92
  • Possible duplicate: http://stackoverflow.com/questions/3077242/force-download-a-pdf-link-using-javascript-ajax-jquery – Chris Mar 02 '13 at 09:45

2 Answers2

2

Don't use a button, use a link and set the href attribute to the URL of your PDF file. The browser will handle the file download for you, honoring the user's browser preferences.

<a href="your/file.pdf" />

If you need the link to look like a button, you can style it using CSS. See for example this SO thread.

Edit: AFAIK, you can't reliably initialize a file download from javascript. What you can do is to open a new window/tab with your pdf URL:

window.open("http://domain.com/document.pdf",'_blank');

But the user's browser can block the new window from being created. You might want to simply generate a download link:

$('<a>Click here to download PDF</a>').attr('href', filename).appendTo(that.$el);

And have the user click the link to initiate the file download.

Community
  • 1
  • 1
jevakallio
  • 35,324
  • 3
  • 105
  • 112
  • @beNerd, you should've probably included that in your original question... anyway, edited the answer. No silver bullet. – jevakallio Mar 02 '13 at 10:51
  • This will work, but the responding server will also need to set the Content-Disposition header to "attachment" if you want to force a download: http://stackoverflow.com/questions/8875949/how-to-implement-content-disposition-attachment – Ben Mar 02 '13 at 10:58
  • @Ben, true, but I think it makes more sense to let the browser make the decision. That's what user in most cases expects, and they can `Save link as...` if they want to force a download themselves. – jevakallio Mar 02 '13 at 11:03
0

use the "download" tag

<a href="assets/pdfs/yourdocument.pdf" download>Download PDF</a>

but does not wok at IE Explorer ;)

Murat Kezli
  • 187
  • 2
  • 5