0

I have a local DB table in which many PDF links are saved around 15000. I want to download all that PDF on one click but my problem is its opening PDF not downloading. I was trying this method.

items = Array.from(document.getElementsByTagName("a"));
items.forEach(function(item) {
    link = item.href;
    if (link.substr(link.length - 4) == ".pdf") {
        filename = link.replace(/^.*[\\\/]/, '');
        item.download = filename;
        item.click();
    }
});
James Z
  • 12,209
  • 10
  • 24
  • 44
  • 1
    Do tag it properly, you have coded it up in JS it pops up under the php tag. – damagedCoda Feb 27 '19 at 05:23
  • Possible duplicate of [How to download PDF automatically using js?](https://stackoverflow.com/questions/34691525/how-to-download-pdf-automatically-using-js) – damagedCoda Feb 27 '19 at 05:24

2 Answers2

4

You can not download all files using only 1 click. Instead of You can use ZIP Archive Class in PHP.

Make one zip file of all available pdf and download it.

$files = array('pdf1.pdf','pdf2.pdf');
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);

  foreach ($files as $file) {
    $zip->addFile($file);
  }

  $zip->close();

And Headers Like

header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
Parth Sureliya
  • 255
  • 5
  • 19
  • its download a zip file but display no archive found during extract. $files = array('https://assets.supply.com/ul_pdfs/309006_SpecSheet.pdf','https://assets.supply.com/ul_pdfs/574955_SpecSheet.pdf'); $zipname = 'file.zip'; $zip = new ZipArchive; $zip->open($zipname, ZipArchive::CREATE); foreach ($files as $file) { $zip->addFile($file); } $zip->close(); header('Content-Type: application/zip'); header('Content-disposition: attachment; filename='.$zipname); header('Content-Length: ' . filesize($zipname)); readfile($zipname); did i miss anything. – Sohan Singh Feb 27 '19 at 05:26
0

Thanks for your reply, this code works for me with zip archive

$files = array('pdflink','pdflink');
$zip = new ZipArchive();
$tmp_file = tempnam('.','');
$zip->open($tmp_file, ZipArchive::CREATE);

foreach($files as $file){
    $download_file = file_get_contents($file);
    $zip->addFromString(basename($file),$download_file);
}   
$zip->close();
header('Content-disposition: attachment; filename=file.zip');
header('Content-type: application/zip');
readfile($tmp_file);

?>