问题
I am trying to convert an html into a pdf using jsPDF. However, the variable and things that happen inside a function seem to be invisible to everything outside of the function. Here is my code:
$(document).ready(function()
{
$("#runpdf").click(function(event)
{
var doc = new jsPDF();
var imageData;
html2canvas($("#page1"),
{
logging:true,
profile:true,
allowTaint:true,
letterRendering: true,
onrendered:function(canvas)
{
imageData= canvas.toDataURL("image/jpeg");
doc.addImage(imageData, 'JPEG', 0, 0, 200, 200);
}
});
doc.save('test.pdf');
});
});
Upon running this, a blank page is rendered, notably that everything within the function html2canvas
did not actually affect var doc
. However, upon putting the doc.save('test.pdf');
bit inside the function (after doc.addImage()
), it executes fine with the page being rendered. However, I cannot do this because I am going to use a for-each loop to execute the html2canvas
function multiple times on multiple pages and then at the end, save the document. But this won't work because it seems that the doc.save()
needs to be in the same function as the rest. How can I avoid this problem?
Thanks
Edit: Problem fixed using a counter and simple if statement.
var doc = new jsPDF("p", "pt", "letter");
$(document).ready(function ()
{
$("#runpdf").click(function (event)
{
$(document.body).width(1903);
var count=0;
$("section").each(function()
{
$(this).children('footer').children('article').append($(document.createElement('span')).text((count+1)+".").css("float","right").css("font-weight", "900").css("font-size","150%"));
count++;
});
var pages = $(".page5");
var remaining = pages.length;
pages.each(function ()
{
html2canvas($(this),
{
logging: true,
profile: true,
allowTaint: true,
letterRendering: true,
onrendered: function (canvas)
{
var imageData = canvas.toDataURL("image/jpeg");
doc.addImage(imageData, 'JPEG', -425, 0, 1450, 800);
remaining--;
if (remaining === 0)
{
doc.save('test.pdf');
}
doc.addPage();
}
});
});
});
});
Thanks for the help, everybody
回答1:
You need to put your save after you've added the image:
html2canvas($("#page1"),
{
logging:true,
profile:true,
allowTaint:true,
letterRendering: true,
onrendered:function(canvas)
{
imageData= canvas.toDataURL("image/jpeg");
doc.addImage(imageData, 'JPEG', 0, 0, 200, 200);
doc.save('test.pdf');
}
});
The onrendered function is a callback and will be executed once the image is rendered. In your code the save is being called prior to the image being added.
回答2:
then you can save at onrendered
onrendered:function(canvas)
{
imageData= canvas.toDataURL("image/jpeg");
doc.addImage(imageData, 'JPEG', 0, 0, 200, 200);
doc.save('test.pdf');
}
来源:https://stackoverflow.com/questions/24369519/var-not-affected-outside-of-function