cesarvr / pdf-generator

Cordova plugin to generate pdf in the client-side
MIT License
107 stars 61 forks source link

Usage in a loop #24

Closed davidtweaver closed 7 years ago

davidtweaver commented 7 years ago

Hello again,

I want to use this plugin in a loop like this:


  var index = 0;
    while (index < this.screeningReports.length) {
      console.log('INDEX', index);
      this.toast.show("exporting..." + index, '500', 'top')
        .subscribe(toast => { console.log('toast ', toast); });
      this.printToPDF(index)
      console.log('is this code ever reached?, returned')
      index += 1;
    }

where printToPDF() looks like this:

  printToPDF(index) {
    console.log('in func print', index)
    let content = document.getElementById(String(index)).innerHTML
    let fullReportDate = new Date(this.screeningReports[index].answers.date)
    let reportDate = fullReportDate.getDate() + '-' + (fullReportDate.getMonth() + 1) + '-' + fullReportDate.getFullYear();
    let fileName = this.screeningReports[index].nhs + '_' + reportDate + '.pdf'
    //generate the pdf.
    cordova.plugins.pdf.htmlToPDF({
      data: content,
      type: "base64"
    },
      (success) => {
        console.log('success: ', success), this.toast.show("exporting...", '1500', 'top')
          .subscribe(toast => { console.log('toast ', toast); });
        let thisFile = this.b64toBlob(String(success));
        this.file.writeFile(this.file.documentsDirectory, fileName, thisFile, false).then(_ => console.log('Should have successfully created file')).catch(err => console.log('File not created'));
      },
      (error) => console.log('error:', error)
    );
  }

but on the first iteration of the loop the plugin seems to halt the rest of the loop on execution. Could you tell me how I could use the plugin in a loop?

cesarvr commented 7 years ago

Each time you call the cordova.plugins.pdf.htmlToPDF method he makes an offscreen webkit object and iOS/Android takes control stoping JS VM, so for what I see here I think you are better constructing the HTML pages first with the amount of page required and the just make one call to the plugin to generate a PDF for you.

davidtweaver commented 7 years ago

Hmm, what I really need to do is generate multiple PDFs rather than one though.

I've tried passing an array of HTML content to the plugin, but that didn't work either

davidtweaver commented 7 years ago

Ah, I fixed the problem! - in the end I had to recursively call my printPdf function from inside itself for every​ div tag to get multiple PDFs. It worked fine that way, it's maybe not the most efficient way to do it but it works