在 2 页 pdf 的第 1 页获取图像

Getting image on page 1 of 2 page pdf

我正在使用 html2canvas 和带有 Angular4 的 jsPDF 创建图像。我想将此图像放在生成的 2 页 pdf 的第 1 页上。

不过好像行,

 doc.save('test.pdf');

需要在 htm2canvas() 之后的函数内部。因为如果我把它放在外面,它不会在 pdf 中包含图像。

generatePDF(){
      var doc = new jsPDF();
      doc.text(50,90,this.problems.length.toString());
      doc.text(50,100,'page 1')
      doc.addPage();
      doc.text(50,100,'page 2')
      html2canvas(document.getElementById('graph')).then(function(canvas) {
        var img = canvas.toDataURL("image/png");
        doc.addImage(img, 'JPEG', 100, 100);
        doc.save('test.pdf');
    });
    // doc.save('test.pdf');//fails to add image to pdf
  }

我无法将 addPage() 放在 html2canvas() 之后,因为当调用 html2canvas 时会生成 pdf 并且之后的任何内容都不会被包含。

似乎唯一的办法就是像这样把jsPDF放在html2canvas()里面,

  generatePDF(){
    html2canvas(document.getElementById('graph')).then(function(canvas) {
      var doc = new jsPDF();
      doc.text(50,100,'page 1')
      var img = canvas.toDataURL("image/png");
      doc.addImage(img, 'JPEG', 100, 100);
      doc.addPage();
      doc.text(50,100,'page 2')
      doc.save('test.pdf');
    });

这确实有效。

但问题是我不能从外部使用变量,当在内部时 html2canvas(),像这样。

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

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

      var doc = new jsPDF();
      doc.text(50,100,'page 1');
      var img = canvas.toDataURL("image/png");
      doc.addImage(img, 'JPEG', 100, 100);
      doc.addPage();
      doc.text(50,100,'page 2')
      doc.save('test.pdf');
    });
    // doc.save('test.pdf');//fails to add image to pdf
  }

package.json 有 html2canvas 和 jspdf 的类型:

...
"@types/html2canvas": "^0.5.35",
"@types/jspdf": "^1.1.31",
"@types/lodash": "^4.14.74",
"html2canvas": "^0.5.0-beta4",
"jspdf": "^1.3.5",
...

完整代码在githubhere,相关代码在第428行app.component.ts底部注释掉。

可能的解决方案

这个函数是异步的:

html2canvas(document.getElementById('graph'))

您只能在回调函数中访问生成的图像。如果要使用 html2canvas 生成图像,那么所有与 pdf 相关的代码都必须在回调中。这真的是你已经做过的。如果您需要其他 pdf 格式的图像,您将有更多的嵌套回调,并且这一行 doc.save('test.pdf'); 必须在最后一个内。

您当然可以访问该变量。问题是每个 function 创建自己的范围并将 this 定义为 link 到自己的上下文,因此 html2canvas then-callback 的 this 与 generatePDF 不同函数的 this。这是 javascript 作为函数式语言的基本范例的一部分。

最简单的解决方案是将上下文保存在局部变量中:

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);
    // ...
  });
  // ...
}

另一种选择是使用 ES 箭头函数(如果 ES6 适合您的项目;我猜这是由于 Angular 4),因为箭头函数保存了父上下文:

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);
    // ...
  });
  // ...
}

不确定这是否是故事的全部,但希望对您有所帮助!