Funsaized
Funsaized

Reputation: 2140

How to concatenate two pages with html2canvas and jsPDF

I am trying to create a multi-page PDF document.

I am doing so by using html2canvas to capture a JPEG of each page. Each JPEG is then added as a new page to the pdf. The gist of the code is below (inspiration from this article here):

var pdf = new jsPDF('p', 'mm', 'a4', true);

html2canvas(document.getElementById("image_1")).then(canvas => {
    pdf.addImage(canvas.toDataURL('image/jpeg'), 'JPEG', 0, 0, 210, 297, 'FAST');
    html2canvas(document.getElementById("image_2")).then(canvas2 => {
        pdf.addPage();
        pdf.addImage(canvas2.toDataURL('image/jpeg'), 'JPEG', 0, 0, 210, 297, 'FAST');
        pdf.save();

    });
});

I would expect the output would have the contents of the element with id="image_1" on the first page and the contents of the element with id="image_2" on the second page. However, instead, I get a PDF with the contents of the element with id="image_1" on BOTH the first and second page...

I wonder if something is being overwritten/not getting written, but from my perspective, I can't see how that would be happening. Any help would be appreciated.

Upvotes: 1

Views: 1218

Answers (1)

Funsaized
Funsaized

Reputation: 2140

Not sure why the above nested promise structure didn't work. I refactored it to the following and am seeing success. Basically I create promises for each canvas element and add those to the PDF after they are resolved:

  getCanvasData = element => {
    return new Promise((resolve, reject) => {
      html2canvas(element, { scale: 2, logging: true })
        .then(function(canvas) {
          resolve(canvas.toDataURL("image/jpeg"));
        })
        .catch(function(error) {
          reject(
            "Error while creating canvas for element with ID: " + element.id
          );
        });
    });
  };

  promisePrint = () => {
    var pdf = new jsPDF({
      orientation: "p",
      unit: "mm",
      format: "a4",
      compression: true
    });

    let pageIds = ["page1", "page2", "page3", "page4"];
    let promises = [];
    pageIds.forEach(page => {promises.push(this.getCanvasData(document.getElementById(page)));
});

    Promise.all(promises).then(dataUrls => {
    dataUrls.forEach((dataUrl, i) => {
        pdf.addImage(dataUrl, "JPEG", 0, 0, 210, 297, undefined, "FAST");
        pdf.addPage();
      });
      pdf.save("testingPromises")
    });
  };

Upvotes: 1

Related Questions