我正在尝试加载动态生成的多个图像。我想将这些图像转换为PDF格式。
以下是HTML代码:
<html>
<body>
<input type='submit' id='test' style='align:center' value='Generate'>
</body>
</html>
使用jspdf生成pdf的脚本是:
<script>
window.onload = function(){
var t = document.getElementById("test");
t.addEventListener("click", sayHi, false);
function sayHi(){
var getImageFromUrl = function(url, callback) {
var img = new Image();
img.onError = function() {
alert('Cannot load image: "'+url+'"');
};
img.onload = function() {
callback(img);
};
img.src = url;
}
var doc = new jsPDF();
var length = <?php echo count($items); ?>; /* $items id from php which is an array of items */
var cnt=0; /* using this variable to get the end of the loop */
<?php
foreach($items as $item)
{?>
cnt++;
getImageFromUrl('http://localhost:800/prod/chart.php?period=<?php echo $timeperiod; ?>&stime=<?php echo $startingtime; ?>&itemids=<?php echo $item->itemid; ?>&type=0&updateProfile=1&profileIdx=web.item.graph&width=1222&screenid=&curtime=1442486527893', function(imgData) {
doc.addImage(imgData, 'JPEG', 10, 10, 150, 75);
/* Initiall tried here to save pdf file and as a result n number of pdf's are downloading with same image */
/* doc.save('out.pdf'); */
}
);
<?php
}
?>
if(cnt==length)
{
/* after trying in for loop i tried here as a result i got only one pdf but with out images */
doc.save('out.pdf');
}
}
}
</script>
以下是我尝试的方法:
提前感谢您的帮助。
答案 0 :(得分:2)
请参考此示例以获取一张图像,并为多张图像执行相同的操作:
var img = new Image();
img.onload = function () {
var dataURI = getBase64Image(img);
return dataURI;
}
img.src = "../Images/UW_DriveLogo.jpg";
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/jpeg");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
然后你可以简单地调用load方法:
doc.addImage(img.onload(), 'PNG', doc.internal.pageSize.width - 75, 0, 75, 75);