Search code examples
javascripthtmlbase64pngjspdf

Unable to add base64 png images to JSPDF Javascript


 function save_pdf() {
 var doc = new jsPDF();  
 var imgSampleData ='data:image/png;base64,/9j/4AAQSkZJRgABAAEA8ADwAAD/2w...';
 doc.addImage(btoa(imgSampleData), 'PNG', 15, 40, 175, 75);
 doc.save('MCR.pdf');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.debug.js"></script>

When I pass base64 strings from one of the webservices I am unable to add these base64s to images of JSPDF below is the error I get in IE

Incomplete or corrupt PNG file

enter image description here

I have attached entire base64 String of whole image. This Base64 works fine and able to see images if I use any online conversion tool.

Attachement base64 png string

What could be the reason why JSPDF unable to parse this type of base64 strings and other seems to parse the String Successfully?


Solution

  • The Base64 Data of Image is JPEG, So was the error.

    var imgSampleData ='data:image/jpeg;base64,/9j/4AAQSkZJRgABAAEA8ADwAAD/2w...';
    

    data:image/png has to be changed to data:image/jpeg and JSPDF fails to recognise that if the Data is jpeg and fails at the above line. I raise an issue with JSPDF Reagrding this.