3

I have some link to PDFs given in a table inside a webpage, I want to download all of them via javascript, what do I do?

Edit:

Clearly speaking, I have a webpage here, I just look at it inside a browser, and I want to do some javascript that it automatically dwonloads all PDFs inside a specific table, that's all.

Michael Lee
  • 467
  • 5
  • 14

4 Answers4

4

Assuming your pdf links are enclosed in <a> tags having href attribute. You can do something like this.

var links = document.getElementsByTagName('a');
// Do this selection based on your table

for(var count=0; count<links.length; count++) {
    var url = links[count].getAttribute('href');
    if(url && url.endsWith('.pdf')) {
        links[count].dispatchEvent(new MouseEvent('click'));
    }
}

For not opening pdf in browser itself you will have to disable this in browser. For chrome go to chrome://plugins and disable pdf viewer. Also if the number of pdfs to download is large, add some timeInterval between consecutive downloads. I hope this helps

kumardeepakr3
  • 395
  • 6
  • 16
  • Nice work. For adding `sleep` intervals see [here](https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep/39914235#39914235). – LoMaPh Nov 07 '18 at 23:06
4

Well finally I have got a way to do the task properly, see my fiddle if you want to look further at it. This script automatically do everything as required by my previous problem, and it forces pdf download without disabling the viewer.

code:

(function(ElementTypeToDownload, DownloadFromWhere) {

  // from http://stackoverflow.com/questions/3077242/force-download-a-pdf-link-using-javascript-ajax-jquery and http://stackoverflow.com/questions/16611497/how-can-i-get-the-name-of-an-html-page-in-javascript
  // Anonymous "self-invoking" function
  if (!(typeof jQuery === 'function')) {
    (function() {
      var startingTime = new Date().getTime();
      // Load the script
      var script = document.createElement("SCRIPT");
      script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
      script.type = 'text/javascript';
      document.getElementsByTagName("head")[0].appendChild(script);

      // Poll for jQuery to come into existance
      var checkReady = function(callback) {
        if (window.jQuery) {
          callback(jQuery);
        } else {
          window.setTimeout(function() {
            checkReady(callback);
          }, 20);
        }
      };

      // Start polling...
      checkReady(function($) {
        $(function() {
          var endingTime = new Date().getTime();
          var tookTime = endingTime - startingTime;
        });
      });
    })();
  }
  // http://facebook.com/anders.tornblad
  // anders.tornblad@gmail.com

  // from http://stackoverflow.com/questions/3077242/force-download-a-pdf-link-using-javascript-ajax-jquery
  function SaveToDisk(fileURL, fileName) {
    // for non-IE
    if (!window.ActiveXObject) {
      var save = document.createElement('a');
      save.href = fileURL;
      save.target = '_blank';
      save.download = fileName || fileURL.split("/").pop() || 'unknown';

      var evt = new MouseEvent('click', {
        'view': window,
        'bubbles': true,
        'cancelable': false
      });
      save.dispatchEvent(evt);

      (window.URL || window.webkitURL).revokeObjectURL(save.href);
    }

    // for IE < 11
    else if (!!window.ActiveXObject && document.execCommand) {
      var _window = window.open(fileURL, '_blank');
      _window.document.close();
      _window.document.execCommand('SaveAs', true, fileName || fileURL)
      _window.close();
    }
  }

  // from http://stackoverflow.com/questions/4623982/test-if-jquery-is-loaded-not-using-the-document-ready-event
  function preInit() {
    // wait until jquery is loeaded
    if (!(typeof jQuery === 'function')) {
      window.setTimeout(function() {
        //console.log(count++);
        preInit();
      }, 10); // Try again every 10 ms..
      return;
    }

    $(ElementTypeToDownload || prompt("Enter the type of element you are going to download, e.g. 'a' for link, 'img' or 'image' for images (do not add quotes, deafult is 'a') ") || 'a', DownloadFromWhere || prompt("jQuery Selector for the place that you want to download content from, e.g. '#DivName', '.ClassName', 'TagName', body by deafult") || 'body').each(function() {
      var tag = (ElementTypeToDownload == 'img' || ElementTypeToDownload == 'image') ? 'src' : 'href';
      SaveToDisk($(this).attr(tag));
    });
  }

  preInit();
})();

Anyway thank you for you guys helping

Michael Lee
  • 467
  • 5
  • 14
  • If you already had worked it out, then why ask? – kumardeepakr3 Nov 19 '16 at 19:55
  • 1
    I asked because I found don't figure out how to achieve the result, but I found it when I have searched and combined multiple SO questions, so I made one on my own. Anyway big thanks for your help. – Michael Lee Nov 19 '16 at 20:05
1

There is a simple solution with JavaScript

HTML:

<button id="download" name="download" type="button" onclick="download()">Some Text</button>

JavaScript:

function download() {
    window.open("file_1.txt");
    window.open("file_2.txt");
}
Zer0
  • 1,580
  • 10
  • 28
1

Create a button below your data to click it. on click all pdf files will start downloading.

Please make sure that multiple download is restricted in your browser. in chrome once you click on the download all button you have to make sure that you click allow in the popup blocker which will be shown in the right side of your address bar

function clickall(){
  var pdfs = document.getElementsByClassName('mydata')[0].getElementsByTagName('a');
  for(var i=0; i<pdfs.length; i++) {
    pdfs[i].setAttribute("download", "download");
    pdfs[i].click();
  }
}

function excuteDomReadyCallBacks(){
  var mydata=document.getElementsByClassName('mydata')[0];
  var element = document.createElement('button');
                element.onclick = 'clickall()';
                element.value = 'download all';
                element.type = 'button';
  mydata[0].parent.insertAfter(element, mydata);
  }
  document.addEventListener('DOMContentLoaded', function() {
excuteDomReadyCallBacks();
    //.. do stuff ..
}, false);
<table class="mydata">
<tbody>
<tr>
<td><b>Name</b></td>
<td><b>City</b></td>
<td><b>State</b></td>
</tr>
<tr>
<td>Greater Noida Cricket Stadium</td>
<td>Greater Noida</td>
<td>
  <a href="http://static.sportskeeda.com/wp-content/uploads/2016/08/hero-isl-2016-fixtures-1472219010.pdf">test2</a>
  </td>
</tr>
<tr>
<td>    Buddh International Circuit</td>
<td>Greater Noida</td>
<td>
  <a href="/test2.pdf">test2</a>
</td>
</tr>
<tr>
<td>    Buddh International Circuit</td>
<td>Greater Noida</td>
<td>
  <a href="http://www.omri.org/sites/default/files/opl_pdf/CompleteCompany-NOP.pdf">test2</a>
</td>
</tr>
</tbody>
</table>
jafarbtech
  • 6,842
  • 1
  • 36
  • 55