Search code examples
javascriptangularblobjszip

Pdf download from url, save it in a file, zip then download the zip


Have been using jszip to create and download the zip file. I am able to download the pdf file separately. but I want to download these pdf into the zip folder and then download the zip file.

code snippet to download the pdf:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       window.location.href = "pdf_url"
    }
};
xhttp.open("GET", "pdf_url");
xhttp.send();

adding the zip api to it:

    var zip = new JSZip();
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
           window.location.href = "pdf_url"
           zip.file("file_name", pdf_url_content);
        }
    };
    xhttp.open("GET", "pdf_url");
    xhttp.send();

creating zip :

  zip.generateAsync({type:"blob"})
    .then(function callback(blob) {
      saveAs(blob, "example.zip");
    }

the pdf_url_content should have the content of the url. how to read that content? I tried using jszip-utils. Not able to proceed. any help would be appreciated.

Thanks in advance.


Solution

  • First, it would be useless to zip the pdf, because the user will download it un-zipped with the xmlhttprequest then zipped, so he will have to download the file twice for nothing.

    I answered anyway for your information

    You should set the proper content-type to your xmlhttprequest, and the responseType to blob. Then you can access the content of the pdf using the property response inside the onreadstatechange callback

    var zip = new JSZip();
    var xhttp = new XMLHttpRequest();
    xhttp.open("GET", "pdf_url");
    xhttp.responseType = "blob";
    xhttp.setRequestHeader("Content-type", "application/pdf");
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
           zip.file("file_name", xhttp.response);
           zip.generateAsync({type:"blob"})
              .then(function(blob) {
                   saveAs(blob, "example.zip");
              });
        }
    };
    
    xhttp.send();
    

    Note that you need FileSaver.js for the downloading part (saveAs function).