jsPDF: Incomplete or corrupt PNG file

I’m trying to add an image to my PDF document but get this error Uncaught Error: Incomplete or corrupt PNG file in this line doc.addImage(imgData, 'PNG', 15, 40, 180, 160); , this happens when I add imgData var to my PDF file but not when i add imgPDF var for test.

Any idea cuz this happens

        var zip = new JSZip();
        var img = zip.folder("documets").folder("products");
        var row = "txtRow";

        var imgData = value['data'];
        var imgPDF = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAIAAAA7ljmRAAAAGElEQVQIW2P4DwcMDAxAfBvMAhEQMYgcACEHG8ELxtbPAAAAAElFTkSuQmCC';

        var doc = new jsPDF('landscape');

        doc.text(20, 20, 'This is the default font.');
        doc.addImage(imgData, 'PNG', 15, 40, 180, 160);

        var pdf = doc.output();

        imgData = imgData.replace(/^data:image\/(png|jpg);base64,/, '');
        img.file("file.png", imgData, {base64: true});
        img.file("file.pdf", pdf,{binary: true});



    zip.file("products.csv", row);
    var content = zip.generate({type:"blob"});
    //FileSaver.js
    saveAs(content, "csv.zip");

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Comments: 21

Most upvoted comments

This happens because the image has not finished loading when you send it to jsPDF. You can ensure your image has finished loading before adding it to the document like this:

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');. };.

Hrannar

I’m getting this issue as well, using Base64 which is fully loaded. It’s not consistent either, some images cause it and some don’t

En pocas palabras el error se debe a que la librería jsPDF no trabaja muy bien con imagenes PNG muy grandes, entonces cambia de formato la imagen que traes del servidor a JPEG y utiliza la version version .min