error:Incomplete or corrupt PNG file in using jspdf

心不动则不痛 提交于 2021-02-07 19:24:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!