Html2canvas for each div export to pdf separately

html2canvas, javascript

Solution

On angular 2(now 6) framework. u can use the logic as below,

- On click execute `generateAllPdf()` function,

- gather all `6 id's` from my html collection,

- iterate through each `id` and call `html2canvas` function,

- as `html2canvas` runs in background to process images, i m using `await` on function,

- after the `html2canvas` completes its process, i ll save the document,

- If suppose i wont use `await` i ll end-up in downloading an empty page.

below is my code logic,

// As All Functions in js are asynchronus, to use await i am using async here
 async generateAllPdf() {
    const doc = new jsPDF('p', 'mm', 'a4');
    const options = {
      pagesplit: true
    };
    const ids = document.querySelectorAll('[id]');
    const length = ids.length;
    for (let i = 0; i < length; i++) {
      const chart = document.getElementById(ids[i].id);
      // excute this function then exit loop
      await html2canvas(chart, { scale: 1 }).then(function (canvas) { 
        doc.addImage(canvas.toDataURL('image/png'), 'JPEG', 10, 50, 200, 150);
        if (i < (length - 1)) {
          doc.addPage();
        }
      });
    }
    // download the pdf with all charts
    doc.save('All_charts_' + Date.now() + '.pdf');
  }

Problem

I have Page, It has 6 div with same class name "exportpdf", I am converting those div into pdf using jspdf and html2canvas ``` var elementTobePrinted = angular.element(attrs.selector), iframeBody = elementTobePrinted.contents().find('div.exportpdf'); ``` In html2canvas..... ``` html2canvas(elementTobePrinted, { onrendered: function (canvas) { var doc = new jsPDF(); for(var i=1;i<elementTobePrinted.length;i++){ doc.addImage(canvas.toDataURL("image/jpeg"), 'jpeg', 15, 40, 180, 160); doc.addImage(canvas.toDataURL("image/jpeg"),'JPEG', 0, 0, 215, 40) doc.addPage(); } doc.save(attrs.fileName); } ``` I converted page to canvas.its create same div contents for whole pdf. I need each div contents into same pdf with different pages. Can anyone help me? The problem is with html2canvas: ``` doc.addImage(canvas.toDataURL("image/jpeg"), 'jpeg', 15, 40,180, 160); ``` Here I need to pass `elementTobePrinted` list to addImage.

Original source