Search code examples
javascriptpdfzipjszip

Save zip of pdf in folder with jszip


i don't get how to properly use jsZip.. i'm trying to get a file from a folder in localhost then zip it and at last save the zipped file in the same folder...

but really i don't have good comprension on how to use it

here what i have done :

        JSZipUtils.getBinaryContent("http://localhost:8100/pdf/test.pdf", function (err, data) {
      if(err) {
          alert('err');
          throw err;
      }
      else{
        zip.file("test.pdf",data,{binary:true})
        .then(function (blob) {
            saveAs(blob, "pdf.zip");
        });
      }  
    });

can anibody help me?


Solution

  • The following bit of code is what ended up working for me.

    NB, this is for jszip utils version 3. It needs filesaver.js to make the saveAs call work (https://github.com/eligrey/FileSaver.js).

    Here's my code:

    function create_zip(){
        // get checked file urls
        var urls = Array();
        $("input:checked").each(function () {
            urls.push($(this).siblings('a').attr('href'));
        })
    console.log(urls);
    
        var zip = new JSZip();
        var count = 0;
        var zipFilename = "archive.zip";
    
        urls.forEach(function(url){
          var filename = url.substr(url.lastIndexOf("/")+1);
    console.log(filename);
          // loading a file and add it in a zip file
          JSZipUtils.getBinaryContent(url, function (err, data) {
             if(err) {
                throw err; // or handle the error
             }
             zip.file(filename, data, {binary:true});
             count++;
    
            if (count == urls.length) {
               zip.generateAsync({type:'blob'}).then(function(content) {
                  saveAs(content, zipFilename);
               });
            }
          });
        });
    };
    

    This is adapted from the info here: https://gist.github.com/noelvo/4502eea719f83270c8e9

    Hope it helps!