【发布时间】:2015-12-16 12:58:18
【问题描述】:
我正在尝试加载动态生成的多个图像。我想把这些图片转换成 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>
以下是我尝试过的方法:
- 尝试生成将所有图像保留在 div 标签中并使用该 div 标签生成 PDF。
- Thought图片同步加载,决定等到图片创建完成再生成PDF。这次我只得到一个 PDF,但没有图像。
- 尝试将图像转换为 base 64 并显示,但没有成功
提前感谢您的帮助。
【问题讨论】:
-
这里的问题是我正在覆盖图像。只要我在 doc.addImage 函数中更改 X 和 Y 坐标,它就会工作。但是 Jspdf 占用了很多空间。对于 48 页,它需要接近 15MB,这是非常高的。需要努力减小尺寸。感谢所有为此工作的人。