Skip to content Skip to sidebar Skip to footer

Getting Image On Page 1 Of 2 Page Pdf

I am creating an image with html2canvas and with jsPDF with Angular4. I want to place this image on page 1 of a 2 page generated pdf. But it seems that the line, doc.save('test.p

Solution 1:

Of course you can access that variable. The problem is that each function creates its own scope and defines this as a link to its own context, so the html2canvas then-callback's this is not the same as generatePDF function's this. This is a part of basic paradigm of javascript as a functional language.

The simplest solution is to save the context in a local variable:

generatePDF() {
  var self = this;
  console.log("outside: self.problem.length = " + self.problems.length);

  html2canvas(document.getElementById('graph')).then(function(canvas) {
    console.log("inside: self.problem.length = " + self.problems.length);
    // ...
  });
  // ...
}

Another option is to use ES arrow function (in case of ES6 is appropriate for your project; and I guess it's so due to Angular 4) because the arrow function saves the parent context:

generatePDF(){
  console.log("outside: this.problem.length = " + this.problems.length);

  html2canvas(document.getElementById('graph')).then((canvas) => {
    console.log("inside: this.problem.length = " + this.problems.length);
    // ...
  });
  // ...
}

Not sure if it's all the story, but hope this helps!


Solution 2:

This function is asynchronous:

html2canvas(document.getElementById('graph'))

You can have access to the generated image only inside the callback function. If are going to use html2canvas to generate images, then all your pdf-related code must be inside the callback. It's really what you already did. If you're going to need another images in pdf, you'll have more nested callbacks and this line doc.save('test.pdf'); must be inside the last one.


Post a Comment for "Getting Image On Page 1 Of 2 Page Pdf"