title: Rearrangement of pages when creating paginated pdf using html2canvas (async)
body: <p>I have a dynamic page which depending on some information will create more or less sections. I want to loop through those, make a canvas out of them and bring those sections to a pdf.
  I had the page previously running with this code, but i had to change the sections.</p>
  <pre><code>var pagina  = 0;
  var paginas_totales = parseInt('&lt;?= $pagina ?&gt;');
  var doc = new jsPDF({
      orientation: &quot;landscape&quot;,
      unit: &quot;mm&quot;,
      format: [297, 238]
  });
  $('.generate').on('click', function() {
      nextStep();
  });
  function generaDescarga() {
      pagina++;
      if(pagina == paginas_totales) {
          doc.save('Report &lt;?= html_entity_decode($dataSampling['samp_name']) ?&gt;.pdf');
          window.scrollTo(0,0)
      } else {
          nextStep()
      }
  }
  var j = -1;
  function nextStep(){
      j++;
      if(j &gt;= paginas_totales) return;
      $('#loader .contenedor_loader span').text(`Creando página ${j + 1} / ${paginas_totales}`)
      //Fix imagen cut
      document.querySelector(&quot;.page-&quot;+j).scrollIntoView()
      setTimeout(() =&gt; {
          html2canvas(
              document.querySelector(&quot;.page-&quot;+j), 
              {
                  // allowTaint: true,
                  backgroundColor:&quot;#0d3451&quot;,
                  scale: 2,
                  userCORS: true,
                  onrendered: function(canvas) {
                      var imgData = canvas.toDataURL(&quot;image/jpeg&quot;, 1.0);
                      doc.addImage(imgData, 'JPEG', 0, 0);
                      if (j != paginas_totales - 1) {
                          doc.addPage();
                      }
                      generaDescarga();
                  }
              }
      
          ).then(canvas =&gt; {// document.body.appendChild(canvas)}
          );
      }, 10);
  }
  </code></pre>
  <p>From here i got plenty of errors, most of them because the asyncronity of the library of html2canvas where i am struggling.</p>
  <p>My actual code looks like this</p>
  <pre><code>    var paginas_totales = parseInt('&lt;?= $pagina ?&gt;');
  rendered =0;
  $('.generate').on('click', function() {
      showLoading();
      var doc = new jsPDF({orientation: &quot;landscape&quot;,unit: &quot;pt&quot;,format: [1125, 900]});
      //Generation of empty structure
      for (let i = 1; i &lt; paginas_totales; i++) {doc.addPage();}
      doc.save('Report &lt;?= $dataSampling['samp_name'] ?&gt;.pdf');
      for (let i = 0; i &lt;paginas_totales ; i++) {
          var div_renderizar = document.querySelector(&quot;.page-&quot;+i);
          if (div_renderizar != null){
              generateCanvas( doc, i, div_renderizar ,function() {
                  rendered++;
                  if (rendered &gt;= paginas_totales){
                      doc.save('Report.pdf');
                      hideLoading();
                  }
              });
          }else{
              console.log(&quot;Failing page &quot;+i);
              hideLoading();
          }
      }
  });
  
  function generateCanvas(doc, i, div_renderizar, callback){
      html2canvas(
          div_renderizar,
          {   allowTaint: true, 
              scale: 2,
              userCORS: true
          }
      ).then(function (canvas){
          let imgData = canvas.toDataURL(&quot;image/jpeg&quot;, 1.0);
          doc.setPage(i);
          doc.addImage(imgData, 'JPEG', 0, 0); 
      }).catch( error =&gt;  {
          console.error(&quot;Falló generateCanvas=&gt; &quot;+error);
          console.log(new Error().stack);
          hideLoading();
      });
      callback();
  }
  </code></pre>
  <p>Where im getting blank pages in the pdf.</p>
  <p>At this point i've already managed to get a pdf with all pages but i get it in a random* order, which i guess is due the asyncronity of the library (lighter pages go first)
  I've tried adding &quot;async&quot; and &quot;await&quot;.
  I've updated the libraries to a CDN for both html2canvas and jsPDF
  I've tried lots of tutorials like
  <a href="https://solveforum.com/forums/threads/solved-html2canvas-and-jspdf-rendering-multiple-divs-blank-pdfs.197029/" rel="nofollow noreferrer">https://solveforum.com/forums/threads/solved-html2canvas-and-jspdf-rendering-multiple-divs-blank-pdfs.197029/</a>
  <a href="https://www.freakyjolly.com/html2canvas-multipage-pdf-tutorial/" rel="nofollow noreferrer">https://www.freakyjolly.com/html2canvas-multipage-pdf-tutorial/</a>
  but most of them focus on static page or pagination depending on height
  I've tried different approaches suggested on other SO pages like
  <a href="https://stackoverflow.com/questions/47632710/html2canvas-creating-multiple-divs">HTML2Canvas creating multiple divs</a>
  <a href="https://stackoverflow.com/questions/45523620/html2canvas-screenshot-keeps-turning-up-blank">html2canvas screenshot keeps turning up blank</a>  (this one because it was generating blank pages)</p>
  <p>But the ORDER on the pages go crazy and the log isn't helping, is just telling me that the error is in this function, or in the .min external file, but not what i need.</p>
  <p>So what i need is</p>
  <ol>
  <li>Create pdf object</li>
  <li>Loop for elements like $(&quot;.page-&quot;+i) from 0 to last index</li>
  <li>Add page for element</li>
  <li>Create canvas for that element and insert that IN ORDER into the pdf</li>
  <li>Download/Preview the results</li>
  </ol>
  <p>The html structure is working perfect, having some pdfs being correctly generated proves this.
  Both html2canvas and jsPDF are correctly installed/configured
  The issue im sure its between point 2 and 4.</p>
  <p>Hope its clear enough. Thank you for all help, really stuck on this, i have tried a lot of approaches, but i wanted to be readable.</p>