英文:
jsPDF generating two pdf files
问题
以下是您提供的代码的中文翻译部分:
(function($) {
$(document).ready(function() {
$('#downloadPDF').click(function() {
var doc = new jsPDF("p", "mm", "a4");
function getDataUri(url, callback) {
var image = new Image();
image.onload = function() {
var canvas = document.createElement('canvas');
canvas.width = this.naturalWidth; // 或 'width',如果您需要特定/缩放大小
canvas.height = this.naturalHeight; // 或 'height',如果您需要特定/缩放大小
canvas.getContext('2d').drawImage(this, 0, 0);
// 获取原始图像数据
callback(canvas.toDataURL('image/png').replace(/^data:image\/(png|jpg);base64,/, ''));
// ... 或者获取数据URI
callback(canvas.toDataURL('image/png'));
};
image.src = url;
}
// 使用方法
getDataUri('/cover.png', function(dataUri) {
console.log('RESULT:', dataUri);
doc.addImage(dataUri, 'png', 0, 0, 210, 297, undefined, 'FAST');
doc.save('download.pdf');
});
})
})
})(jQuery)
如果您需要进一步的帮助,请随时提问。
英文:
I'm using the code below to create a PDF of an image when the user clicks the "download" button. It's almost working fine but the problem is that it’s generating two PDF files instead of one.
(function($) {
$(document).ready(function() {
$('#downloadPDF').click(function() {
var doc = new jsPDF("p", "mm", "a4");
function getDataUri(url, callback) {
var image = new Image();
image.onload = function() {
var canvas = document.createElement('canvas');
canvas.width = this.naturalWidth; // or 'width' if you want a special/scaled size
canvas.height = this.naturalHeight; // or 'height' if you want a special/scaled size
canvas.getContext('2d').drawImage(this, 0, 0);
// Get raw image data
callback(canvas.toDataURL('image/png').replace(/^data:image\/(png|jpg);base64,/, ''));
// ... or get as Data URI
callback(canvas.toDataURL('image/png'));
};
image.src = url;
}
// Usage
getDataUri('/cover.png', function(dataUri) {
console.log('RESULT:', dataUri);
doc.addImage(dataUri, 'png', 0, 0, 210, 297, undefined, 'FAST');
doc.save('download.pdf')
});
})
})
})(jQuery)
I think it’s a loop, but I can't figure out how to solve it.
答案1
得分: 0
你似乎在两个地方调用了 callback
,一次在注释 // Get raw image data
之后,另一次在 // ... or get as Data URI
之后。根据你的需求,删除其中一个调用,问题应该会解决。
英文:
You seem to be calling callback
twice, once after the comment // Get raw image data
and another time after // ... or get as Data URI
. Remove one of the calls depending which case you want and it should solve the problem.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论