GauthamK
GauthamK

Reputation: 188

Is there a way to save multiple jsPDF outputs into an single ZIP using jsZIP?

I use jsPDF to generate multiple PDFs. Is there a way for me to save all the PDFs as a single ZIP through jsZIP?

Upvotes: 5

Views: 4646

Answers (2)

basklein
basklein

Reputation: 395

For anyone coming here to find a more direct answer to this question, I have this example:

var zip = new JSZip();

angular.forEach ($scope.students, function (student) {
//The createFile() function returns a jsPDF
    var doc = createFile(student);
    if (typeof doc !== 'undefined') {
        try {
            zip.file(student.name + '.pdf', doc.output('blob'));
        }
        catch {
            console.error('Something went wrong!');
        }
    }
});

zip.generateAsync({type:'blob'}).then(function(content) {
    saveAs(content, 'reports.zip');
});

Basically, zip.file() adds a new file to the zip with (name, data). You add the jsPDF document as a blob by calling doc.output('blob'). Don't forget to add '.pdf' at the end of the name.

Then you generate a zip file by calling the zip.generateAsync() function and save it when it finishes generating.

In this example I used jsPDF, JSZip and FileSaver.js

Upvotes: 8

TheTechy
TheTechy

Reputation: 172

Does this help? https://gist.github.com/noelvo/4502eea719f83270c8e9

var zip = new JSZip();
var count = 0;
var zipFilename = "zipFilename.zip";
var urls = [
  'http://image-url-1',
  'http://image-url-2',
  'http://image-url-3'
];

urls.forEach(function(url){
  var filename = "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) {
       var zipFile = zip.generate({type: "blob"});
       saveAs(zipFile, zipFilename);
     }
  });
});

Upvotes: 0

Related Questions