Search code examples
javascripthtmljspdf

error:Incomplete or corrupt PNG file in using jspdf


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.


Solution

  • 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);
        }
    });