问题
I want to add 2 images in my pdf
when i click "create-pdf" icon.
First image is a canvas that convert to image and it correctly work.
var canvas = document.getElementsByClassName("jade-schematic-diagram");
img = canvas[0].toDataURL("image/png");
img.id="pic2";
doc = new jsPDF({
unit:'px',
format:'a4'
});
doc.addImage(img, 'JPEG', 20, 20,400,150);
This section of my code got this error:
Error: Incomplete or corrupt PNG file
var srcpath;
var element = $(".plot-waveforms"); // global variable
var imgageData = new Image();
imgageData.id = "pic";
html2canvas(element, {
onrendered: function (canvas) {
srcpath = canvas.toDataURL("image/png");
}
});
imgageData.src=srcpath;
doc.addImage(imgageData , 'PNG', 20, 20,400,150);
I was added these script in my html head tag.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="//cdn.rawgit.com/niklasvh/html2canvas/0.5.0-alpha2/dist/html2canvas.min.js"></script>
<script type="text/javascript" src="//cdn.rawgit.com/MrRio/jsPDF/master/dist/jspdf.min.js"></script>
<script type="text/javascript" src="zlib.js"></script>
<script type="text/javascript" src="png.js"></script>
<script type="text/javascript" src="addimage.js"></script>
<script type="text/javascript" src="png_support.js"></script>
Please help me. I searched a lot but i don't find anything.
回答1:
onrendered
is an async function, isn't it? https://github.com/niklasvh/html2canvas/issues/470
So you have to place srcpath
inside onrendered
html2canvas(element, {
onrendered: function (canvas) {
srcpath = canvas.toDataURL("image/png");
imgageData.src=srcpath;
doc.addImage(imgageData , 'PNG', 20, 20,400,150);
}
});
回答2:
The image has not finished loading when you send it to jsPDF. So in order to ensure that the image has finished loading before adding it to the document, Add this to your code :
var myImage = new Image();
myImage .src = 'https://www.myserver.com/somepath/myImage.png';
myImage .onload = function(){
doc.addImage(myImage , 'png', 5, 5, 40, 10);
doc.save('myPDF.pdf');
};
来源:https://stackoverflow.com/questions/38264135/errorincomplete-or-corrupt-png-file-in-using-jspdf