在第2页的第1页获取图像pdf [英] Getting image on page 1 of 2 page pdf
问题描述
我正在使用html2canvas和Angular4的jsPDF创建图像.我想将此图像放置在2页生成的pdf的第1页上.
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.
但是似乎这行,
doc.save('test.pdf');
需要紧接在htm2canvas()
之后的函数内.因为如果我将其放置在该位置之外,它将不会在pdf中包含该图像.
needs to be inside the function just after htm2canvas()
. Because if I place it outside this it will not include the image in the 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,之后将不包含任何内容.
I can't place the addPage()
after the html2canvas()
, because when html2canvas
is called that generates the pdf and nothing after it will be included.
似乎唯一的方法是像这样将jsPDF
放在html2canvas()
内,
Seems the only way is to put the jsPDF
inside the html2canvas()
like this,
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()
内部时,我不能像这样从外部使用变量.
But then the problem is that I can't use a variable from outside, when inside html2canvas()
, like this.
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的类型:
package.json has the types for html2canvas and 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",
...
完整代码位于此处在github上,第428行的app.component.ts
底部注释了相关代码.
The full code is here on github, with the relevant code commented out at the bottom of app.component.ts
on line 428.