jsPDF Incomplete or corrupt PNG file

纵饮孤独 提交于 2021-01-28 04:38:17

问题


Adding regular png images was no problem with jsPDF, but now i send a generated image from my server and the browser console displays this error when rendering the PDF file:

Incomplete or corrupt PNG file

obviously the image is not incomplete or corrupt because i can see the response from the server and the image is fine. Also to avoid render the pdf file before the image is ready i make a check to a that holds the image value variable if is undefined/null. the format of my image is

var image = "data:image/png;base64,iVBORw0KGgoAAAANSUh...etc";

What could be the problem?

Edit: i changed the format of the image to jpg and this error shows

Supplied data is not a JPEG

if i use this library jspdf.plugin.addimage.js the images are rendered correctly but not the png images.

edit: 2 i made a solution modifying the jspdf.plugin.addimage.js file function addImage, i just changed the name of the function and added those generated images to pdf with that function, since the version of jspdf.min.js has the same name for the same function with this way it won't override the function i can use the one that works with normal images and the ones generated by the server.


回答1:


This type of error occurs because the image has not finished loading when you send to jsPdf, use onLoad event to check the image loaded completely. for Example -

 /* where src = full image url
        callback = is callback function
        outputFormat = image output format */
    function toDataUrl(src, callback, outputFormat) {
                var img = new Image();
                img.setAttribute('crossOrigin', 'anonymous');
                img.onload = function () {

                   /*image completely converted to base64string */
                    var canvas = document.createElement('CANVAS');
                    var ctx = canvas.getContext('2d');
                    var dataURL;
                    canvas.height = this.height;
                    canvas.width = this.width;
                    ctx.drawImage(this, 0, 0);
                    dataURL = canvas.toDataURL(outputFormat);

                    /* call back function */
                    callback(dataURL);
                };
                img.src = src;
                if (img.complete || img.complete === undefined) {
                    img.src = appConfig.config.dummyImage;
                    img.src = src;
                }
            }



  function callbackBase64(base64Img)
    {
           /*base64Img contains full base64string of image   */
           console.log(base64Img);
    }

call above function and get base64string of image -

toDataUrl('http://example1.com/image1.jpg', callbackBase64(base64Img), "image/png");


来源:https://stackoverflow.com/questions/35561225/jspdf-incomplete-or-corrupt-png-file

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